From eeeba86d38ce0cdb374865f5222903768eb5dc24 Mon Sep 17 00:00:00 2001 From: JC5 Date: Fri, 23 Jan 2026 15:14:29 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=96=20Auto=20commit=20for=20release=20?= =?UTF-8?q?'develop'=20on=202026-01-23?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Autocomplete/AccountController.php | 12 +- .../Autocomplete/BillController.php | 2 +- .../Autocomplete/BudgetController.php | 2 +- .../Autocomplete/CategoryController.php | 2 +- .../Autocomplete/CurrencyController.php | 4 +- .../Autocomplete/PiggyBankController.php | 10 +- .../Autocomplete/RecurrenceController.php | 2 +- .../Autocomplete/RuleController.php | 2 +- .../Autocomplete/RuleGroupController.php | 2 +- .../Autocomplete/TransactionController.php | 10 +- .../Controllers/Chart/AccountController.php | 62 +-- .../Controllers/Chart/BalanceController.php | 15 +- .../V1/Controllers/Chart/BudgetController.php | 80 ++-- .../Controllers/Chart/CategoryController.php | 40 +- app/Api/V1/Controllers/Controller.php | 40 +- .../Data/Bulk/TransactionController.php | 2 +- .../V1/Controllers/Data/DestroyController.php | 50 +-- .../Data/Export/ExportController.php | 5 +- .../V1/Controllers/Data/PurgeController.php | 2 +- .../Insight/Expense/AccountController.php | 12 +- .../Insight/Expense/BillController.php | 20 +- .../Insight/Expense/BudgetController.php | 14 +- .../Insight/Expense/CategoryController.php | 14 +- .../Insight/Expense/PeriodController.php | 14 +- .../Insight/Expense/TagController.php | 36 +- .../Insight/Income/AccountController.php | 16 +- .../Insight/Income/CategoryController.php | 14 +- .../Insight/Income/PeriodController.php | 14 +- .../Insight/Income/TagController.php | 38 +- .../Insight/Transfer/AccountController.php | 2 +- .../Insight/Transfer/CategoryController.php | 10 +- .../Insight/Transfer/PeriodController.php | 14 +- .../Insight/Transfer/TagController.php | 38 +- .../Models/Account/ListController.php | 56 +-- .../Models/Account/ShowController.php | 36 +- .../Models/Account/StoreController.php | 14 +- .../Models/Account/UpdateController.php | 18 +- .../Models/Attachment/DestroyController.php | 2 +- .../Models/Attachment/ShowController.php | 31 +- .../Models/Attachment/StoreController.php | 10 +- .../Models/Attachment/UpdateController.php | 8 +- .../Models/AvailableBudget/ShowController.php | 34 +- .../Models/Bill/ListController.php | 53 +-- .../Models/Bill/ShowController.php | 32 +- .../Models/Bill/StoreController.php | 14 +- .../Models/Bill/UpdateController.php | 14 +- .../Models/Budget/ListController.php | 78 ++-- .../Models/Budget/ShowController.php | 34 +- .../Models/Budget/StoreController.php | 14 +- .../Models/Budget/UpdateController.php | 14 +- .../Models/BudgetLimit/DestroyController.php | 2 +- .../Models/BudgetLimit/ListController.php | 25 +- .../Models/BudgetLimit/ShowController.php | 40 +- .../Models/BudgetLimit/StoreController.php | 22 +- .../Models/BudgetLimit/UpdateController.php | 18 +- .../Models/Category/ListController.php | 37 +- .../Models/Category/ShowController.php | 32 +- .../Models/Category/StoreController.php | 12 +- .../Models/Category/UpdateController.php | 14 +- .../DestroyController.php | 2 +- .../CurrencyExchangeRate/IndexController.php | 2 +- .../CurrencyExchangeRate/ShowController.php | 16 +- .../CurrencyExchangeRate/StoreController.php | 26 +- .../CurrencyExchangeRate/UpdateController.php | 4 +- .../Models/ObjectGroup/DestroyController.php | 2 +- .../Models/ObjectGroup/ListController.php | 46 +-- .../Models/ObjectGroup/ShowController.php | 18 +- .../Models/ObjectGroup/UpdateController.php | 8 +- .../Models/PiggyBank/ListController.php | 56 +-- .../Models/PiggyBank/ShowController.php | 32 +- .../Models/PiggyBank/StoreController.php | 12 +- .../Models/PiggyBank/UpdateController.php | 14 +- .../Models/Recurrence/ListController.php | 27 +- .../Models/Recurrence/ShowController.php | 24 +- .../Models/Recurrence/StoreController.php | 14 +- .../Models/Recurrence/TriggerController.php | 28 +- .../Models/Recurrence/UpdateController.php | 14 +- .../Models/Rule/DestroyController.php | 2 +- .../Models/Rule/ShowController.php | 22 +- .../Models/Rule/StoreController.php | 8 +- .../Models/Rule/TriggerController.php | 18 +- .../Models/Rule/UpdateController.php | 10 +- .../Models/RuleGroup/DestroyController.php | 2 +- .../Models/RuleGroup/ListController.php | 18 +- .../Models/RuleGroup/ShowController.php | 22 +- .../Models/RuleGroup/StoreController.php | 10 +- .../Models/RuleGroup/TriggerController.php | 22 +- .../Models/RuleGroup/UpdateController.php | 8 +- .../Models/Tag/DestroyController.php | 2 +- .../Controllers/Models/Tag/ListController.php | 39 +- .../Controllers/Models/Tag/ShowController.php | 22 +- .../Models/Tag/StoreController.php | 8 +- .../Models/Tag/UpdateController.php | 8 +- .../Models/Transaction/DestroyController.php | 4 +- .../Models/Transaction/ListController.php | 44 +- .../Models/Transaction/ShowController.php | 40 +- .../Models/Transaction/StoreController.php | 34 +- .../Models/Transaction/UpdateController.php | 29 +- .../TransactionCurrency/DestroyController.php | 2 +- .../TransactionCurrency/ListController.php | 151 +++---- .../TransactionCurrency/ShowController.php | 30 +- .../TransactionCurrency/StoreController.php | 8 +- .../TransactionCurrency/UpdateController.php | 30 +- .../TransactionLink/DestroyController.php | 2 +- .../Models/TransactionLink/ShowController.php | 22 +- .../TransactionLink/StoreController.php | 18 +- .../TransactionLink/UpdateController.php | 6 +- .../TransactionLinkType/DestroyController.php | 2 +- .../TransactionLinkType/ListController.php | 29 +- .../TransactionLinkType/ShowController.php | 22 +- .../TransactionLinkType/StoreController.php | 16 +- .../TransactionLinkType/UpdateController.php | 14 +- .../Models/UserGroup/IndexController.php | 10 +- .../Models/UserGroup/UpdateController.php | 4 +- .../Controllers/Search/AccountController.php | 30 +- .../Search/TransactionController.php | 22 +- .../Controllers/Summary/BasicController.php | 161 ++++---- .../V1/Controllers/System/AboutController.php | 6 +- .../System/ConfigurationController.php | 6 +- .../V1/Controllers/System/CronController.php | 10 +- .../V1/Controllers/System/UserController.php | 36 +- .../User/PreferencesController.php | 26 +- .../Controllers/Webhook/AttemptController.php | 20 +- .../Controllers/Webhook/MessageController.php | 20 +- .../V1/Controllers/Webhook/ShowController.php | 32 +- .../Controllers/Webhook/StoreController.php | 14 +- .../Controllers/Webhook/UpdateController.php | 14 +- app/Api/V1/Requests/AggregateFormRequest.php | 18 +- .../Autocomplete/AutocompleteApiRequest.php | 2 +- .../Autocomplete/AutocompleteRequest.php | 2 +- .../AutocompleteTransactionApiRequest.php | 2 +- app/Api/V1/Requests/Chart/ChartRequest.php | 4 +- .../Data/Bulk/MoveTransactionsRequest.php | 10 +- app/Api/V1/Requests/Data/DestroyRequest.php | 8 +- .../V1/Requests/Data/Export/ExportRequest.php | 10 +- app/Api/V1/Requests/DateRangeRequest.php | 2 +- app/Api/V1/Requests/DateRequest.php | 4 +- .../Requests/Generic/ObjectTypeApiRequest.php | 8 +- .../Generic/PaginationDateRangeRequest.php | 2 +- .../V1/Requests/Insight/GenericRequest.php | 18 +- .../Requests/Models/Account/ShowRequest.php | 2 +- .../Requests/Models/Account/StoreRequest.php | 14 +- .../Requests/Models/Account/UpdateRequest.php | 10 +- .../Models/Attachment/StoreRequest.php | 6 +- .../Models/Attachment/UpdateRequest.php | 6 +- .../Models/AvailableBudget/Request.php | 4 +- .../V1/Requests/Models/Bill/StoreRequest.php | 10 +- .../V1/Requests/Models/Bill/UpdateRequest.php | 4 +- .../Requests/Models/Budget/StoreRequest.php | 24 +- .../Requests/Models/Budget/UpdateRequest.php | 6 +- .../Models/BudgetLimit/StoreRequest.php | 19 +- .../Models/BudgetLimit/UpdateRequest.php | 4 +- .../CurrencyExchangeRate/DestroyRequest.php | 2 +- .../CurrencyExchangeRate/StoreRequest.php | 4 +- .../CurrencyExchangeRate/UpdateRequest.php | 4 +- .../Models/PiggyBank/StoreRequest.php | 32 +- .../Models/PiggyBank/UpdateRequest.php | 10 +- .../Models/Recurrence/StoreRequest.php | 46 +-- .../Models/Recurrence/UpdateRequest.php | 54 +-- .../V1/Requests/Models/Rule/StoreRequest.php | 32 +- .../V1/Requests/Models/Rule/TestRequest.php | 4 +- .../Requests/Models/Rule/TriggerRequest.php | 4 +- .../V1/Requests/Models/Rule/UpdateRequest.php | 28 +- .../Models/RuleGroup/StoreRequest.php | 4 +- .../Requests/Models/RuleGroup/TestRequest.php | 4 +- .../Models/RuleGroup/TriggerRequest.php | 2 +- .../Models/RuleGroup/UpdateRequest.php | 6 +- .../V1/Requests/Models/Tag/StoreRequest.php | 4 +- .../V1/Requests/Models/Tag/UpdateRequest.php | 4 +- .../Models/Transaction/StoreRequest.php | 216 +++++----- .../Models/Transaction/UpdateRequest.php | 126 +++--- .../TransactionCurrency/StoreRequest.php | 4 +- .../TransactionCurrency/UpdateRequest.php | 4 +- .../Models/TransactionLink/StoreRequest.php | 18 +- .../Models/TransactionLink/UpdateRequest.php | 20 +- .../TransactionLinkType/StoreRequest.php | 2 +- .../TransactionLinkType/UpdateRequest.php | 2 +- .../Models/UserGroup/UpdateRequest.php | 4 +- .../Requests/Models/Webhook/CreateRequest.php | 16 +- .../Requests/Models/Webhook/UpdateRequest.php | 20 +- app/Api/V1/Requests/PaginationRequest.php | 6 +- .../Search/TransactionSearchRequest.php | 2 +- app/Api/V1/Requests/System/UpdateRequest.php | 2 +- .../V1/Requests/System/UserStoreRequest.php | 4 +- .../V1/Requests/System/UserUpdateRequest.php | 4 +- app/Casts/SeparateTimezoneCaster.php | 2 +- .../Correction/ClearsEmptyForeignAmounts.php | 2 +- .../Correction/ConvertsDatesToUTC.php | 4 +- .../Correction/CorrectsAccountTypes.php | 66 ++- .../Commands/Correction/CorrectsAmounts.php | 23 +- .../Correction/CorrectsCurrencies.php | 30 +- .../Commands/Correction/CorrectsDatabase.php | 2 +- .../Correction/CorrectsFrontpageAccounts.php | 4 +- .../Correction/CorrectsGroupAccounts.php | 4 +- .../Correction/CorrectsGroupInformation.php | 4 +- .../Commands/Correction/CorrectsIbans.php | 10 +- .../CorrectsInvertedBudgetLimits.php | 8 +- .../Correction/CorrectsLongDescriptions.php | 6 +- .../Correction/CorrectsMetaDataFields.php | 4 +- .../CorrectsOpeningBalanceCurrencies.php | 9 +- .../Correction/CorrectsPreferences.php | 2 +- .../CorrectsPrimaryCurrencyAmounts.php | 16 +- .../CorrectsRecurringTransactions.php | 4 +- .../CorrectsTimezoneInformation.php | 26 +- .../Correction/CorrectsTransactionTypes.php | 10 +- .../Correction/CorrectsTransferBudgets.php | 3 +- .../Correction/CorrectsUnevenAmount.php | 80 ++-- .../Correction/CreatesAccessTokens.php | 6 +- .../Correction/CreatesGroupMemberships.php | 11 +- .../Commands/Correction/CreatesLinkTypes.php | 12 +- .../Commands/Correction/RemovesBills.php | 2 +- .../Correction/RemovesEmptyGroups.php | 5 +- .../Correction/RemovesEmptyJournals.php | 7 +- .../RemovesLinksToDeletedObjects.php | 14 +- .../RemovesOrphanedTransactions.php | 8 +- .../Commands/Correction/RemovesZeroAmount.php | 5 +- .../Explain/ExplainAvailableBudget.php | 2 +- app/Console/Commands/Export/ExportsData.php | 12 +- .../Integrity/ReportsEmptyObjects.php | 17 +- .../Commands/Integrity/ReportsIntegrity.php | 2 +- .../ValidatesEnvironmentVariables.php | 6 +- .../Integrity/ValidatesFilePermissions.php | 2 +- .../Commands/System/CreatesDatabase.php | 10 +- .../Commands/System/CreatesFirstUser.php | 10 +- .../Commands/System/ForcesDecimalSize.php | 94 +++-- .../Commands/System/ForcesMigrations.php | 2 +- .../Commands/System/OutputsInstructions.php | 24 +- .../Commands/System/OutputsVersion.php | 2 +- .../System/RecalculatesRunningBalance.php | 2 +- .../Commands/System/ResetsErrorMailLimit.php | 2 +- .../Commands/System/ScansAttachments.php | 6 +- .../Commands/System/SetsLatestVersion.php | 2 +- .../Commands/System/VerifySecurityAlerts.php | 2 +- app/Console/Commands/Tools/ApplyRules.php | 70 ++-- app/Console/Commands/Tools/Cron.php | 12 +- .../Upgrade/AddsTransactionIdentifiers.php | 21 +- .../Upgrade/RemovesDatabaseDecryption.php | 6 +- .../Upgrade/RepairsAccountBalances.php | 4 +- .../Upgrade/RepairsPostgresSequences.php | 4 +- .../Upgrade/UpgradesAccountCurrencies.php | 10 +- .../Upgrade/UpgradesAccountMetaData.php | 6 +- .../Commands/Upgrade/UpgradesAttachments.php | 12 +- .../Commands/Upgrade/UpgradesBillsToRules.php | 34 +- .../Upgrade/UpgradesBudgetLimitPeriods.php | 10 +- .../Commands/Upgrade/UpgradesBudgetLimits.php | 6 +- .../Upgrade/UpgradesCreditCardLiabilities.php | 4 +- .../Upgrade/UpgradesCurrencyPreferences.php | 9 +- .../Commands/Upgrade/UpgradesDatabase.php | 2 +- .../Upgrade/UpgradesJournalMetaData.php | 26 +- .../Commands/Upgrade/UpgradesJournalNotes.php | 10 +- .../Commands/Upgrade/UpgradesLiabilities.php | 19 +- .../Upgrade/UpgradesLiabilitiesEight.php | 37 +- .../Upgrade/UpgradesMultiPiggyBanks.php | 14 +- .../UpgradesPrimaryCurrencyAmounts.php | 4 +- .../Upgrade/UpgradesRecurrenceMetaData.php | 10 +- .../Commands/Upgrade/UpgradesRuleActions.php | 22 +- .../Commands/Upgrade/UpgradesTagLocations.php | 16 +- .../Commands/Upgrade/UpgradesToGroups.php | 36 +- .../Upgrade/UpgradesTransferCurrencies.php | 81 ++-- .../UpgradesVariousCurrencyInformation.php | 32 +- .../Commands/Upgrade/UpgradesWebhooks.php | 21 +- app/Console/Commands/VerifiesAccessToken.php | 10 +- app/Console/Kernel.php | 2 +- app/Entities/AccountBalance.php | 6 +- app/Enums/UserRoleEnum.php | 28 +- .../PiggyBank/PiggyBankAmountIsChanged.php | 6 +- .../TriggeredStoredTransactionGroup.php | 4 +- .../User/UserSuccessfullyLoggedIn.php | 1 + app/Exceptions/GracefulNotFoundHandler.php | 10 +- app/Exceptions/Handler.php | 41 +- app/Exceptions/IntervalException.php | 12 +- app/Factory/AccountFactory.php | 60 +-- app/Factory/AccountMetaFactory.php | 4 +- app/Factory/AttachmentFactory.php | 12 +- app/Factory/BillFactory.php | 21 +- app/Factory/BudgetFactory.php | 7 +- app/Factory/CategoryFactory.php | 7 +- app/Factory/PiggyBankEventFactory.php | 4 +- app/Factory/PiggyBankFactory.php | 45 +- app/Factory/RecurrenceFactory.php | 4 +- app/Factory/TagFactory.php | 27 +- app/Factory/TransactionCurrencyFactory.php | 12 +- app/Factory/TransactionFactory.php | 22 +- app/Factory/TransactionGroupFactory.php | 8 +- app/Factory/TransactionJournalFactory.php | 113 ++--- app/Factory/TransactionJournalMetaFactory.php | 8 +- app/Factory/TransactionTypeFactory.php | 2 +- app/Factory/UserGroupFactory.php | 12 +- .../Chart/Basic/ChartJsGenerator.php | 38 +- .../Report/Account/MonthReportGenerator.php | 5 +- .../Report/Audit/MonthReportGenerator.php | 62 +-- .../Report/Budget/MonthReportGenerator.php | 10 +- .../Report/Category/MonthReportGenerator.php | 15 +- .../Report/ReportGeneratorFactory.php | 2 +- .../Report/Standard/MonthReportGenerator.php | 9 +- .../Standard/MultiYearReportGenerator.php | 9 +- .../Report/Standard/YearReportGenerator.php | 9 +- .../Report/Tag/MonthReportGenerator.php | 5 +- .../Webhook/StandardMessageGenerator.php | 61 +-- app/Handlers/Events/AdminEventHandler.php | 4 +- app/Handlers/Events/AuditEventHandler.php | 6 +- app/Handlers/Events/AutomationHandler.php | 6 +- .../Events/DestroyedGroupEventHandler.php | 4 +- .../Events/PreferencesEventHandler.php | 7 +- .../Events/StoredAccountEventHandler.php | 2 +- .../Events/StoredGroupEventHandler.php | 20 +- .../Events/UpdatedAccountEventHandler.php | 2 +- .../Events/UpdatedGroupEventHandler.php | 33 +- app/Handlers/Events/UserEventHandler.php | 6 +- .../Events/VersionCheckEventHandler.php | 14 +- app/Handlers/Events/WebhookEventHandler.php | 5 +- app/Handlers/Observer/AccountObserver.php | 10 +- app/Handlers/Observer/AutoBudgetObserver.php | 4 +- .../Observer/AvailableBudgetObserver.php | 4 +- app/Handlers/Observer/BillObserver.php | 4 +- app/Handlers/Observer/BudgetLimitObserver.php | 8 +- app/Handlers/Observer/BudgetObserver.php | 12 +- .../Observer/PiggyBankEventObserver.php | 6 +- app/Handlers/Observer/PiggyBankObserver.php | 6 +- app/Handlers/Observer/TransactionObserver.php | 10 +- app/Helpers/Attachments/AttachmentHelper.php | 66 +-- .../Attachments/AttachmentHelperInterface.php | 2 +- .../Extensions/AccountCollection.php | 20 +- .../Extensions/AttachmentCollection.php | 59 +-- .../Extensions/CollectorProperties.php | 12 +- .../Collector/Extensions/MetaCollection.php | 48 +-- .../Collector/Extensions/TimeCollection.php | 38 +- app/Helpers/Collector/GroupCollector.php | 178 ++++---- app/Helpers/Fiscal/FiscalHelper.php | 2 +- app/Helpers/Report/NetWorth.php | 26 +- app/Helpers/Report/PopupReport.php | 38 +- app/Helpers/Report/PopupReportInterface.php | 2 +- app/Helpers/Report/ReportHelper.php | 28 +- .../Webhook/Sha3SignatureGenerator.php | 2 +- .../Controllers/Account/CreateController.php | 20 +- .../Controllers/Account/EditController.php | 56 +-- .../Controllers/Account/IndexController.php | 110 ++--- .../Account/ReconcileController.php | 38 +- .../Controllers/Account/ShowController.php | 55 +-- .../Admin/ConfigurationController.php | 12 +- app/Http/Controllers/Admin/LinkController.php | 8 +- .../Admin/NotificationController.php | 38 +- .../Controllers/Admin/UpdateController.php | 8 +- app/Http/Controllers/Admin/UserController.php | 24 +- app/Http/Controllers/AttachmentController.php | 19 +- .../Auth/ForgotPasswordController.php | 4 +- app/Http/Controllers/Auth/LoginController.php | 29 +- .../Controllers/Auth/RegisterController.php | 14 +- .../Auth/ResetPasswordController.php | 4 +- .../Controllers/Auth/TwoFactorController.php | 12 +- .../Controllers/Bill/CreateController.php | 12 +- app/Http/Controllers/Bill/EditController.php | 20 +- app/Http/Controllers/Bill/IndexController.php | 74 ++-- app/Http/Controllers/Bill/ShowController.php | 52 +-- .../Budget/BudgetLimitController.php | 62 +-- .../Controllers/Budget/CreateController.php | 20 +- .../Controllers/Budget/EditController.php | 26 +- .../Controllers/Budget/IndexController.php | 94 ++--- .../Controllers/Budget/ShowController.php | 60 +-- .../Controllers/Category/CreateController.php | 4 +- .../Controllers/Category/EditController.php | 8 +- .../Category/NoCategoryController.php | 46 ++- .../Controllers/Category/ShowController.php | 34 +- .../Controllers/Chart/AccountController.php | 223 +++++----- app/Http/Controllers/Chart/BillController.php | 40 +- .../Controllers/Chart/BudgetController.php | 218 +++++----- .../Chart/BudgetReportController.php | 46 +-- .../Controllers/Chart/CategoryController.php | 76 ++-- .../Chart/CategoryReportController.php | 82 ++-- .../Chart/DoubleReportController.php | 108 ++--- .../Chart/ExpenseReportController.php | 62 +-- .../Controllers/Chart/PiggyBankController.php | 38 +- .../Controllers/Chart/ReportController.php | 64 +-- .../Controllers/Chart/TagReportController.php | 100 ++--- .../Chart/TransactionController.php | 48 +-- app/Http/Controllers/Controller.php | 42 +- app/Http/Controllers/DebugController.php | 54 +-- .../Controllers/Export/IndexController.php | 15 +- app/Http/Controllers/HomeController.php | 30 +- app/Http/Controllers/JavascriptController.php | 38 +- app/Http/Controllers/Json/BoxController.php | 64 +-- .../Controllers/Json/BudgetController.php | 4 +- .../Controllers/Json/FrontpageController.php | 24 +- app/Http/Controllers/Json/IntroController.php | 20 +- .../Controllers/Json/ReconcileController.php | 45 +- .../Controllers/Json/RecurrenceController.php | 62 +-- app/Http/Controllers/Json/RuleController.php | 2 +- app/Http/Controllers/NewUserController.php | 15 +- .../ObjectGroup/EditController.php | 2 +- .../PiggyBank/AmountController.php | 28 +- .../PiggyBank/CreateController.php | 10 +- .../Controllers/PiggyBank/EditController.php | 16 +- .../Controllers/PiggyBank/IndexController.php | 50 +-- .../Controllers/PiggyBank/ShowController.php | 12 +- .../Controllers/Popup/ReportController.php | 12 +- .../Controllers/PreferencesController.php | 98 ++--- .../Controllers/Profile/MfaController.php | 28 +- app/Http/Controllers/ProfileController.php | 17 +- .../Recurring/CreateController.php | 56 +-- .../Recurring/DeleteController.php | 2 +- .../Controllers/Recurring/EditController.php | 54 +-- .../Controllers/Recurring/IndexController.php | 32 +- .../Controllers/Recurring/ShowController.php | 38 +- .../Recurring/TriggerController.php | 12 +- .../Controllers/Report/AccountController.php | 2 +- .../Controllers/Report/BalanceController.php | 41 +- .../Controllers/Report/BillController.php | 2 +- .../Controllers/Report/BudgetController.php | 68 ++-- .../Controllers/Report/CategoryController.php | 130 +++--- .../Controllers/Report/DoubleController.php | 112 ++--- .../Report/OperationsController.php | 10 +- app/Http/Controllers/Report/TagController.php | 106 ++--- app/Http/Controllers/ReportController.php | 46 +-- .../Controllers/Rule/CreateController.php | 44 +- app/Http/Controllers/Rule/EditController.php | 32 +- app/Http/Controllers/Rule/IndexController.php | 2 +- .../Controllers/Rule/SelectController.php | 42 +- .../RuleGroup/CreateController.php | 2 +- .../RuleGroup/DeleteController.php | 2 +- .../Controllers/RuleGroup/EditController.php | 6 +- .../RuleGroup/ExecutionController.php | 8 +- app/Http/Controllers/SearchController.php | 24 +- .../Controllers/System/InstallController.php | 24 +- app/Http/Controllers/TagController.php | 86 ++-- .../Transaction/BulkController.php | 2 +- .../Transaction/ConvertController.php | 100 ++--- .../Transaction/CreateController.php | 38 +- .../Transaction/DeleteController.php | 12 +- .../Transaction/EditController.php | 20 +- .../Transaction/IndexController.php | 50 +-- .../Transaction/LinkController.php | 6 +- .../Transaction/MassController.php | 32 +- .../Transaction/ShowController.php | 64 +-- .../TransactionCurrency/CreateController.php | 12 +- .../TransactionCurrency/DeleteController.php | 4 +- .../TransactionCurrency/EditController.php | 23 +- .../TransactionCurrency/IndexController.php | 4 +- app/Http/Kernel.php | 32 +- app/Http/Middleware/AcceptHeaders.php | 8 +- app/Http/Middleware/Authenticate.php | 2 +- app/Http/Middleware/InterestingMessage.php | 18 +- app/Http/Middleware/IsAdmin.php | 2 +- app/Http/Middleware/IsDemoUser.php | 2 +- app/Http/Middleware/Range.php | 16 +- app/Http/Middleware/SecureHeaders.php | 24 +- app/Http/Middleware/TrustProxies.php | 14 +- app/Http/Requests/AccountFormRequest.php | 18 +- app/Http/Requests/BillStoreRequest.php | 4 +- app/Http/Requests/BillUpdateRequest.php | 4 +- app/Http/Requests/BudgetFormStoreRequest.php | 4 +- app/Http/Requests/BudgetFormUpdateRequest.php | 8 +- app/Http/Requests/CategoryFormRequest.php | 2 +- app/Http/Requests/ConfigurationRequest.php | 8 +- app/Http/Requests/CurrencyFormRequest.php | 8 +- app/Http/Requests/JournalLinkRequest.php | 14 +- app/Http/Requests/LinkTypeFormRequest.php | 4 +- app/Http/Requests/MassEditJournalRequest.php | 2 +- app/Http/Requests/NewUserFormRequest.php | 2 +- app/Http/Requests/NotificationRequest.php | 20 +- app/Http/Requests/PiggyBankStoreRequest.php | 6 +- app/Http/Requests/PiggyBankUpdateRequest.php | 6 +- app/Http/Requests/PreferencesRequest.php | 2 +- app/Http/Requests/ProfileFormRequest.php | 2 +- .../Requests/ReconciliationStoreRequest.php | 6 +- app/Http/Requests/RecurrenceFormRequest.php | 110 ++--- app/Http/Requests/ReportFormRequest.php | 8 +- app/Http/Requests/RuleFormRequest.php | 30 +- app/Http/Requests/RuleGroupFormRequest.php | 2 +- app/Http/Requests/TagFormRequest.php | 10 +- app/Http/Requests/TestRuleFormRequest.php | 4 +- app/Http/Requests/UserFormRequest.php | 4 +- app/Jobs/CreateAutoBudgetLimits.php | 60 +-- app/Jobs/CreateRecurringTransactions.php | 66 +-- app/Jobs/DownloadExchangeRates.php | 26 +- app/Jobs/MailError.php | 12 +- app/Jobs/WarnAboutBills.php | 16 +- .../CreatesPiggyBankEventForChangedAmount.php | 4 +- .../NotifiesUserAboutFailedRuleAction.php | 16 +- .../NotifiesAboutExtensionOrRenewal.php | 2 +- .../NotifiesAboutOverdueSubscriptions.php | 12 +- .../System/HandlesNewUserRegistration.php | 14 +- .../Security/User/StoresNewIpAddress.php | 7 +- app/Listeners/Test/SendsTestNotification.php | 13 + app/Mail/ConfirmEmailChangeMail.php | 3 +- app/Mail/InvitationMail.php | 2 +- app/Models/Account.php | 22 +- app/Models/AccountMeta.php | 4 +- app/Models/AccountType.php | 30 +- app/Models/Attachment.php | 10 +- app/Models/AuditLogEntry.php | 4 +- app/Models/AutoBudget.php | 12 +- app/Models/AvailableBudget.php | 20 +- app/Models/Bill.php | 20 +- app/Models/Budget.php | 10 +- app/Models/BudgetLimit.php | 11 +- app/Models/Category.php | 8 +- app/Models/Configuration.php | 2 +- app/Models/CurrencyExchangeRate.php | 10 +- app/Models/GroupMembership.php | 2 +- app/Models/InvitedUser.php | 2 +- app/Models/Location.php | 8 +- app/Models/Note.php | 2 +- app/Models/ObjectGroup.php | 6 +- app/Models/PeriodStatistic.php | 4 +- app/Models/PiggyBank.php | 13 +- app/Models/PiggyBankEvent.php | 8 +- app/Models/PiggyBankRepetition.php | 6 +- app/Models/Preference.php | 18 +- app/Models/Recurrence.php | 12 +- app/Models/RecurrenceMeta.php | 4 +- app/Models/RecurrenceRepetition.php | 20 +- app/Models/RecurrenceTransaction.php | 20 +- app/Models/RecurrenceTransactionMeta.php | 4 +- app/Models/Rule.php | 12 +- app/Models/RuleAction.php | 6 +- app/Models/RuleGroup.php | 8 +- app/Models/RuleTrigger.php | 6 +- app/Models/Tag.php | 8 +- app/Models/Transaction.php | 26 +- app/Models/TransactionCurrency.php | 16 +- app/Models/TransactionGroup.php | 9 +- app/Models/TransactionJournal.php | 14 +- app/Models/TransactionJournalLink.php | 9 +- app/Models/TransactionJournalMeta.php | 6 +- app/Models/TransactionType.php | 16 +- app/Models/UserGroup.php | 6 +- app/Models/Webhook.php | 12 +- app/Models/WebhookAttempt.php | 6 +- app/Models/WebhookDelivery.php | 2 +- app/Models/WebhookMessage.php | 8 +- app/Models/WebhookResponse.php | 2 +- app/Models/WebhookTrigger.php | 2 +- .../Admin/UnknownUserLoginAttempt.php | 5 +- app/Notifications/Admin/UserInvitation.php | 9 +- app/Notifications/Admin/UserRegistration.php | 7 +- .../Admin/VersionCheckResult.php | 6 +- .../Notifiables/OwnerNotifiable.php | 4 +- .../ReturnsAvailableChannels.php | 2 +- app/Notifications/ReturnsSettings.php | 20 +- .../Security/DisabledMFANotification.php | 5 +- .../Security/EnabledMFANotification.php | 5 +- .../Security/MFABackupFewLeftNotification.php | 7 +- .../Security/MFABackupNoLeftNotification.php | 5 +- .../MFAManyFailedAttemptsNotification.php | 7 +- .../MFAUsedBackupCodeNotification.php | 5 +- .../Security/NewBackupCodesNotification.php | 5 +- .../Security/UserFailedLoginAttempt.php | 5 +- .../Test/OwnerTestNotificationEmail.php | 3 +- .../Test/UserTestNotificationEmail.php | 3 +- app/Notifications/User/BillReminder.php | 6 +- app/Notifications/User/NewAccessToken.php | 3 +- app/Notifications/User/RuleActionFailed.php | 13 +- .../User/SubscriptionsOverdueReminder.php | 12 +- .../User/TransactionCreation.php | 3 +- app/Notifications/User/UserLogin.php | 3 +- app/Notifications/User/UserNewPassword.php | 5 +- app/Notifications/User/UserRegistration.php | 3 +- app/Providers/AccountServiceProvider.php | 4 +- app/Providers/AdminServiceProvider.php | 4 +- app/Providers/AppServiceProvider.php | 4 +- app/Providers/AttachmentServiceProvider.php | 4 +- app/Providers/AuthServiceProvider.php | 4 +- app/Providers/BillServiceProvider.php | 4 +- app/Providers/BudgetServiceProvider.php | 4 +- app/Providers/CategoryServiceProvider.php | 4 +- app/Providers/CurrencyServiceProvider.php | 4 +- app/Providers/EventServiceProvider.php | 32 +- app/Providers/FireflyServiceProvider.php | 24 +- app/Providers/FireflySessionProvider.php | 8 +- app/Providers/JournalServiceProvider.php | 4 +- app/Providers/PiggyBankServiceProvider.php | 4 +- app/Providers/RecurringServiceProvider.php | 4 +- app/Providers/RouteServiceProvider.php | 8 +- app/Providers/RuleGroupServiceProvider.php | 4 +- app/Providers/RuleServiceProvider.php | 4 +- app/Providers/SearchServiceProvider.php | 6 +- app/Providers/TagServiceProvider.php | 4 +- .../Account/AccountRepository.php | 147 ++++--- .../Account/AccountRepositoryInterface.php | 38 +- app/Repositories/Account/AccountTasker.php | 76 ++-- .../Account/OperationsRepository.php | 114 +++--- .../Account/OperationsRepositoryInterface.php | 40 +- .../Attachment/AttachmentRepository.php | 10 +- .../AttachmentRepositoryInterface.php | 2 +- .../AuditLogEntry/ALERepository.php | 4 +- app/Repositories/Bill/BillRepository.php | 133 +++--- .../Bill/BillRepositoryInterface.php | 6 +- .../Budget/AvailableBudgetRepository.php | 71 ++-- .../AvailableBudgetRepositoryInterface.php | 12 +- .../Budget/BudgetLimitRepository.php | 74 ++-- .../Budget/BudgetLimitRepositoryInterface.php | 10 +- app/Repositories/Budget/BudgetRepository.php | 164 ++++---- .../Budget/BudgetRepositoryInterface.php | 12 +- .../Budget/NoBudgetRepository.php | 18 +- .../Budget/NoBudgetRepositoryInterface.php | 4 +- .../Budget/OperationsRepository.php | 82 ++-- .../Budget/OperationsRepositoryInterface.php | 14 +- .../Category/CategoryRepository.php | 53 +-- .../Category/CategoryRepositoryInterface.php | 12 +- .../Category/NoCategoryRepository.php | 60 +-- .../NoCategoryRepositoryInterface.php | 10 +- .../Category/OperationsRepository.php | 134 +++--- .../OperationsRepositoryInterface.php | 20 +- .../Currency/CurrencyRepository.php | 61 +-- .../Currency/CurrencyRepositoryInterface.php | 14 +- .../ExchangeRate/ExchangeRateRepository.php | 30 +- .../ExchangeRateRepositoryInterface.php | 4 +- .../Journal/JournalAPIRepository.php | 11 +- .../Journal/JournalAPIRepositoryInterface.php | 2 +- .../Journal/JournalCLIRepository.php | 19 +- .../Journal/JournalCLIRepositoryInterface.php | 6 +- .../Journal/JournalRepository.php | 22 +- .../Journal/JournalRepositoryInterface.php | 8 +- .../LinkType/LinkTypeRepository.php | 40 +- .../LinkType/LinkTypeRepositoryInterface.php | 12 +- .../ObjectGroup/CreatesObjectGroups.php | 17 +- .../ObjectGroup/ObjectGroupRepository.php | 12 +- .../PeriodStatisticRepository.php | 39 +- .../PiggyBank/ModifiesPiggyBanks.php | 62 +-- .../PiggyBank/PiggyBankRepository.php | 62 +-- .../PiggyBankRepositoryInterface.php | 16 +- .../Recurring/RecurringRepository.php | 46 ++- .../RecurringRepositoryInterface.php | 12 +- app/Repositories/Rule/RuleRepository.php | 100 ++--- .../Rule/RuleRepositoryInterface.php | 2 +- .../RuleGroup/RuleGroupRepository.php | 54 ++- .../RuleGroupRepositoryInterface.php | 10 +- app/Repositories/Tag/OperationsRepository.php | 42 +- .../Tag/OperationsRepositoryInterface.php | 8 +- app/Repositories/Tag/TagRepository.php | 80 ++-- .../Tag/TagRepositoryInterface.php | 18 +- .../TransactionGroupRepository.php | 88 ++-- .../TransactionGroupRepositoryInterface.php | 6 +- .../TransactionTypeRepository.php | 6 +- .../TransactionTypeRepositoryInterface.php | 4 +- app/Repositories/User/UserRepository.php | 53 +-- .../User/UserRepositoryInterface.php | 12 +- .../UserGroup/UserGroupRepository.php | 33 +- .../UserGroupRepositoryInterface.php | 2 +- .../Webhook/WebhookRepository.php | 34 +- app/Rules/Account/IsValidAccountType.php | 2 +- app/Rules/Account/IsValidAccountTypeList.php | 2 +- app/Rules/BelongsUser.php | 28 +- app/Rules/BelongsUserGroup.php | 23 +- app/Rules/IsAssetAccountId.php | 2 +- app/Rules/IsDefaultUserGroupName.php | 4 +- app/Rules/IsTransferAccount.php | 2 +- app/Rules/IsValidActionExpression.php | 2 +- app/Rules/IsValidAmount.php | 2 +- app/Rules/IsValidAttachmentModel.php | 18 +- app/Rules/IsValidDateRange.php | 4 +- app/Rules/IsValidSortInstruction.php | 4 +- .../IsValidTransactionTypeList.php | 2 +- app/Rules/UniqueAccountNumber.php | 7 +- app/Rules/UniqueIban.php | 11 +- app/Rules/ValidRecurrenceRepetitionValue.php | 4 +- .../FireflyIIIOrg/Update/UpdateRequest.php | 40 +- .../Destroy/AccountDestroyService.php | 17 +- .../Destroy/CategoryDestroyService.php | 3 +- .../Internal/Support/AccountServiceTrait.php | 99 +++-- .../Internal/Support/BillServiceTrait.php | 5 +- .../Support/CreditRecalculateService.php | 39 +- .../Internal/Support/JournalServiceTrait.php | 44 +- .../Internal/Support/LocationServiceTrait.php | 8 +- .../Support/RecurringTransactionTrait.php | 72 ++-- .../Internal/Update/AccountUpdateService.php | 42 +- .../Internal/Update/BillUpdateService.php | 34 +- .../Internal/Update/CategoryUpdateService.php | 15 +- .../Internal/Update/CurrencyUpdateService.php | 4 +- .../Internal/Update/GroupCloneService.php | 18 +- .../Internal/Update/GroupUpdateService.php | 14 +- .../Internal/Update/JournalUpdateService.php | 204 +++++----- .../Update/RecurrenceUpdateService.php | 26 +- .../Webhook/StandardWebhookSender.php | 38 +- app/Support/Amount.php | 76 ++-- .../Authentication/RemoteUserGuard.php | 12 +- .../Authentication/RemoteUserProvider.php | 4 +- app/Support/Balance.php | 13 +- app/Support/Binder/AccountList.php | 12 +- app/Support/Binder/BudgetList.php | 2 +- app/Support/Binder/CategoryList.php | 2 +- app/Support/Binder/Date.php | 20 +- app/Support/Binder/DynamicConfigKey.php | 2 +- app/Support/Binder/EitherConfigKey.php | 2 +- app/Support/Binder/JournalList.php | 6 +- app/Support/Binder/TagList.php | 4 +- app/Support/Binder/TagOrId.php | 2 +- app/Support/CacheProperties.php | 2 +- app/Support/Calendar/Calculator.php | 8 +- .../Chart/Budget/FrontpageChartGenerator.php | 24 +- .../Category/FrontpageChartGenerator.php | 46 +-- .../Category/WholePeriodChartGenerator.php | 62 +-- app/Support/Chart/ChartData.php | 2 +- app/Support/ChartColour.php | 4 +- app/Support/Cronjobs/AbstractCronjob.php | 6 +- app/Support/Cronjobs/AutoBudgetCronjob.php | 8 +- app/Support/Cronjobs/BillWarningCronjob.php | 14 +- app/Support/Cronjobs/ExchangeRatesCronjob.php | 8 +- app/Support/Cronjobs/RecurringCronjob.php | 14 +- app/Support/Cronjobs/UpdateCheckCronjob.php | 36 +- app/Support/Cronjobs/WebhookCronjob.php | 12 +- app/Support/Debug/Timer.php | 4 +- app/Support/ExpandedForm.php | 98 ++--- app/Support/Export/ExportDataGenerator.php | 147 +++---- app/Support/FireflyConfig.php | 18 +- app/Support/Form/AccountForm.php | 56 +-- app/Support/Form/CurrencyForm.php | 64 +-- app/Support/Form/FormSupport.php | 26 +- app/Support/Form/PiggyBankForm.php | 10 +- app/Support/Form/RuleForm.php | 14 +- .../Http/Api/AccountBalanceGrouped.php | 66 +-- app/Support/Http/Api/AccountFilter.php | 14 +- app/Support/Http/Api/CleansChartData.php | 2 +- .../Http/Api/CollectsAccountsFromFilter.php | 5 +- .../Http/Api/ExchangeRateConverter.php | 27 +- .../Http/Api/SummaryBalanceGrouped.php | 58 +-- app/Support/Http/Api/TransactionFilter.php | 6 +- .../Http/Api/ValidatesUserGroupTrait.php | 12 +- app/Support/Http/Controllers/AugumentData.php | 54 +-- .../Http/Controllers/BasicDataSupport.php | 2 +- .../Http/Controllers/ChartGeneration.php | 32 +- app/Support/Http/Controllers/CreateStuff.php | 8 +- app/Support/Http/Controllers/CronRunner.php | 10 +- .../Http/Controllers/DateCalculation.php | 14 +- .../Http/Controllers/GetConfigurationData.php | 82 ++-- .../Http/Controllers/ModelInformation.php | 62 +-- .../Http/Controllers/PeriodOverview.php | 158 +++---- .../Http/Controllers/RenderPartialViews.php | 50 +-- .../Http/Controllers/RequestInformation.php | 22 +- .../Http/Controllers/RuleManagement.php | 14 +- .../Controllers/TransactionCalculation.php | 19 +- .../Http/Controllers/UserNavigation.php | 16 +- .../JsonApi/Enrichments/AccountEnrichment.php | 119 +++--- .../Enrichments/AvailableBudgetEnrichment.php | 38 +- .../JsonApi/Enrichments/BudgetEnrichment.php | 46 ++- .../Enrichments/BudgetLimitEnrichment.php | 54 +-- .../Enrichments/CategoryEnrichment.php | 35 +- .../Enrichments/PiggyBankEnrichment.php | 92 ++--- .../Enrichments/PiggyBankEventEnrichment.php | 42 +- .../Enrichments/RecurringEnrichment.php | 177 ++++---- .../Enrichments/SubscriptionEnrichment.php | 123 +++--- .../TransactionGroupEnrichment.php | 66 +-- .../JsonApi/Enrichments/WebhookEnrichment.php | 28 +- .../Models/AccountBalanceCalculator.php | 49 +-- app/Support/Models/BillDateCalculator.php | 20 +- app/Support/Models/ReturnsIntegerIdTrait.php | 2 +- .../Models/ReturnsIntegerUserIdTrait.php | 4 +- app/Support/Navigation.php | 110 ++--- app/Support/Notifications/UrlValidator.php | 5 +- .../RecalculatesAvailableBudgetsTrait.php | 35 +- app/Support/ParseDateString.php | 38 +- app/Support/Preferences.php | 48 +-- .../Report/Budget/BudgetReportGenerator.php | 96 ++--- .../Category/CategoryReportGenerator.php | 26 +- .../Summarizer/TransactionSummarizer.php | 34 +- .../Recurring/CalculateRangeOccurrences.php | 22 +- .../Recurring/CalculateXOccurrences.php | 30 +- .../Recurring/CalculateXOccurrencesSince.php | 32 +- .../Recurring/FiltersWeekends.php | 6 +- .../UserGroup/UserGroupInterface.php | 4 +- .../Repositories/UserGroup/UserGroupTrait.php | 12 +- app/Support/Request/AppendsLocationData.php | 53 ++- app/Support/Request/ChecksLogin.php | 8 +- app/Support/Request/ConvertsDataTypes.php | 36 +- app/Support/Request/ValidatesWebhooks.php | 6 +- app/Support/Search/AccountSearch.php | 13 +- app/Support/Search/OperatorQuerySearch.php | 307 +++++++------- app/Support/Search/QueryParser/NodeResult.php | 2 +- .../Search/QueryParser/QueryParser.php | 10 +- .../Singleton/PreferencesSingleton.php | 4 +- app/Support/Steam.php | 190 ++++----- app/Support/System/IsOldVersion.php | 4 +- app/Support/System/OAuthKeys.php | 8 +- app/Support/Twig/AmountFormat.php | 14 +- app/Support/Twig/General.php | 52 ++- app/Support/Twig/Rule.php | 8 +- app/Support/Twig/TransactionGroupTwig.php | 31 +- app/Support/Twig/Translation.php | 2 +- app/TransactionRules/Actions/AddTag.php | 11 +- .../Actions/AppendDescription.php | 5 +- .../Actions/AppendDescriptionToNotes.php | 6 +- app/TransactionRules/Actions/AppendNotes.php | 16 +- .../Actions/AppendNotesToDescription.php | 6 +- app/TransactionRules/Actions/ClearNotes.php | 5 +- .../Actions/ConvertToDeposit.php | 41 +- .../Actions/ConvertToTransfer.php | 51 +-- .../Actions/ConvertToWithdrawal.php | 41 +- .../Actions/DeleteTransaction.php | 2 +- app/TransactionRules/Actions/LinkToBill.php | 15 +- .../Actions/MoveDescriptionToNotes.php | 12 +- .../Actions/MoveNotesToDescription.php | 8 +- .../Actions/PrependDescription.php | 3 +- app/TransactionRules/Actions/PrependNotes.php | 16 +- .../Actions/RemoveAllTags.php | 2 +- app/TransactionRules/Actions/RemoveTag.php | 14 +- app/TransactionRules/Actions/SetAmount.php | 12 +- app/TransactionRules/Actions/SetBudget.php | 12 +- app/TransactionRules/Actions/SetCategory.php | 12 +- .../Actions/SetDescription.php | 2 +- .../Actions/SetDestinationAccount.php | 19 +- .../Actions/SetDestinationToCashAccount.php | 13 +- app/TransactionRules/Actions/SetNotes.php | 14 +- .../Actions/SetSourceAccount.php | 19 +- .../Actions/SetSourceToCashAccount.php | 11 +- .../Actions/SwitchAccounts.php | 16 +- .../Actions/UpdatePiggyBank.php | 28 +- .../Engine/SearchRuleEngine.php | 42 +- .../Expressions/ActionExpression.php | 12 +- .../ActionExpressionLanguageProvider.php | 8 +- .../Factory/ActionFactory.php | 6 +- .../Traits/RefreshNotesTrait.php | 5 +- app/Transformers/AccountTransformer.php | 132 +++--- app/Transformers/AttachmentTransformer.php | 2 +- .../AvailableBudgetTransformer.php | 38 +- app/Transformers/BillTransformer.php | 64 +-- app/Transformers/BudgetLimitTransformer.php | 42 +- app/Transformers/BudgetTransformer.php | 58 +-- app/Transformers/CategoryTransformer.php | 16 +- app/Transformers/CurrencyTransformer.php | 2 +- app/Transformers/ExchangeRateTransformer.php | 6 +- app/Transformers/LinkTypeTransformer.php | 2 +- app/Transformers/ObjectGroupTransformer.php | 2 +- .../PiggyBankEventTransformer.php | 30 +- app/Transformers/PiggyBankTransformer.php | 58 +-- app/Transformers/PreferenceTransformer.php | 2 +- app/Transformers/RecurrenceTransformer.php | 2 +- app/Transformers/RuleGroupTransformer.php | 2 +- app/Transformers/RuleTransformer.php | 8 +- app/Transformers/TagTransformer.php | 4 +- .../TransactionGroupTransformer.php | 300 +++++++------- .../TransactionLinkTransformer.php | 2 +- app/Transformers/UserGroupTransformer.php | 16 +- app/Transformers/UserTransformer.php | 2 +- .../WebhookAttemptTransformer.php | 2 +- .../WebhookMessageTransformer.php | 2 +- app/Transformers/WebhookTransformer.php | 2 +- app/User.php | 23 +- app/Validation/Account/DepositValidation.php | 22 +- .../Account/LiabilityValidation.php | 8 +- app/Validation/Account/OBValidation.php | 22 +- .../Account/ReconciliationValidation.php | 12 +- app/Validation/Account/TransferValidation.php | 12 +- .../Account/WithdrawalValidation.php | 16 +- app/Validation/AccountValidator.php | 30 +- .../Bulk/ValidatesBulkTransactionQuery.php | 8 +- .../AutoBudget/ValidatesAutoBudgetRequest.php | 4 +- app/Validation/CurrencyValidation.php | 16 +- app/Validation/FireflyValidator.php | 119 +++--- app/Validation/GroupValidation.php | 11 +- app/Validation/RecurrenceValidation.php | 30 +- app/Validation/TransactionValidation.php | 80 ++-- composer.lock | 12 +- config/firefly.php | 4 +- package-lock.json | 385 +++++++++--------- resources/assets/v1/src/locales/id.json | 64 +-- resources/assets/v1/src/locales/ko.json | 4 +- .../Api/Autocomplete/BillControllerTest.php | 20 +- .../Api/Autocomplete/BudgetControllerTest.php | 12 +- .../Autocomplete/CategoryControllerTest.php | 10 +- .../Autocomplete/CurrencyControllerTest.php | 18 +- .../ObjectGroupControllerTest.php | 12 +- .../Autocomplete/PiggyBankControllerTest.php | 18 +- .../Autocomplete/RecurrenceControllerTest.php | 14 +- .../Api/Autocomplete/RuleControllerTest.php | 16 +- .../Autocomplete/RuleGroupControllerTest.php | 14 +- .../Api/Autocomplete/TagControllerTest.php | 12 +- .../Api/Chart/AccountControllerTest.php | 4 +- .../Api/Chart/BalanceControllerTest.php | 4 +- .../Api/Chart/BudgetControllerTest.php | 4 +- .../Api/Chart/CategoryControllerTest.php | 4 +- .../Api/Models/Account/ListControllerTest.php | 15 +- .../Api/Models/Account/ShowControllerTest.php | 21 +- .../Api/System/AboutControllerTest.php | 4 +- tests/integration/CreatesApplication.php | 2 +- .../Support/Models/BillDateCalculatorTest.php | 12 +- .../NavigationCustomEndOfPeriodTest.php | 2 +- tests/integration/TestCase.php | 4 +- .../Support/Calendar/CalculatorProvider.php | 2 +- .../unit/Support/Calendar/CalculatorTest.php | 2 +- .../Calendar/Periodicity/BimonthlyTest.php | 2 +- .../Calendar/Periodicity/FortnightlyTest.php | 2 +- .../Calendar/Periodicity/HalfYearlyTest.php | 2 +- .../Calendar/Periodicity/MonthlyTest.php | 2 +- .../Calendar/Periodicity/QuarterlyTest.php | 2 +- .../Calendar/Periodicity/YearlyTest.php | 2 +- .../unit/Support/NavigationAddPeriodTest.php | 52 +-- .../Support/NavigationEndOfPeriodTest.php | 26 +- ...ctQueryParserInterfaceParseQueryTester.php | 32 +- 888 files changed, 10732 insertions(+), 10387 deletions(-) diff --git a/app/Api/V1/Controllers/Autocomplete/AccountController.php b/app/Api/V1/Controllers/Autocomplete/AccountController.php index 73e85dac63..51aa06ce3d 100644 --- a/app/Api/V1/Controllers/Autocomplete/AccountController.php +++ b/app/Api/V1/Controllers/Autocomplete/AccountController.php @@ -88,11 +88,11 @@ class AccountController extends Controller // set date to end-of-day for account balance. so it is at $date 23:59:59 $date->endOfDay(); - $return = []; - $timer = Timer::getInstance(); + $return = []; + $timer = Timer::getInstance(); $timer->start(sprintf('AC accounts "%s"', $query)); - $result = $this->repository->searchAccount((string) $query, $types, $limit); - $allBalances = Steam::accountsBalancesOptimized($result, $date, $this->primaryCurrency, $this->convertToPrimary); + $result = $this->repository->searchAccount((string) $query, $types, $limit); + $allBalances = Steam::accountsBalancesOptimized($result, $date, $this->primaryCurrency, $this->convertToPrimary); /** @var Account $account */ foreach ($result as $account) { @@ -109,7 +109,7 @@ class AccountController extends Controller $nameWithBalance = sprintf('%s (%s)', $account->name, Amount::formatAnything($useCurrency, $amount, false)); } - $return[] = [ + $return[] = [ 'id' => (string) $account->id, 'name' => $account->name, 'name_with_balance' => $nameWithBalance, @@ -124,7 +124,7 @@ class AccountController extends Controller 'account_currency_name' => $currency->name, 'account_currency_code' => $currency->code, 'account_currency_symbol' => $currency->symbol, - 'account_currency_decimal_places' => $currency->decimal_places + 'account_currency_decimal_places' => $currency->decimal_places, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/BillController.php b/app/Api/V1/Controllers/Autocomplete/BillController.php index cae9dd63b4..b43e56e1f2 100644 --- a/app/Api/V1/Controllers/Autocomplete/BillController.php +++ b/app/Api/V1/Controllers/Autocomplete/BillController.php @@ -63,7 +63,7 @@ class BillController extends Controller public function bills(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchBill($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn(Bill $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); + $filtered = $result->map(static fn (Bill $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/BudgetController.php b/app/Api/V1/Controllers/Autocomplete/BudgetController.php index d919648529..40d42d5c18 100644 --- a/app/Api/V1/Controllers/Autocomplete/BudgetController.php +++ b/app/Api/V1/Controllers/Autocomplete/BudgetController.php @@ -63,7 +63,7 @@ class BudgetController extends Controller public function budgets(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchBudget($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn(Budget $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); + $filtered = $result->map(static fn (Budget $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/CategoryController.php b/app/Api/V1/Controllers/Autocomplete/CategoryController.php index 39a5bf614e..27fa145d52 100644 --- a/app/Api/V1/Controllers/Autocomplete/CategoryController.php +++ b/app/Api/V1/Controllers/Autocomplete/CategoryController.php @@ -63,7 +63,7 @@ class CategoryController extends Controller public function categories(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchCategory($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn(Category $item): array => ['id' => (string) $item->id, 'name' => $item->name]); + $filtered = $result->map(static fn (Category $item): array => ['id' => (string) $item->id, 'name' => $item->name]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php index 327d73e9a4..656c96b493 100644 --- a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php +++ b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php @@ -74,7 +74,7 @@ class CurrencyController extends Controller 'name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol, - 'decimal_places' => $currency->decimal_places + 'decimal_places' => $currency->decimal_places, ]; } @@ -99,7 +99,7 @@ class CurrencyController extends Controller 'name' => sprintf('%s (%s)', $currency->name, $currency->code), 'code' => $currency->code, 'symbol' => $currency->symbol, - 'decimal_places' => $currency->decimal_places + 'decimal_places' => $currency->decimal_places, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php index 4c031d7a6b..a7d54eff6b 100644 --- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php +++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php @@ -52,7 +52,7 @@ class PiggyBankController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->piggyRepository = app(PiggyBankRepositoryInterface::class); + $this->piggyRepository = app(PiggyBankRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); $this->piggyRepository->setUser($this->user); $this->piggyRepository->setUserGroup($this->userGroup); @@ -72,7 +72,7 @@ class PiggyBankController extends Controller foreach ($piggies as $piggy) { $currency = $piggy->transactionCurrency; $objectGroup = $piggy->objectGroups()->first(); - $response[] = [ + $response[] = [ 'id' => (string) $piggy->id, 'name' => $piggy->name, 'currency_id' => (string) $currency->id, @@ -82,7 +82,7 @@ class PiggyBankController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'object_group_id' => null === $objectGroup ? null : (string) $objectGroup->id, 'object_group_title' => $objectGroup?->title, - 'object_group_order' => $objectGroup?->order + 'object_group_order' => $objectGroup?->order, ]; } @@ -100,7 +100,7 @@ class PiggyBankController extends Controller $currency = $piggy->transactionCurrency; $currentAmount = $this->piggyRepository->getCurrentAmount($piggy); $objectGroup = $piggy->objectGroups()->first(); - $response[] = [ + $response[] = [ 'id' => (string) $piggy->id, 'name' => $piggy->name, 'name_with_balance' => sprintf( @@ -115,7 +115,7 @@ class PiggyBankController extends Controller 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, 'object_group_id' => null === $objectGroup ? null : (string) $objectGroup->id, - 'object_group_title' => $objectGroup?->title + 'object_group_title' => $objectGroup?->title, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php index 22a2e87110..2d243b4d2b 100644 --- a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php +++ b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php @@ -67,7 +67,7 @@ class RecurrenceController extends Controller 'id' => (string) $recurrence->id, 'name' => $recurrence->title, 'description' => $recurrence->description, - 'active' => $recurrence->active + 'active' => $recurrence->active, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RuleController.php b/app/Api/V1/Controllers/Autocomplete/RuleController.php index 1801850cbf..d0a509156a 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleController.php @@ -67,7 +67,7 @@ class RuleController extends Controller 'id' => (string) $rule->id, 'name' => $rule->title, 'description' => $rule->description, - 'active' => $rule->active + 'active' => $rule->active, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php index 2327442eb2..51acc4a3c2 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php @@ -67,7 +67,7 @@ class RuleGroupController extends Controller 'id' => (string) $group->id, 'name' => $group->title, 'description' => $group->description, - 'active' => $group->active + 'active' => $group->active, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/TransactionController.php b/app/Api/V1/Controllers/Autocomplete/TransactionController.php index 3b88b39427..6f17845992 100644 --- a/app/Api/V1/Controllers/Autocomplete/TransactionController.php +++ b/app/Api/V1/Controllers/Autocomplete/TransactionController.php @@ -53,7 +53,7 @@ class TransactionController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); $this->groupRepository = app(TransactionGroupRepositoryInterface::class); $this->repository->setUser($this->user); $this->repository->setUserGroup($this->userGroup); @@ -66,7 +66,7 @@ class TransactionController extends Controller public function transactions(AutocompleteTransactionApiRequest $request): JsonResponse { - $result = $this->repository->searchJournalDescriptions($request->attributes->get('query'), $request->attributes->get('limit')); + $result = $this->repository->searchJournalDescriptions($request->attributes->get('query'), $request->attributes->get('limit')); // limit and unique $filtered = $result->unique('description'); @@ -78,7 +78,7 @@ class TransactionController extends Controller 'id' => (string) $journal->id, 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => $journal->description, - 'description' => $journal->description + 'description' => $journal->description, ]; } @@ -103,7 +103,7 @@ class TransactionController extends Controller } // limit and unique - $array = []; + $array = []; /** @var TransactionJournal $journal */ foreach ($result as $journal) { @@ -111,7 +111,7 @@ class TransactionController extends Controller 'id' => (string) $journal->id, 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), - 'description' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description) + 'description' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), ]; } diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 7f07f63622..36effec09a 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -51,7 +51,7 @@ class AccountController extends Controller protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - private array $chartData = []; + private array $chartData = []; private AccountRepositoryInterface $repository; /** @@ -99,18 +99,18 @@ class AccountController extends Controller private function renderAccountData(array $params, Account $account): void { Log::debug(sprintf('Now in %s(array, #%d)', __METHOD__, $account->id)); - $currency = $this->repository->getAccountCurrency($account); - $currentStart = clone $params['start']; - $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToPrimary); - $period = $params['period'] ?? '1D'; + $currency = $this->repository->getAccountCurrency($account); + $currentStart = clone $params['start']; + $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToPrimary); + $period = $params['period'] ?? '1D'; - $previous = array_values($range)[0]['balance']; - $pcPrevious = null; + $previous = array_values($range)[0]['balance']; + $pcPrevious = null; if (!$currency instanceof TransactionCurrency) { $currency = $this->primaryCurrency; } - $currentSet = [ - 'label' => $account->name, + $currentSet = [ + 'label' => $account->name, // the currency that belongs to the account. 'currency_id' => (string) $currency->id, @@ -120,43 +120,43 @@ class AccountController extends Controller 'currency_decimal_places' => $currency->decimal_places, // the primary currency - 'primary_currency_id' => (string) $this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, // the default currency of the user (could be the same!) - 'date' => $params['start']->toAtomString(), - 'start_date' => $params['start']->toAtomString(), - 'end_date' => $params['end']->toAtomString(), - 'type' => 'line', - 'yAxisID' => 0, - 'period' => $period, - 'entries' => [], - 'pc_entries' => [] + 'date' => $params['start']->toAtomString(), + 'start_date' => $params['start']->toAtomString(), + 'end_date' => $params['end']->toAtomString(), + 'type' => 'line', + 'yAxisID' => 0, + 'period' => $period, + 'entries' => [], + 'pc_entries' => [], ]; if ($this->convertToPrimary) { - $currentSet['pc_entries'] = []; - $currentSet['primary_currency_id'] = (string) $this->primaryCurrency->id; - $currentSet['primary_currency_code'] = $this->primaryCurrency->code; - $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $currentSet['pc_entries'] = []; + $currentSet['primary_currency_id'] = (string) $this->primaryCurrency->id; + $currentSet['primary_currency_code'] = $this->primaryCurrency->code; + $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; $currentSet['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; - $pcPrevious = array_values($range)[0]['pc_balance']; + $pcPrevious = array_values($range)[0]['pc_balance']; } // create array of values to collect. while ($currentStart <= $params['end']) { - $format = $currentStart->format('Y-m-d'); - $label = $currentStart->toAtomString(); - $balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous; - $previous = $balance; + $format = $currentStart->format('Y-m-d'); + $label = $currentStart->toAtomString(); + $balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous; + $previous = $balance; $currentSet['entries'][$label] = $balance; // do the same for the primary currency balance, if relevant: - $pcBalance = null; + $pcBalance = null; if ($this->convertToPrimary) { - $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; - $pcPrevious = $pcBalance; + $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; + $pcPrevious = $pcBalance; $currentSet['pc_entries'][$label] = $pcBalance; } - $currentStart = Navigation::addPeriod($currentStart, $period); + $currentStart = Navigation::addPeriod($currentStart, $period); // $currentStart->addDay(); } diff --git a/app/Api/V1/Controllers/Chart/BalanceController.php b/app/Api/V1/Controllers/Chart/BalanceController.php index 74c69fcc2e..e65a3af8ad 100644 --- a/app/Api/V1/Controllers/Chart/BalanceController.php +++ b/app/Api/V1/Controllers/Chart/BalanceController.php @@ -47,7 +47,7 @@ class BalanceController extends Controller protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - private array $chartData = []; + private array $chartData = []; private GroupCollectorInterface $collector; private AccountRepositoryInterface $repository; @@ -59,7 +59,7 @@ class BalanceController extends Controller $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); $this->repository = app(AccountRepositoryInterface::class); - $this->collector = app(GroupCollectorInterface::class); + $this->collector = app(GroupCollectorInterface::class); $this->repository->setUserGroup($this->userGroup); $this->collector->setUserGroup($this->userGroup); $this->repository->setUser($this->user); @@ -95,11 +95,12 @@ class BalanceController extends Controller TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::RECONCILIATION->value, - TransactionTypeEnum::TRANSFER->value - ]); - $journals = $this->collector->getExtractedJournals(); + TransactionTypeEnum::TRANSFER->value, + ]) + ; + $journals = $this->collector->getExtractedJournals(); - $object = new AccountBalanceGrouped(); + $object = new AccountBalanceGrouped(); $object->setPreferredRange($queryParameters['period']); $object->setPrimary($this->primaryCurrency); $object->setAccounts($accounts); @@ -107,7 +108,7 @@ class BalanceController extends Controller $object->setStart($queryParameters['start']); $object->setEnd($queryParameters['end']); $object->groupByCurrencyAndPeriod(); - $data = $object->convertToChartData(); + $data = $object->convertToChartData(); foreach ($data as $entry) { $this->chartData[] = $entry; } diff --git a/app/Api/V1/Controllers/Chart/BudgetController.php b/app/Api/V1/Controllers/Chart/BudgetController.php index 7f19cc6d35..07fd41b6b5 100644 --- a/app/Api/V1/Controllers/Chart/BudgetController.php +++ b/app/Api/V1/Controllers/Chart/BudgetController.php @@ -56,7 +56,7 @@ class BudgetController extends Controller protected OperationsRepositoryInterface $opsRepository; private BudgetLimitRepositoryInterface $blRepository; - private array $currencies = []; + private array $currencies = []; private BudgetRepositoryInterface $repository; public function __construct() @@ -64,8 +64,8 @@ class BudgetController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); $this->repository->setUserGroup($this->userGroup); $this->opsRepository->setUserGroup($this->userGroup); @@ -86,10 +86,10 @@ class BudgetController extends Controller public function overview(DateRangeRequest $request): JsonResponse { /** @var Carbon $start */ - $start = $request->attributes->get('start'); + $start = $request->attributes->get('start'); /** @var Carbon $end */ - $end = $request->attributes->get('end'); + $end = $request->attributes->get('end'); // code from FrontpageChartGenerator, but not in separate class $budgets = $this->repository->getActiveBudgets(); @@ -123,48 +123,48 @@ class BudgetController extends Controller */ foreach ($expenses as $currencyId => $row) { // budgeted, left and overspent are now 0. - $limit = $this->filterLimit($currencyId, $limits); + $limit = $this->filterLimit($currencyId, $limits); // primary currency entries - $row['pc_budgeted'] = '0'; - $row['pc_spent'] = '0'; - $row['pc_left'] = '0'; + $row['pc_budgeted'] = '0'; + $row['pc_spent'] = '0'; + $row['pc_left'] = '0'; $row['pc_overspent'] = '0'; if ($limit instanceof BudgetLimit) { - $row['budgeted'] = $limit->amount; - $row['left'] = bcsub((string) $row['budgeted'], bcmul((string) $row['spent'], '-1')); + $row['budgeted'] = $limit->amount; + $row['left'] = bcsub((string) $row['budgeted'], bcmul((string) $row['spent'], '-1')); $row['overspent'] = bcmul($row['left'], '-1'); - $row['left'] = 1 === bccomp($row['left'], '0') ? $row['left'] : '0'; + $row['left'] = 1 === bccomp($row['left'], '0') ? $row['left'] : '0'; $row['overspent'] = 1 === bccomp($row['overspent'], '0') ? $row['overspent'] : '0'; } // convert data if necessary. if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id) { $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $row['pc_budgeted'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['budgeted']); - $row['pc_spent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['spent']); - $row['pc_left'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['left']); + $row['pc_budgeted'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['budgeted']); + $row['pc_spent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['spent']); + $row['pc_left'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['left']); $row['pc_overspent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['overspent']); } if ($this->convertToPrimary && $currencyId === $this->primaryCurrency->id) { - $row['pc_budgeted'] = $row['budgeted']; - $row['pc_spent'] = $row['spent']; - $row['pc_left'] = $row['left']; + $row['pc_budgeted'] = $row['budgeted']; + $row['pc_spent'] = $row['spent']; + $row['pc_left'] = $row['left']; $row['pc_overspent'] = $row['overspent']; } - $rows[] = $row; + $rows[] = $row; } // is always an array - $return = []; + $return = []; foreach ($rows as $row) { - $current = [ - 'label' => $budget->name, - 'currency_id' => (string) $row['currency_id'], - 'currency_name' => $row['currency_name'], - 'currency_code' => $row['currency_code'], - 'currency_decimal_places' => $row['currency_decimal_places'], + $current = [ + 'label' => $budget->name, + 'currency_id' => (string) $row['currency_id'], + 'currency_name' => $row['currency_name'], + 'currency_code' => $row['currency_code'], + 'currency_decimal_places' => $row['currency_decimal_places'], 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -172,19 +172,19 @@ class BudgetController extends Controller 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'period' => null, - 'date' => $row['start'], - 'start_date' => $row['start'], - 'end_date' => $row['end'], - 'yAxisID' => 0, - 'type' => 'bar', - 'entries' => ['budgeted' => $row['budgeted'], 'spent' => $row['spent'], 'left' => $row['left'], 'overspent' => $row['overspent']], - 'pc_entries' => [ + 'period' => null, + 'date' => $row['start'], + 'start_date' => $row['start'], + 'end_date' => $row['end'], + 'yAxisID' => 0, + 'type' => 'bar', + 'entries' => ['budgeted' => $row['budgeted'], 'spent' => $row['spent'], 'left' => $row['left'], 'overspent' => $row['overspent']], + 'pc_entries' => [ 'budgeted' => $row['pc_budgeted'], 'spent' => $row['pc_spent'], 'left' => $row['pc_left'], - 'overspent' => $row['pc_overspent'] - ] + 'overspent' => $row['pc_overspent'], + ], ]; $return[] = $current; } @@ -224,7 +224,7 @@ class BudgetController extends Controller */ foreach ($spent as $currencyId => $block) { $this->currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $return[$currencyId] ??= [ + $return[$currencyId] ??= [ 'currency_id' => (string) $currencyId, 'currency_code' => $block['currency_code'], 'currency_name' => $block['currency_name'], @@ -235,7 +235,7 @@ class BudgetController extends Controller 'budgeted' => '0', 'spent' => '0', 'left' => '0', - 'overspent' => '0' + 'overspent' => '0', ]; $currentBudgetArray = $block['budgets'][$budgetId]; @@ -243,7 +243,7 @@ class BudgetController extends Controller /** @var array $journal */ foreach ($currentBudgetArray['transaction_journals'] as $journal) { /** @var numeric-string $amount */ - $amount = (string) $journal['amount']; + $amount = (string) $journal['amount']; $return[$currencyId]['spent'] = bcadd($return[$currencyId]['spent'], $amount); } } @@ -251,7 +251,7 @@ class BudgetController extends Controller return $return; } - private function filterLimit(int $currencyId, Collection $limits): null|BudgetLimit + private function filterLimit(int $currencyId, Collection $limits): ?BudgetLimit { $amount = '0'; $limit = null; diff --git a/app/Api/V1/Controllers/Chart/CategoryController.php b/app/Api/V1/Controllers/Chart/CategoryController.php index cd22995017..679dab4e5c 100644 --- a/app/Api/V1/Controllers/Chart/CategoryController.php +++ b/app/Api/V1/Controllers/Chart/CategoryController.php @@ -60,7 +60,7 @@ class CategoryController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->accountRepos = app(AccountRepositoryInterface::class); + $this->accountRepos = app(AccountRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); $this->accountRepos->setUserGroup($this->userGroup); $this->currencyRepos->setUserGroup($this->userGroup); @@ -82,7 +82,7 @@ class CategoryController extends Controller public function overview(DateRangeRequest $request): JsonResponse { /** @var Carbon $start */ - $start = $request->attributes->get('start'); + $start = $request->attributes->get('start'); /** @var Carbon $end */ $end = $request->attributes->get('end'); @@ -90,7 +90,7 @@ class CategoryController extends Controller AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::ASSET->value + AccountTypeEnum::ASSET->value, ]); $currencies = []; $return = []; @@ -98,26 +98,26 @@ class CategoryController extends Controller // get journals for entire period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->withAccountInformation(); $collector->setXorAccounts($accounts)->withCategoryInformation(); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value]); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($journals as $journal) { // find journal: - $journalCurrencyId = (int) $journal['currency_id']; - $type = $journal['transaction_type_type']; - $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId); + $journalCurrencyId = (int) $journal['currency_id']; + $type = $journal['transaction_type_type']; + $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId); $currencies[$journalCurrencyId] = $currency; - $currencyId = $currency->id; - $currencyName = $currency->name; - $currencyCode = $currency->code; - $currencySymbol = $currency->symbol; - $currencyDecimalPlaces = $currency->decimal_places; - $amount = Steam::positive((string) $journal['amount']); - $pcAmount = null; + $currencyId = $currency->id; + $currencyName = $currency->name; + $currencyCode = $currency->code; + $currencySymbol = $currency->symbol; + $currencyDecimalPlaces = $currency->decimal_places; + $amount = Steam::positive((string) $journal['amount']); + $pcAmount = null; // overrule if necessary: if ($this->convertToPrimary && $journalCurrencyId === $this->primaryCurrency->id) { @@ -133,8 +133,8 @@ class CategoryController extends Controller Log::debug(sprintf('Converted %s %s to %s %s', $journal['currency_code'], $amount, $this->primaryCurrency->code, $pcAmount)); } - $categoryName = $journal['category_name'] ?? (string) trans('firefly.no_category'); - $key = sprintf('%s-%s', $categoryName, $currencyCode); + $categoryName = $journal['category_name'] ?? (string) trans('firefly.no_category'); + $key = sprintf('%s-%s', $categoryName, $currencyCode); // create arrays $return[$key] ??= [ 'label' => $categoryName, @@ -154,7 +154,7 @@ class CategoryController extends Controller 'yAxisID' => 0, 'type' => 'bar', 'entries' => ['spent' => '0', 'earned' => '0'], - 'pc_entries' => ['spent' => '0', 'earned' => '0'] + 'pc_entries' => ['spent' => '0', 'earned' => '0'], ]; // add monies @@ -175,10 +175,10 @@ class CategoryController extends Controller } } } - $return = array_values($return); + $return = array_values($return); // order by amount - usort($return, static fn(array $a, array $b): int => ((float) $a['entries']['spent'] + (float) $a['entries']['earned']) + usort($return, static fn (array $a, array $b): int => ((float) $a['entries']['spent'] + (float) $a['entries']['earned']) < ((float) $b['entries']['spent'] + (float) $b['entries']['earned']) ? 1 : -1); diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php index 1ee342bcbc..eab84c1be8 100644 --- a/app/Api/V1/Controllers/Controller.php +++ b/app/Api/V1/Controllers/Controller.php @@ -66,9 +66,9 @@ abstract class Controller extends BaseController protected const string CONTENT_TYPE = 'application/vnd.api+json'; protected const string JSON_CONTENT_TYPE = 'application/json'; - protected array $accepts = ['application/json', 'application/vnd.api+json']; + protected array $accepts = ['application/json', 'application/vnd.api+json']; - protected bool $convertToPrimary = false; + protected bool $convertToPrimary = false; protected TransactionCurrency $primaryCurrency; /** @deprecated use Request classes */ @@ -83,9 +83,9 @@ abstract class Controller extends BaseController $this->middleware(function ($request, $next) { $this->parameters = $this->getParameters(); if (auth()->check()) { - $language = Steam::getLanguage(); + $language = Steam::getLanguage(); $this->convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); app()->setLocale($language); } @@ -99,18 +99,18 @@ abstract class Controller extends BaseController } #[Deprecated(message: <<<'TXT' - use Request classes - Method to grab all parameters from the URL - TXT)] + use Request classes + Method to grab all parameters from the URL + TXT)] private function getParameters(): ParameterBag { - $bag = new ParameterBag(); - $page = (int) request()->get('page'); - $page = min(max(1, $page), 2 ** 16); + $bag = new ParameterBag(); + $page = (int) request()->get('page'); + $page = min(max(1, $page), 2 ** 16); $bag->set('page', $page); // some date fields: - $dates = ['start', 'end', 'date']; + $dates = ['start', 'end', 'date']; foreach ($dates as $field) { $date = null; @@ -121,7 +121,7 @@ abstract class Controller extends BaseController Log::error($e->getMessage()); Log::error($e->getTraceAsString()); } - $obj = null; + $obj = null; if (null !== $date) { try { $obj = Carbon::parse((string) $date, config('app.timezone')); @@ -158,7 +158,7 @@ abstract class Controller extends BaseController ) { // set default for user: /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $pageSize = (int) Preferences::getForUser($user, 'listPageSize', 50)->data; $bag->set($integer, $pageSize); @@ -190,14 +190,14 @@ abstract class Controller extends BaseController $params[$key] = $value; } - return $return . http_build_query($params); + return $return.http_build_query($params); } final protected function getManager(): Manager { // create some objects: $manager = new Manager(); - $baseUrl = request()->getSchemeAndHttpHost() . '/api/v1'; + $baseUrl = request()->getSchemeAndHttpHost().'/api/v1'; $manager->setSerializer(new JsonApiSerializer($baseUrl)); return $manager; @@ -205,14 +205,14 @@ abstract class Controller extends BaseController final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array { - $manager = new Manager(); - $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost()); + $manager = new Manager(); + $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost()); // TODO add stuff to path? $manager->setSerializer(new JsonApiSerializer($baseUrl)); - $objects = $paginator->getCollection(); + $objects = $paginator->getCollection(); // the transformer, at this point, needs to collect information that ALL items in the collection // require, like meta-data and stuff like that, and save it for later. @@ -233,8 +233,8 @@ abstract class Controller extends BaseController final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array { // create some objects: - $manager = new Manager(); - $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost()); + $manager = new Manager(); + $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost()); $manager->setSerializer(new JsonApiSerializer($baseUrl)); $resource = new Item($object, $transformer, $key); diff --git a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php index 4f4012244c..38c615bd5b 100644 --- a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php +++ b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php @@ -74,7 +74,7 @@ class TransactionController extends Controller $destination = $this->repository->find((int) $params['update']['account_id']); /** @var AccountDestroyService $service */ - $service = app(AccountDestroyService::class); + $service = app(AccountDestroyService::class); $service->moveTransactions($original, $destination); } diff --git a/app/Api/V1/Controllers/Data/DestroyController.php b/app/Api/V1/Controllers/Data/DestroyController.php index ce9d9ab6dd..ab519becbe 100644 --- a/app/Api/V1/Controllers/Data/DestroyController.php +++ b/app/Api/V1/Controllers/Data/DestroyController.php @@ -72,8 +72,8 @@ class DestroyController extends Controller public function destroy(DestroyRequest $request): JsonResponse { - $objects = $request->getObjects(); - $this->unused = $request->boolean('unused'); + $objects = $request->getObjects(); + $this->unused = $request->boolean('unused'); $allExceptAssets = [ AccountTypeEnum::BENEFICIARY->value, @@ -85,7 +85,7 @@ class DestroyController extends Controller AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::RECONCILIATION->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; $all = [ AccountTypeEnum::ASSET->value, @@ -100,36 +100,36 @@ class DestroyController extends Controller AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::RECONCILIATION->value + AccountTypeEnum::RECONCILIATION->value, ]; $liabilities = [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value]; $transactions = [ TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ]; match ($objects) { - 'budgets' => $this->destroyBudgets(), - 'bills' => $this->destroyBills(), - 'piggy_banks' => $this->destroyPiggyBanks(), - 'rules' => $this->destroyRules(), - 'recurring' => $this->destroyRecurringTransactions(), - 'categories' => $this->destroyCategories(), - 'tags' => $this->destroyTags(), - 'object_groups' => $this->destroyObjectGroups(), + 'budgets' => $this->destroyBudgets(), + 'bills' => $this->destroyBills(), + 'piggy_banks' => $this->destroyPiggyBanks(), + 'rules' => $this->destroyRules(), + 'recurring' => $this->destroyRecurringTransactions(), + 'categories' => $this->destroyCategories(), + 'tags' => $this->destroyTags(), + 'object_groups' => $this->destroyObjectGroups(), 'not_assets_liabilities' => $this->destroyAccounts($allExceptAssets), - 'accounts' => $this->destroyAccounts($all), - 'asset_accounts' => $this->destroyAccounts([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]), - 'expense_accounts' => $this->destroyAccounts([AccountTypeEnum::BENEFICIARY->value, AccountTypeEnum::EXPENSE->value]), - 'revenue_accounts' => $this->destroyAccounts([AccountTypeEnum::REVENUE->value]), - 'liabilities' => $this->destroyAccounts($liabilities), - 'transactions' => $this->destroyTransactions($transactions), - 'withdrawals' => $this->destroyTransactions([TransactionTypeEnum::WITHDRAWAL->value]), - 'deposits' => $this->destroyTransactions([TransactionTypeEnum::DEPOSIT->value]), - 'transfers' => $this->destroyTransactions([TransactionTypeEnum::TRANSFER->value]), - default => throw new FireflyException(sprintf('200033: This endpoint can\'t handle object "%s"', $objects)) + 'accounts' => $this->destroyAccounts($all), + 'asset_accounts' => $this->destroyAccounts([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]), + 'expense_accounts' => $this->destroyAccounts([AccountTypeEnum::BENEFICIARY->value, AccountTypeEnum::EXPENSE->value]), + 'revenue_accounts' => $this->destroyAccounts([AccountTypeEnum::REVENUE->value]), + 'liabilities' => $this->destroyAccounts($liabilities), + 'transactions' => $this->destroyTransactions($transactions), + 'withdrawals' => $this->destroyTransactions([TransactionTypeEnum::WITHDRAWAL->value]), + 'deposits' => $this->destroyTransactions([TransactionTypeEnum::DEPOSIT->value]), + 'transfers' => $this->destroyTransactions([TransactionTypeEnum::TRANSFER->value]), + default => throw new FireflyException(sprintf('200033: This endpoint can\'t handle object "%s"', $objects)) }; Preferences::mark(); @@ -140,11 +140,11 @@ class DestroyController extends Controller private function destroyBudgets(): void { /** @var AvailableBudgetRepositoryInterface $abRepository */ - $abRepository = app(AvailableBudgetRepositoryInterface::class); + $abRepository = app(AvailableBudgetRepositoryInterface::class); $abRepository->destroyAll(); /** @var BudgetLimitRepositoryInterface $blRepository */ - $blRepository = app(BudgetLimitRepositoryInterface::class); + $blRepository = app(BudgetLimitRepositoryInterface::class); $blRepository->destroyAll(); /** @var BudgetRepositoryInterface $budgetRepository */ diff --git a/app/Api/V1/Controllers/Data/Export/ExportController.php b/app/Api/V1/Controllers/Data/Export/ExportController.php index ce4c1c8472..295cfff4d8 100644 --- a/app/Api/V1/Controllers/Data/Export/ExportController.php +++ b/app/Api/V1/Controllers/Data/Export/ExportController.php @@ -87,13 +87,14 @@ class ExportController extends Controller $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename=' . $fileName) + ->header('Content-Disposition', 'attachment; filename='.$fileName) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen((string) $data[$key])); + ->header('Content-Length', (string) strlen((string) $data[$key])) + ; return $response; } diff --git a/app/Api/V1/Controllers/Data/PurgeController.php b/app/Api/V1/Controllers/Data/PurgeController.php index c49e436a0b..2af2cd8bab 100644 --- a/app/Api/V1/Controllers/Data/PurgeController.php +++ b/app/Api/V1/Controllers/Data/PurgeController.php @@ -64,7 +64,7 @@ class PurgeController extends Controller public function purge(): JsonResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // some manual code, too lazy to call all repositories. diff --git a/app/Api/V1/Controllers/Insight/Expense/AccountController.php b/app/Api/V1/Controllers/Insight/Expense/AccountController.php index c4d71f3e3e..5a5c2ff85a 100644 --- a/app/Api/V1/Controllers/Insight/Expense/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Expense/AccountController.php @@ -51,8 +51,8 @@ class AccountController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); - $this->repository = app(AccountRepositoryInterface::class); + $user = auth()->user(); + $this->repository = app(AccountRepositoryInterface::class); $this->repository->setUser($user); $this->opsRepository = app(OperationsRepositoryInterface::class); @@ -77,8 +77,8 @@ class AccountController extends Controller 'name' => $expense['name'], 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } @@ -101,8 +101,8 @@ class AccountController extends Controller 'name' => $expense['name'], 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/BillController.php b/app/Api/V1/Controllers/Insight/Expense/BillController.php index 2b253bcca0..ca0ec0274e 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BillController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BillController.php @@ -47,7 +47,7 @@ class BillController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(BillRepositoryInterface::class); $this->repository->setUser($user); @@ -74,11 +74,11 @@ class BillController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->setBills($bills); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { $billId = (int) $journal['bill_id']; $currencyId = (int) $journal['currency_id']; @@ -104,7 +104,7 @@ class BillController extends Controller $journal[$field] ?? '0' )); - $key = sprintf('%d-%d', $billId, $currencyId); + $key = sprintf('%d-%d', $billId, $currencyId); if (0 !== $currencyId) { $response[$key] ??= [ @@ -113,9 +113,9 @@ class BillController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$key]['difference'] = bcadd($response[$key]['difference'], (string) ($journal[$field] ?? '0')); + $response[$key]['difference'] = bcadd($response[$key]['difference'], (string) ($journal[$field] ?? '0')); $response[$key]['difference_float'] = (float) $response[$key]['difference']; // intentional float } } @@ -136,11 +136,11 @@ class BillController extends Controller $response = []; // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->withoutBill(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { $currencyId = (int) $journal['currency_id']; @@ -164,9 +164,9 @@ class BillController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], (string) ($journal[$field] ?? '0')); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], (string) ($journal[$field] ?? '0')); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // intentional float } } diff --git a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php index 8b7d53b87e..076cd64293 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php @@ -50,9 +50,9 @@ class BudgetController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(BudgetRepositoryInterface::class); - $this->noRepository = app(NoBudgetRepositoryInterface::class); - $user = auth()->user(); + $this->repository = app(BudgetRepositoryInterface::class); + $this->noRepository = app(NoBudgetRepositoryInterface::class); + $user = auth()->user(); $this->opsRepository->setUser($user); $this->repository->setUser($user); $this->noRepository->setUser($user); @@ -83,8 +83,8 @@ class BudgetController extends Controller 'name' => $budget->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } } @@ -105,8 +105,8 @@ class BudgetController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php index 34d62bfb9d..00e996f553 100644 --- a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php @@ -50,9 +50,9 @@ class CategoryController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); $this->opsRepository->setUser($user); $this->repository->setUser($user); $this->noRepository->setUser($user); @@ -83,8 +83,8 @@ class CategoryController extends Controller 'name' => $category->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } } @@ -105,8 +105,8 @@ class CategoryController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php index db65c264c8..24e408cd5c 100644 --- a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // same code as many other sumExpense methods. I think this needs some kind of generic method. - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyCode = $journal['currency_code']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyCode = $journal['currency_code']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -77,9 +77,9 @@ class PeriodController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // intentional float } diff --git a/app/Api/V1/Controllers/Insight/Expense/TagController.php b/app/Api/V1/Controllers/Insight/Expense/TagController.php index b98e5898c5..f42e3d04a9 100644 --- a/app/Api/V1/Controllers/Insight/Expense/TagController.php +++ b/app/Api/V1/Controllers/Insight/Expense/TagController.php @@ -67,17 +67,17 @@ class TagController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // same code as many other sumExpense methods. I think this needs some kind of generic method. - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyCode = $journal['currency_code']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyCode = $journal['currency_code']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -100,9 +100,9 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // float but on purpose. } @@ -114,11 +114,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -126,7 +126,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -150,21 +150,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'] + 'currency_code' => $journal['currency_code'], ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], (string) $journal['amount']); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], (string) $journal['amount']); $response[$key]['difference_float'] = (float) $response[$key]['difference']; // float but on purpose. } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'] + 'currency_code' => $journal['foreign_currency_code'], ]; - $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], (string) $journal['foreign_amount']); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], (string) $journal['foreign_amount']); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; // float but on purpose. } } diff --git a/app/Api/V1/Controllers/Insight/Income/AccountController.php b/app/Api/V1/Controllers/Insight/Income/AccountController.php index 9343a9ff4a..f151c62873 100644 --- a/app/Api/V1/Controllers/Insight/Income/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Income/AccountController.php @@ -51,8 +51,8 @@ class AccountController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); - $this->repository = app(AccountRepositoryInterface::class); + $user = auth()->user(); + $this->repository = app(AccountRepositoryInterface::class); $this->repository->setUser($user); $this->opsRepository = app(OperationsRepositoryInterface::class); @@ -68,8 +68,8 @@ class AccountController extends Controller $end = $request->getEnd(); $assetAccounts = $request->getAssetAccounts(); - $income = $this->opsRepository->sumIncomeByDestination($start, $end, $assetAccounts); - $result = []; + $income = $this->opsRepository->sumIncomeByDestination($start, $end, $assetAccounts); + $result = []; /** @var array $entry */ foreach ($income as $entry) { @@ -78,8 +78,8 @@ class AccountController extends Controller 'name' => $entry['name'], 'difference' => $entry['sum'], 'difference_float' => (float) $entry['sum'], // float but on purpose. - 'currency_id' => (string) $entry['currency_id'], - 'currency_code' => $entry['currency_code'] + 'currency_id' => (string) $entry['currency_id'], + 'currency_code' => $entry['currency_code'], ]; } @@ -102,8 +102,8 @@ class AccountController extends Controller 'name' => $entry['name'], 'difference' => $entry['sum'], 'difference_float' => (float) $entry['sum'], // float but on purpose. - 'currency_id' => (string) $entry['currency_id'], - 'currency_code' => $entry['currency_code'] + 'currency_id' => (string) $entry['currency_id'], + 'currency_code' => $entry['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/CategoryController.php b/app/Api/V1/Controllers/Insight/Income/CategoryController.php index 774a8d91af..6690239fd3 100644 --- a/app/Api/V1/Controllers/Insight/Income/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Income/CategoryController.php @@ -50,9 +50,9 @@ class CategoryController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); $this->opsRepository->setUser($user); $this->repository->setUser($user); $this->noRepository->setUser($user); @@ -83,8 +83,8 @@ class CategoryController extends Controller 'name' => $category->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // float but on purpose. - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } } @@ -105,8 +105,8 @@ class CategoryController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // float but on purpose. - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/PeriodController.php b/app/Api/V1/Controllers/Insight/Income/PeriodController.php index 9fd3f92490..f413788066 100644 --- a/app/Api/V1/Controllers/Insight/Income/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Income/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -70,9 +70,9 @@ class PeriodController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // float but on purpose. } diff --git a/app/Api/V1/Controllers/Insight/Income/TagController.php b/app/Api/V1/Controllers/Insight/Income/TagController.php index 168bd891d9..903aafd498 100644 --- a/app/Api/V1/Controllers/Insight/Income/TagController.php +++ b/app/Api/V1/Controllers/Insight/Income/TagController.php @@ -47,7 +47,7 @@ class TagController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -68,17 +68,17 @@ class TagController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -94,9 +94,9 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } @@ -108,11 +108,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -120,7 +120,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -144,21 +144,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'] + 'currency_code' => $journal['currency_code'], ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'] + 'currency_code' => $journal['foreign_currency_code'], ]; - $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Transfer/AccountController.php b/app/Api/V1/Controllers/Insight/Transfer/AccountController.php index 968f22bd64..2a48129c14 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/AccountController.php @@ -46,7 +46,7 @@ class AccountController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); + $user = auth()->user(); $this->opsRepository = app(OperationsRepositoryInterface::class); $this->opsRepository->setUser($user); diff --git a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php index 9c8083932c..580f16be0d 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php @@ -50,9 +50,9 @@ class CategoryController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); $this->opsRepository->setUser($user); $this->repository->setUser($user); $this->noRepository->setUser($user); @@ -84,7 +84,7 @@ class CategoryController extends Controller 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_code' => $expense['currency_code'], ]; } } @@ -106,7 +106,7 @@ class CategoryController extends Controller 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'] + 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php index 2532bf53b0..004aede122 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -70,9 +70,9 @@ class PeriodController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/TagController.php b/app/Api/V1/Controllers/Insight/Transfer/TagController.php index 4dce153611..89bc03a155 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/TagController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/TagController.php @@ -47,7 +47,7 @@ class TagController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -65,17 +65,17 @@ class TagController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -91,9 +91,9 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode + 'currency_code' => $currencyCode, ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } @@ -105,11 +105,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -117,7 +117,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -141,21 +141,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'] + 'currency_code' => $journal['currency_code'], ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'] + 'currency_code' => $journal['foreign_currency_code'], ]; - $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; // intentional float } } diff --git a/app/Api/V1/Controllers/Models/Account/ListController.php b/app/Api/V1/Controllers/Models/Account/ListController.php index 47caec7efa..a092a83bbb 100644 --- a/app/Api/V1/Controllers/Models/Account/ListController.php +++ b/app/Api/V1/Controllers/Models/Account/ListController.php @@ -70,21 +70,21 @@ class ListController extends Controller public function attachments(PaginationRequest $request, Account $account): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); - $collection = $this->repository->getAttachments($account); + $collection = $this->repository->getAttachments($account); - $count = $collection->count(); - $attachments = $collection->slice($offset, $limit); + $count = $collection->count(); + $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.attachments', [$account->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.attachments', [$account->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ - $transformer = app(AttachmentTransformer::class); + $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -93,31 +93,31 @@ class ListController extends Controller public function piggyBanks(PaginationRequest $request, Account $account): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks($account); - $count = $collection->count(); - $piggyBanks = $collection->slice($offset, $limit); + $collection = $this->repository->getPiggyBanks($account); + $count = $collection->count(); + $piggyBanks = $collection->slice($offset, $limit); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.piggy-banks', [$account->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.piggy-banks', [$account->id]).$this->buildParams()); /** @var PiggyBankTransformer $transformer */ - $transformer = app(PiggyBankTransformer::class); + $transformer = app(PiggyBankTransformer::class); // $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -129,14 +129,14 @@ class ListController extends Controller public function transactions(PaginationDateRangeRequest $request, Account $account): JsonResponse { ['limit' => $limit, 'page' => $page, 'start' => $start, 'end' => $end, 'types' => $types] = $request->attributes->all(); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($admin)->setAccounts(new Collection()->push($account))->withAPIInformation()->setLimit($limit)->setPage($page)->setTypes($types); if (null !== $start) { $collector->setStart($start); @@ -145,18 +145,18 @@ class ListController extends Controller $collector->setEnd($end); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.accounts.transactions', [$account->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.accounts.transactions', [$account->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $transactions = $enrichment->enrich($paginator->getCollection()); + $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Account/ShowController.php b/app/Api/V1/Controllers/Models/Account/ShowController.php index 08cd1c0568..2a9c0f0ec2 100644 --- a/app/Api/V1/Controllers/Models/Account/ShowController.php +++ b/app/Api/V1/Controllers/Models/Account/ShowController.php @@ -68,7 +68,7 @@ class ShowController extends Controller */ public function index(ShowRequest $request): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); [ 'types' => $types, 'page' => $page, @@ -77,37 +77,37 @@ class ShowController extends Controller 'sort' => $sort, 'start' => $start, 'end' => $end, - 'date' => $date - ] = $request->attributes->all(); + 'date' => $date, + ] = $request->attributes->all(); // get list of accounts. Count it and split it. $this->repository->resetAccountOrder(); - $collection = $this->repository->getAccountsByType($types, $sort); - $count = $collection->count(); + $collection = $this->repository->getAccountsByType($types, $sort); + $count = $collection->count(); // continue sort: // TODO if the user sorts on DB dependent field there must be no slice before enrichment, only after. // TODO still need to figure out how to do this easily. - $accounts = $collection->slice($offset, $limit); + $accounts = $collection->slice($offset, $limit); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setSort($sort); $enrichment->setDate($date); $enrichment->setStart($start); $enrichment->setEnd($end); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.index').$this->buildParams()); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); - $resource = new FractalCollection($accounts, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($accounts, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -124,22 +124,22 @@ class ShowController extends Controller // get list of accounts. Count it and split it. $this->repository->resetAccountOrder(); $account->refresh(); - $manager = $this->getManager(); + $manager = $this->getManager(); ['start' => $start, 'end' => $end, 'date' => $date] = $request->attributes->all(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($date); $enrichment->setStart($start); $enrichment->setEnd($end); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $transformer = app(AccountTransformer::class); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Account/StoreController.php b/app/Api/V1/Controllers/Models/Account/StoreController.php index 521e2b5c75..4369470d4d 100644 --- a/app/Api/V1/Controllers/Models/Account/StoreController.php +++ b/app/Api/V1/Controllers/Models/Account/StoreController.php @@ -64,23 +64,23 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAllAccountData(); + $data = $request->getAllAccountData(); $this->repository->resetAccountOrder(); - $account = $this->repository->store($data); - $manager = $this->getManager(); + $account = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Account/UpdateController.php b/app/Api/V1/Controllers/Models/Account/UpdateController.php index 526d1aadfa..60eb57fbb6 100644 --- a/app/Api/V1/Controllers/Models/Account/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Account/UpdateController.php @@ -68,24 +68,24 @@ class UpdateController extends Controller public function update(UpdateRequest $request, Account $account): JsonResponse { Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getUpdateData(); - $data['type'] = config('firefly.shortNamesByFullName.' . $account->accountType->type); - $account = $this->repository->update($account, $data); - $manager = $this->getManager(); + $data = $request->getUpdateData(); + $data['type'] = config('firefly.shortNamesByFullName.'.$account->accountType->type); + $account = $this->repository->update($account, $data); + $manager = $this->getManager(); $account->refresh(); Preferences::mark(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $transformer = app(AccountTransformer::class); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php index 98181e7eb1..23df884307 100644 --- a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php @@ -50,7 +50,7 @@ class DestroyController extends Controller $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/Attachment/ShowController.php b/app/Api/V1/Controllers/Models/Attachment/ShowController.php index 844f5ae3f9..41b1da901b 100644 --- a/app/Api/V1/Controllers/Models/Attachment/ShowController.php +++ b/app/Api/V1/Controllers/Models/Attachment/ShowController.php @@ -57,7 +57,7 @@ class ShowController extends Controller $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); @@ -87,24 +87,25 @@ class ShowController extends Controller throw new FireflyException('200000: File has not been uploaded (yet).'); } if ($this->repository->exists($attachment)) { - $content = $this->repository->getContent($attachment); + $content = $this->repository->getContent($attachment); if ('' === $content) { throw new FireflyException('200002: File is empty (zero bytes).'); } - $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); + $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); /** @var LaravelResponse $response */ $response = response($content); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename=' . $quoted) + ->header('Content-Disposition', 'attachment; filename='.$quoted) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen($content)); + ->header('Content-Length', (string) strlen($content)) + ; return $response; } @@ -128,21 +129,21 @@ class ShowController extends Controller throw new NotFoundHttpException(); } - $manager = $this->getManager(); + $manager = $this->getManager(); // get list of attachments. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $attachments = $collection->slice($offset, $limit); + $collection = $this->repository->get(); + $count = $collection->count(); + $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.attachments.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.attachments.index').$this->buildParams()); /** @var AttachmentTransformer $transformer */ - $transformer = app(AttachmentTransformer::class); + $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -161,12 +162,12 @@ class ShowController extends Controller throw new NotFoundHttpException(); } - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/StoreController.php b/app/Api/V1/Controllers/Models/Attachment/StoreController.php index b623993844..c7ce834fe8 100644 --- a/app/Api/V1/Controllers/Models/Attachment/StoreController.php +++ b/app/Api/V1/Controllers/Models/Attachment/StoreController.php @@ -55,7 +55,7 @@ class StoreController extends Controller $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); @@ -79,14 +79,14 @@ class StoreController extends Controller throw new NotFoundHttpException(); } Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getAll(); - $attachment = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $attachment = $this->repository->store($data); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php index 5b7900490a..a69ad515d0 100644 --- a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php @@ -52,7 +52,7 @@ class UpdateController extends Controller $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); @@ -73,14 +73,14 @@ class UpdateController extends Controller throw new NotFoundHttpException(); } - $data = $request->getAll(); + $data = $request->getAll(); $this->repository->update($attachment, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php index 638903e488..71e77638d7 100644 --- a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php +++ b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php @@ -52,7 +52,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->abRepository->setUser($user); @@ -68,29 +68,29 @@ class ShowController extends Controller */ public function index(PaginationDateRangeRequest $request): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); ['limit' => $limit, 'offset' => $offset, 'page' => $page, 'start' => $start, 'end' => $end] = $request->attributes->all(); // get list of available budgets. Count it and split it. - $collection = $this->abRepository->getAvailableBudgetsByDate($start, $end); - $count = $collection->count(); - $availableBudgets = $collection->slice($offset, $limit); + $collection = $this->abRepository->getAvailableBudgetsByDate($start, $end); + $count = $collection->count(); + $availableBudgets = $collection->slice($offset, $limit); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AvailableBudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new AvailableBudgetEnrichment(); $enrichment->setUser($admin); - $availableBudgets = $enrichment->enrich($availableBudgets); + $availableBudgets = $enrichment->enrich($availableBudgets); // make paginator: - $paginator = new LengthAwarePaginator($availableBudgets, $count, $limit, $page); - $paginator->setPath(route('api.v1.available-budgets.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($availableBudgets, $count, $limit, $page); + $paginator->setPath(route('api.v1.available-budgets.index').$this->buildParams()); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); - $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); + $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -104,21 +104,21 @@ class ShowController extends Controller */ public function show(AvailableBudget $availableBudget): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // $start = $this->parameters->get('start'); // $end = $this->parameters->get('end'); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AvailableBudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new AvailableBudgetEnrichment(); $enrichment->setUser($admin); $availableBudget = $enrichment->enrichSingle($availableBudget); - $resource = new Item($availableBudget, $transformer, 'available_budgets'); + $resource = new Item($availableBudget, $transformer, 'available_budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/ListController.php b/app/Api/V1/Controllers/Models/Bill/ListController.php index 6d90120acb..02e6c9571d 100644 --- a/app/Api/V1/Controllers/Models/Bill/ListController.php +++ b/app/Api/V1/Controllers/Models/Bill/ListController.php @@ -73,20 +73,20 @@ class ListController extends Controller public function attachments(PaginationRequest $request, Bill $bill): JsonResponse { ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); - $manager = $this->getManager(); - $collection = $this->repository->getAttachments($bill); + $manager = $this->getManager(); + $collection = $this->repository->getAttachments($bill); - $count = $collection->count(); - $attachments = $collection->slice($offset, $limit); + $count = $collection->count(); + $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.bills.attachments', [$bill->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.bills.attachments', [$bill->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ - $transformer = app(AttachmentTransformer::class); + $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -102,18 +102,18 @@ class ListController extends Controller { ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); - $manager = $this->getManager(); - $collection = $this->repository->getRulesForBill($bill); - $count = $collection->count(); - $rules = $collection->slice($offset, $limit); + $manager = $this->getManager(); + $collection = $this->repository->getRulesForBill($bill); + $count = $collection->count(); + $rules = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $limit, $page); - $paginator->setPath(route('api.v1.bills.rules', [$bill->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $limit, $page); + $paginator->setPath(route('api.v1.bills.rules', [$bill->id]).$this->buildParams()); /** @var RuleTransformer $transformer */ - $transformer = app(RuleTransformer::class); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $transformer = app(RuleTransformer::class); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -129,14 +129,14 @@ class ListController extends Controller { ['limit' => $limit, 'page' => $page, 'types' => $types, 'start' => $start, 'end' => $end] = $request->attributes->all(); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // include source + destination account name and type. @@ -148,7 +148,8 @@ class ListController extends Controller // set page to retrieve ->setPage($page) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $start) { $collector->setStart($start); @@ -158,18 +159,18 @@ class ListController extends Controller } // get paginator. - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.bills.transactions', [$bill->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.bills.transactions', [$bill->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $transactions = $enrichment->enrich($paginator->getCollection()); + $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Bill/ShowController.php b/app/Api/V1/Controllers/Models/Bill/ShowController.php index 3cb71f90c5..d2e4238ab2 100644 --- a/app/Api/V1/Controllers/Models/Bill/ShowController.php +++ b/app/Api/V1/Controllers/Models/Bill/ShowController.php @@ -70,25 +70,25 @@ class ShowController extends Controller ['limit' => $limit, 'offset' => $offset, 'start' => $start, 'end' => $end, 'page' => $page] = $request->attributes->all(); $this->repository->correctOrder(); - $bills = $this->repository->getBills(); - $manager = $this->getManager(); - $count = $bills->count(); - $bills = $bills->slice($offset, $limit); - $paginator = new LengthAwarePaginator($bills, $count, $limit, $page); + $bills = $this->repository->getBills(); + $manager = $this->getManager(); + $count = $bills->count(); + $bills = $bills->slice($offset, $limit); + $paginator = new LengthAwarePaginator($bills, $count, $limit, $page); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); /** @var BillTransformer $transformer */ - $transformer = app(BillTransformer::class); + $transformer = app(BillTransformer::class); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -104,21 +104,21 @@ class ShowController extends Controller { ['start' => $start, 'end' => $end] = $request->attributes->all(); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ - $transformer = app(BillTransformer::class); + $transformer = app(BillTransformer::class); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.php index 2c45baa991..f6787572b3 100644 --- a/app/Api/V1/Controllers/Models/Bill/StoreController.php +++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php @@ -68,24 +68,24 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $bill = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/UpdateController.php b/app/Api/V1/Controllers/Models/Bill/UpdateController.php index c84e5d4c88..9824103e5a 100644 --- a/app/Api/V1/Controllers/Models/Bill/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Bill/UpdateController.php @@ -63,24 +63,24 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Bill $bill): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->update($bill, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $bill = $this->repository->update($bill, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/ListController.php b/app/Api/V1/Controllers/Models/Budget/ListController.php index 6fd01dbeed..92d9d1fc7b 100644 --- a/app/Api/V1/Controllers/Models/Budget/ListController.php +++ b/app/Api/V1/Controllers/Models/Budget/ListController.php @@ -58,7 +58,7 @@ class ListController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->setUser(auth()->user()); $this->blRepository->setUser(auth()->user()); @@ -73,22 +73,22 @@ class ListController extends Controller */ public function attachments(Budget $budget): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($budget); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($budget); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.attachments', [$budget->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.budgets.attachments', [$budget->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -102,26 +102,26 @@ class ListController extends Controller */ public function budgetLimits(Budget $budget): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); $this->parameters->set('budget_id', $budget->id); $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.budget-limits', [$budget->id]) . $this->buildParams()); + $paginator->setPath(route('api.v1.budgets.budget-limits', [$budget->id]).$this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -135,20 +135,20 @@ class ListController extends Controller */ public function transactions(Request $request, Budget $budget): JsonResponse { - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on budget. @@ -160,7 +160,8 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -169,18 +170,18 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.transactions', [$budget->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.transactions', [$budget->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -194,20 +195,20 @@ class ListController extends Controller */ public function withoutBudget(Request $request): JsonResponse { - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // withdrawals only @@ -221,7 +222,8 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -230,18 +232,18 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.without-budget') . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.without-budget').$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Budget/ShowController.php b/app/Api/V1/Controllers/Models/Budget/ShowController.php index 756258c780..e0acca2b76 100644 --- a/app/Api/V1/Controllers/Models/Budget/ShowController.php +++ b/app/Api/V1/Controllers/Models/Budget/ShowController.php @@ -52,7 +52,7 @@ class ShowController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->setUser(auth()->user()); $this->blRepository->setUser(auth()->user()); @@ -69,34 +69,34 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->getBudgets(); - $count = $collection->count(); - $budgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getBudgets(); + $count = $collection->count(); + $budgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $budgets = $enrichment->enrich($budgets); + $budgets = $enrichment->enrich($budgets); // make paginator: - $paginator = new LengthAwarePaginator($budgets, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($budgets, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.budgets.index').$this->buildParams()); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgets, $transformer, 'budgets'); + $resource = new FractalCollection($budgets, $transformer, 'budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -107,22 +107,22 @@ class ShowController extends Controller */ public function show(Budget $budget): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/StoreController.php b/app/Api/V1/Controllers/Models/Budget/StoreController.php index 4d8658707e..db9416f1cb 100644 --- a/app/Api/V1/Controllers/Models/Budget/StoreController.php +++ b/app/Api/V1/Controllers/Models/Budget/StoreController.php @@ -65,24 +65,24 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; - $budget = $this->repository->store($data); + $budget = $this->repository->store($data); $budget->refresh(); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/UpdateController.php b/app/Api/V1/Controllers/Models/Budget/UpdateController.php index f7d64ac91f..bfb9d8478e 100644 --- a/app/Api/V1/Controllers/Models/Budget/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Budget/UpdateController.php @@ -57,23 +57,23 @@ class UpdateController extends Controller public function update(UpdateRequest $request, Budget $budget): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; - $budget = $this->repository->update($budget, $data); - $manager = $this->getManager(); + $budget = $this->repository->update($budget, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php b/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php index c06607e9ac..fb648c564d 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php @@ -48,7 +48,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->blRepository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php index 5896a5e96f..f21f276843 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php @@ -51,19 +51,19 @@ class ListController extends Controller */ public function transactions(Request $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on budget. @@ -75,23 +75,24 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; $collector->setRange($budgetLimit->start_date, $budgetLimit->end_date); $collector->setTypes($types); - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.limits.transactions', [$budget->id, $budgetLimit->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.limits.transactions', [$budget->id, $budgetLimit->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php index 7d4029f68e..9b84a1e6fe 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php @@ -57,8 +57,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); - $this->repository = app(BudgetRepositoryInterface::class); + $user = auth()->user(); + $this->repository = app(BudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->setUser($user); $this->blRepository->setUser($user); @@ -76,35 +76,35 @@ class ShowController extends Controller public function index(Budget $budget): JsonResponse { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // enrich budget: - $enrichment = new BudgetEnrichment(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); /** @var Budget $budget */ - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); - $manager = $this->getManager(); + $manager = $this->getManager(); $manager->parseIncludes('budget'); $pageSize = $this->parameters->get('limit'); $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.limits.index', [$budget->id]) . $this->buildParams()); + $paginator->setPath(route('api.v1.budgets.limits.index', [$budget->id]).$this->buildParams()); // enrich - $enrichment = new BudgetLimitEnrichment(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -120,27 +120,27 @@ class ShowController extends Controller */ public function indexAll(SameDateRequest $request): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); $manager->parseIncludes('budget'); $pageSize = $this->parameters->get('limit'); $collection = $this->blRepository->getAllBudgetLimits($this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budget-limits.index') . $this->buildParams()); + $paginator->setPath(route('api.v1.budget-limits.index').$this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -158,19 +158,19 @@ class ShowController extends Controller throw new FireflyException('20028: The budget limit does not belong to the budget.'); } // continue! - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ $transformer = app(BudgetLimitTransformer::class); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php index 9fa8c07ce6..7ce95da4ad 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php @@ -49,7 +49,7 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->blRepository->setUser($user); @@ -65,27 +65,27 @@ class StoreController extends Controller */ public function store(StoreRequest $request, Budget $budget): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['start_date'] = $data['start']; - $data['end_date'] = $data['end']; + $data['end_date'] = $data['end']; $data['fire_webhooks'] ??= true; - $data['budget_id'] = $budget->id; + $data['budget_id'] = $budget->id; - $budgetLimit = $this->blRepository->store($data); - $manager = $this->getManager(); + $budgetLimit = $this->blRepository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); - $budgetLimit = $enrichment->enrichSingle($budgetLimit); + $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php index 5af898a023..2e71ab25bb 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php @@ -54,7 +54,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->blRepository->setUser($user); @@ -74,24 +74,24 @@ class UpdateController extends Controller if ($budget->id !== $budgetLimit->budget_id) { throw new FireflyException('20028: The budget limit does not belong to the budget.'); } - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; $data['budget_id'] = $budget->id; - $budgetLimit = $this->blRepository->update($budgetLimit, $data); - $manager = $this->getManager(); + $budgetLimit = $this->blRepository->update($budgetLimit, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); - $budgetLimit = $enrichment->enrichSingle($budgetLimit); + $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/ListController.php b/app/Api/V1/Controllers/Models/Category/ListController.php index 62a64811bd..46ce84caed 100644 --- a/app/Api/V1/Controllers/Models/Category/ListController.php +++ b/app/Api/V1/Controllers/Models/Category/ListController.php @@ -68,22 +68,22 @@ class ListController extends Controller */ public function attachments(Category $category): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($category); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($category); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.categories.attachments', [$category->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.categories.attachments', [$category->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -97,19 +97,19 @@ class ListController extends Controller */ public function transactions(Request $request, Category $category): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on category. @@ -121,7 +121,8 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -130,19 +131,19 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.categories.transactions', [$category->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.categories.transactions', [$category->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Category/ShowController.php b/app/Api/V1/Controllers/Models/Category/ShowController.php index d4e6db27b3..b8b8df00bb 100644 --- a/app/Api/V1/Controllers/Models/Category/ShowController.php +++ b/app/Api/V1/Controllers/Models/Category/ShowController.php @@ -65,33 +65,33 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->getCategories(); - $count = $collection->count(); - $categories = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getCategories(); + $count = $collection->count(); + $categories = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $categories = $enrichment->enrich($categories); + $categories = $enrichment->enrich($categories); // make paginator: - $paginator = new LengthAwarePaginator($categories, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.categories.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($categories, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.categories.index').$this->buildParams()); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($categories, $transformer, 'categories'); + $resource = new FractalCollection($categories, $transformer, 'categories'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -105,7 +105,7 @@ class ShowController extends Controller */ public function show(Category $category): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -113,14 +113,14 @@ class ShowController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/StoreController.php b/app/Api/V1/Controllers/Models/Category/StoreController.php index a4082580c7..99ed2d0e61 100644 --- a/app/Api/V1/Controllers/Models/Category/StoreController.php +++ b/app/Api/V1/Controllers/Models/Category/StoreController.php @@ -65,8 +65,8 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $category = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $category = $this->repository->store($request->getAll()); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -74,14 +74,14 @@ class StoreController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/UpdateController.php b/app/Api/V1/Controllers/Models/Category/UpdateController.php index 35340733e0..c9a7c8910b 100644 --- a/app/Api/V1/Controllers/Models/Category/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Category/UpdateController.php @@ -63,9 +63,9 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Category $category): JsonResponse { - $data = $request->getAll(); - $category = $this->repository->update($category, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $category = $this->repository->update($category, $data); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -73,14 +73,14 @@ class UpdateController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php index 6a6512f5e3..116f7f913f 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php @@ -42,7 +42,7 @@ class DestroyController extends Controller public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php index ff8f0fe566..4f55c411e9 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php @@ -42,7 +42,7 @@ class IndexController extends Controller public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php index f5b4095e7d..11cf33a539 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php @@ -46,7 +46,7 @@ class ShowController extends Controller public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() @@ -62,12 +62,12 @@ class ShowController extends Controller public function show(TransactionCurrency $from, TransactionCurrency $to): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $page = $this->parameters->get('page'); - $rates = $this->repository->getRates($from, $to); - $count = $rates->count(); - $rates = $rates->slice(($page - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($rates, $count, $pageSize, $page); + $pageSize = $this->parameters->get('limit'); + $page = $this->parameters->get('page'); + $rates = $this->repository->getRates($from, $to); + $count = $rates->count(); + $rates = $rates->slice(($page - 1) * $pageSize, $pageSize); + $paginator = new LengthAwarePaginator($rates, $count, $pageSize, $page); $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); // give params to transformer @@ -85,7 +85,7 @@ class ShowController extends Controller public function showSingleByDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse { - $transformer = new ExchangeRateTransformer(); + $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); $exchangeRate = $this->repository->getSpecificRateOnDate($from, $to, $date); diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php index d0253019a2..039437e83a 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php @@ -47,7 +47,7 @@ class StoreController extends Controller public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() @@ -63,8 +63,8 @@ class StoreController extends Controller public function storeByCurrencies(StoreByCurrenciesRequest $request, TransactionCurrency $from, TransactionCurrency $to): JsonResponse { - $data = $request->getAll(); - $collection = new Collection(); + $data = $request->getAll(); + $collection = new Collection(); foreach ($data as $date => $rate) { $date = Carbon::createFromFormat('Y-m-d', $date); @@ -76,7 +76,7 @@ class StoreController extends Controller continue; } - $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); + $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); $collection->push($new); } @@ -90,9 +90,9 @@ class StoreController extends Controller public function storeByDate(StoreByDateRequest $request, Carbon $date): JsonResponse { - $data = $request->getAll(); - $from = $request->getFromCurrency(); - $collection = new Collection(); + $data = $request->getAll(); + $from = $request->getFromCurrency(); + $collection = new Collection(); foreach ($data['rates'] as $key => $rate) { $to = Amount::getTransactionCurrencyByCode($key); $existing = $this->repository->getSpecificRateOnDate($from, $to, $date); @@ -103,7 +103,7 @@ class StoreController extends Controller continue; } - $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); + $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); $collection->push($new); } @@ -117,13 +117,13 @@ class StoreController extends Controller public function store(StoreRequest $request): JsonResponse { - $date = $request->getDate(); - $rate = $request->getRate(); - $from = $request->getFromCurrency(); - $to = $request->getToCurrency(); + $date = $request->getDate(); + $rate = $request->getRate(); + $from = $request->getFromCurrency(); + $to = $request->getToCurrency(); // already has rate? - $object = $this->repository->getSpecificRateOnDate($from, $to, $date); + $object = $this->repository->getSpecificRateOnDate($from, $to, $date); if ($object instanceof CurrencyExchangeRate) { // just update it, no matter. $rate = $this->repository->updateExchangeRate($object, $rate, $date); diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php index 8c37eed1df..71e0edfc01 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php @@ -43,7 +43,7 @@ class UpdateController extends Controller public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() @@ -78,7 +78,7 @@ class UpdateController extends Controller $rate = $request->getRate(); $exchangeRate = $this->repository->updateExchangeRate($exchangeRate, $rate, $date); - $transformer = new ExchangeRateTransformer(); + $transformer = new ExchangeRateTransformer(); return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php index 643277a0e8..eb0b25aa38 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php @@ -46,7 +46,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php index 71d44b7584..7a18b363d6 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php @@ -52,7 +52,7 @@ class ListController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); @@ -68,32 +68,32 @@ class ListController extends Controller */ public function bills(ObjectGroup $objectGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getBills($objectGroup); - $count = $collection->count(); - $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getBills($objectGroup); + $count = $collection->count(); + $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); // make paginator: - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]).$this->buildParams()); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -108,32 +108,32 @@ class ListController extends Controller public function piggyBanks(ObjectGroup $objectGroup): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks($objectGroup); - $count = $collection->count(); - $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getPiggyBanks($objectGroup); + $count = $collection->count(); + $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.object-groups.piggy-banks', [$objectGroup->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.object-groups.piggy-banks', [$objectGroup->id]).$this->buildParams()); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php index 79d3f6c414..7381460148 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php @@ -50,7 +50,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); @@ -66,10 +66,10 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); $this->repository->resetOrder(); $collection = $this->repository->get(); @@ -77,14 +77,14 @@ class ShowController extends Controller $objectGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($objectGroups, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.object-groups.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($objectGroups, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.object-groups.index').$this->buildParams()); /** @var ObjectGroupTransformer $transformer */ - $transformer = app(ObjectGroupTransformer::class); + $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($objectGroups, $transformer, 'object_groups'); + $resource = new FractalCollection($objectGroups, $transformer, 'object_groups'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -98,14 +98,14 @@ class ShowController extends Controller */ public function show(ObjectGroup $objectGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); $this->repository->resetOrder(); $objectGroup->refresh(); /** @var ObjectGroupTransformer $transformer */ $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($objectGroup, $transformer, 'object_groups'); + $resource = new Item($objectGroup, $transformer, 'object_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php index db00c35e27..dc6a06087d 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php @@ -48,7 +48,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); @@ -62,15 +62,15 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, ObjectGroup $objectGroup): JsonResponse { - $data = $request->getUpdateData(); + $data = $request->getUpdateData(); $this->repository->update($objectGroup, $data); $this->repository->resetOrder(); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var ObjectGroupTransformer $transformer */ $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($objectGroup, $transformer, 'object_groups'); + $resource = new Item($objectGroup, $transformer, 'object_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php index 0cee0c0207..fdc0e7d9f9 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php @@ -68,30 +68,30 @@ class ListController extends Controller public function accounts(PiggyBank $piggyBank): JsonResponse { // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); - $collection = $piggyBank->accounts; - $count = $collection->count(); - $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $piggyBank->accounts; + $count = $collection->count(); + $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]).$this->buildParams()); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -103,22 +103,22 @@ class ListController extends Controller */ public function attachments(PiggyBank $piggyBank): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($piggyBank); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($piggyBank); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.attachments', [$piggyBank->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.attachments', [$piggyBank->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -133,29 +133,29 @@ class ListController extends Controller public function piggyBankEvents(PiggyBank $piggyBank): JsonResponse { // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); - $collection = $this->repository->getEvents($piggyBank); - $count = $collection->count(); - $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getEvents($piggyBank); + $count = $collection->count(); + $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEventEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEventEnrichment(); $enrichment->setUser($admin); - $events = $enrichment->enrich($events); + $events = $enrichment->enrich($events); // make paginator: - $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.events', [$piggyBank->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.events', [$piggyBank->id]).$this->buildParams()); /** @var PiggyBankEventTransformer $transformer */ $transformer = app(PiggyBankEventTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($events, $transformer, sprintf('piggy-banks/%d/events', $piggyBank->id)); + $resource = new FractalCollection($events, $transformer, sprintf('piggy-banks/%d/events', $piggyBank->id)); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php index 8dea00b766..e80c617371 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php @@ -65,31 +65,31 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks(); - $count = $collection->count(); - $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getPiggyBanks(); + $count = $collection->count(); + $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.index').$this->buildParams()); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -103,20 +103,20 @@ class ShowController extends Controller */ public function show(PiggyBank $piggyBank): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy-banks'); + $resource = new Item($piggyBank, $transformer, 'piggy-banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php b/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php index 6682ef250a..80858e3875 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php @@ -65,21 +65,21 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $piggyBank = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $piggyBank = $this->repository->store($request->getAll()); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy_banks'); + $resource = new Item($piggyBank, $transformer, 'piggy_banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php index 0e8fb4ab20..9cc3edef43 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php @@ -63,23 +63,23 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, PiggyBank $piggyBank): JsonResponse { - $data = $request->getAll(); - $piggyBank = $this->repository->update($piggyBank, $data); + $data = $request->getAll(); + $piggyBank = $this->repository->update($piggyBank, $data); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy-banks'); + $resource = new Item($piggyBank, $transformer, 'piggy-banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/ListController.php b/app/Api/V1/Controllers/Models/Recurrence/ListController.php index 253cf66329..a67b959017 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ListController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ListController.php @@ -68,21 +68,21 @@ class ListController extends Controller */ public function transactions(Request $request, Recurrence $recurrence): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); // whatever is returned by the query, it must be part of these journals: - $journalIds = $this->repository->getJournalIds($recurrence); + $journalIds = $this->repository->getJournalIds($recurrence); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on journal IDs. @@ -94,7 +94,8 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -103,19 +104,19 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php index 42297a896a..c0dd269c0e 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php @@ -65,10 +65,10 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. $collection = $this->repository->get(); @@ -77,20 +77,20 @@ class ShowController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); $recurrences = $enrichment->enrich($recurrences); // make paginator: - $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.recurrences.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.recurrences.index').$this->buildParams()); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); + $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -104,20 +104,20 @@ class ShowController extends Controller */ public function show(Recurrence $recurrence): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php index 1b27ce8f1a..3d0a4a36c8 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php @@ -65,22 +65,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); - $recurrence = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $recurrence = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php b/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php index dd0bb08c8d..8880d7b307 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php @@ -63,33 +63,33 @@ class TriggerController extends Controller { // find recurrence occurrence for this date and trigger it. // grab the date from the last time the recurrence fired: - $backupDate = $recurrence->latest_date; - $date = $request->getDate(); + $backupDate = $recurrence->latest_date; + $date = $request->getDate(); // fire the recurring cron job on the given date, then post-date the created transaction. Log::info(sprintf('Trigger: will now fire recurring cron job task for date "%s".', $date->format('Y-m-d H:i:s'))); /** @var CreateRecurringTransactions $job */ - $job = app(CreateRecurringTransactions::class); + $job = app(CreateRecurringTransactions::class); $job->setRecurrences(new Collection()->push($recurrence)); $job->setDate($date); $job->setForce(false); $job->handle(); Log::debug('Done with recurrence.'); - $groups = $job->getGroups(); + $groups = $job->getGroups(); $this->repository->markGroupsAsNow($groups); - $recurrence->latest_date = $backupDate; + $recurrence->latest_date = $backupDate; $recurrence->latest_date_tz = $backupDate?->format('e'); $recurrence->save(); Preferences::mark(); // enrich groups and return them: - $paginator = new LengthAwarePaginator(new Collection(), 0, 1); + $paginator = new LengthAwarePaginator(new Collection(), 0, 1); if ($groups->count() > 0) { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ @@ -98,20 +98,20 @@ class TriggerController extends Controller $paginator = $collector->getPaginatedGroups(); } - $manager = $this->getManager(); - $paginator->setPath(route('api.v1.recurrences.trigger', [$recurrence->id]) . $this->buildParams()); + $manager = $this->getManager(); + $paginator->setPath(route('api.v1.recurrences.trigger', [$recurrence->id]).$this->buildParams()); // enrich - $admin = auth()->user(); - $enrichment = new TransactionGroupEnrichment(); + $admin = auth()->user(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $transactions = $enrichment->enrich($paginator->getCollection()); + $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php index 1855a39982..3805ac90b8 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php @@ -63,22 +63,22 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Recurrence $recurrence): JsonResponse { - $data = $request->getAll(); - $recurrence = $this->repository->update($recurrence, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $recurrence = $this->repository->update($recurrence, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/DestroyController.php b/app/Api/V1/Controllers/Models/Rule/DestroyController.php index 51154bbe1f..887f53cdfd 100644 --- a/app/Api/V1/Controllers/Models/Rule/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Rule/DestroyController.php @@ -46,7 +46,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleRepository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/Rule/ShowController.php b/app/Api/V1/Controllers/Models/Rule/ShowController.php index 585c3509b8..0955f8b66a 100644 --- a/app/Api/V1/Controllers/Models/Rule/ShowController.php +++ b/app/Api/V1/Controllers/Models/Rule/ShowController.php @@ -50,7 +50,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleRepository->setUser($user); @@ -67,25 +67,25 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->ruleRepository->getAll(); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleRepository->getAll(); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.index').$this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -99,13 +99,13 @@ class ShowController extends Controller */ public function show(Rule $rule): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/StoreController.php b/app/Api/V1/Controllers/Models/Rule/StoreController.php index 5f419aa5b8..dd7b6e2dd1 100644 --- a/app/Api/V1/Controllers/Models/Rule/StoreController.php +++ b/app/Api/V1/Controllers/Models/Rule/StoreController.php @@ -47,7 +47,7 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleRepository->setUser($user); @@ -64,14 +64,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->ruleRepository->store($request->getAll()); - $manager = $this->getManager(); + $rule = $this->ruleRepository->store($request->getAll()); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/TriggerController.php b/app/Api/V1/Controllers/Models/Rule/TriggerController.php index 0881bafd2a..644a9ff0f7 100644 --- a/app/Api/V1/Controllers/Models/Rule/TriggerController.php +++ b/app/Api/V1/Controllers/Models/Rule/TriggerController.php @@ -54,7 +54,7 @@ class TriggerController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleRepository->setUser($user); @@ -69,10 +69,10 @@ class TriggerController extends Controller */ public function testRule(TestRequest $request, Rule $rule): JsonResponse { - $parameters = $request->getTestParameters(); + $parameters = $request->getTestParameters(); /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules(new Collection()->push($rule)); // overrule the rule(s) if necessary. @@ -94,21 +94,21 @@ class TriggerController extends Controller $count = $transactions->count(); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($rule->user); $transactions = $enrichment->enrich($transactions); - $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.test', [$rule->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.test', [$rule->id]).$this->buildParams()); // resulting list is presented as JSON thing. - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Rule/UpdateController.php b/app/Api/V1/Controllers/Models/Rule/UpdateController.php index a863b73a90..87861956fb 100644 --- a/app/Api/V1/Controllers/Models/Rule/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Rule/UpdateController.php @@ -48,7 +48,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleRepository->setUser($user); @@ -65,15 +65,15 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Rule $rule): JsonResponse { - $data = $request->getAll(); - $rule = $this->ruleRepository->update($rule, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $rule = $this->ruleRepository->update($rule, $data); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php b/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php index cd002c83b2..a3de71cedd 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php @@ -46,7 +46,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php index 9ba8ba9707..3b9d42cefd 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php @@ -49,7 +49,7 @@ class ListController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); @@ -64,24 +64,24 @@ class ListController extends Controller */ public function rules(RuleGroup $group): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->ruleGroupRepository->getRules($group); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleGroupRepository->getRules($group); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.rules', [$group->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.rules', [$group->id]).$this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php index eb26ecf7a2..3589218f1f 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php @@ -50,7 +50,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); @@ -66,24 +66,24 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of rule groups. Count it and split it. - $collection = $this->ruleGroupRepository->get(); - $count = $collection->count(); - $ruleGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleGroupRepository->get(); + $count = $collection->count(); + $ruleGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($ruleGroups, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($ruleGroups, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.index').$this->buildParams()); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($ruleGroups, $transformer, 'rule_groups'); + $resource = new FractalCollection($ruleGroups, $transformer, 'rule_groups'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -97,13 +97,13 @@ class ShowController extends Controller */ public function show(RuleGroup $ruleGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php index 75858725a8..e0521d95b9 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php @@ -49,12 +49,12 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository->setUser($user); return $next($request); @@ -69,14 +69,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $ruleGroup = $this->ruleGroupRepository->store($request->getAll()); - $manager = $this->getManager(); + $ruleGroup = $this->ruleGroupRepository->store($request->getAll()); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php index 44e900344d..18652acff2 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php @@ -55,7 +55,7 @@ class TriggerController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); @@ -72,14 +72,14 @@ class TriggerController extends Controller */ public function testGroup(TestRequest $request, RuleGroup $group): JsonResponse { - $rules = $this->ruleGroupRepository->getActiveRules($group); + $rules = $this->ruleGroupRepository->getActiveRules($group); if (0 === $rules->count()) { throw new FireflyException('200023: No rules in this rule group.'); } - $parameters = $request->getTestParameters(); + $parameters = $request->getTestParameters(); /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules($rules); // overrule the rule(s) if necessary. @@ -101,21 +101,21 @@ class TriggerController extends Controller $count = $transactions->count(); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($group->user); $transactions = $enrichment->enrich($transactions); - $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.test', [$group->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.test', [$group->id]).$this->buildParams()); // resulting list is presented as JSON thing. - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -131,7 +131,7 @@ class TriggerController extends Controller */ public function triggerGroup(TriggerRequest $request, RuleGroup $group): JsonResponse { - $rules = $this->ruleGroupRepository->getActiveRules($group); + $rules = $this->ruleGroupRepository->getActiveRules($group); if (0 === $rules->count()) { throw new FireflyException('200023: No rules in this rule group.'); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php b/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php index bcfe10e602..9ee6d626c9 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php @@ -48,7 +48,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $this->ruleGroupRepository->setUser($user); @@ -65,14 +65,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, RuleGroup $ruleGroup): JsonResponse { - $ruleGroup = $this->ruleGroupRepository->update($ruleGroup, $request->getAll()); - $manager = $this->getManager(); + $ruleGroup = $this->ruleGroupRepository->update($ruleGroup, $request->getAll()); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/DestroyController.php b/app/Api/V1/Controllers/Models/Tag/DestroyController.php index 35c982314a..7ef770ad12 100644 --- a/app/Api/V1/Controllers/Models/Tag/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Tag/DestroyController.php @@ -46,7 +46,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/Tag/ListController.php b/app/Api/V1/Controllers/Models/Tag/ListController.php index 20bb2113c7..8a73e6679e 100644 --- a/app/Api/V1/Controllers/Models/Tag/ListController.php +++ b/app/Api/V1/Controllers/Models/Tag/ListController.php @@ -56,7 +56,7 @@ class ListController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -71,22 +71,22 @@ class ListController extends Controller */ public function attachments(Tag $tag): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($tag); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($tag); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.tags.attachments', [$tag->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.tags.attachments', [$tag->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -100,19 +100,19 @@ class ListController extends Controller */ public function transactions(Request $request, Tag $tag): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on tag. @@ -124,7 +124,8 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -132,19 +133,19 @@ class ListController extends Controller if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.tags.transactions', [$tag->id]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.tags.transactions', [$tag->id]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Tag/ShowController.php b/app/Api/V1/Controllers/Models/Tag/ShowController.php index 72b3644332..04b6e04d5f 100644 --- a/app/Api/V1/Controllers/Models/Tag/ShowController.php +++ b/app/Api/V1/Controllers/Models/Tag/ShowController.php @@ -50,7 +50,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -67,24 +67,24 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->get(); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.tags.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.tags.index').$this->buildParams()); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'tags'); + $resource = new FractalCollection($rules, $transformer, 'tags'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -98,13 +98,13 @@ class ShowController extends Controller */ public function show(Tag $tag): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($tag, $transformer, 'tags'); + $resource = new Item($tag, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/StoreController.php b/app/Api/V1/Controllers/Models/Tag/StoreController.php index 16a09d7fd0..62dfcaef1d 100644 --- a/app/Api/V1/Controllers/Models/Tag/StoreController.php +++ b/app/Api/V1/Controllers/Models/Tag/StoreController.php @@ -47,7 +47,7 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -64,14 +64,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $rule = $this->repository->store($request->getAll()); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'tags'); + $resource = new Item($rule, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/UpdateController.php b/app/Api/V1/Controllers/Models/Tag/UpdateController.php index 339238e5f6..09b67903e9 100644 --- a/app/Api/V1/Controllers/Models/Tag/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Tag/UpdateController.php @@ -48,7 +48,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); $this->repository->setUser($user); @@ -65,14 +65,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Tag $tag): JsonResponse { - $rule = $this->repository->update($tag, $request->getAll()); - $manager = $this->getManager(); + $rule = $this->repository->update($tag, $request->getAll()); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'tags'); + $resource = new Item($rule, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php index a228a59ce7..153bd46167 100644 --- a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php @@ -53,9 +53,9 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); $this->repository->setUser($admin); $this->groupRepository = app(TransactionGroupRepository::class); diff --git a/app/Api/V1/Controllers/Models/Transaction/ListController.php b/app/Api/V1/Controllers/Models/Transaction/ListController.php index 680d581bad..51df963149 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ListController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ListController.php @@ -54,7 +54,7 @@ class ListController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); $this->journalAPIRepository = app(JournalAPIRepositoryInterface::class); $this->journalAPIRepository->setUser($admin); @@ -69,9 +69,9 @@ class ListController extends Controller */ public function attachments(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = new Collection(); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = new Collection(); foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getAttachments($transactionJournal)->merge($collection); } @@ -80,14 +80,14 @@ class ListController extends Controller $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transactions.attachments', [$transactionGroup->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transactions.attachments', [$transactionGroup->id]).$this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -99,31 +99,31 @@ class ListController extends Controller */ public function piggyBankEvents(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); - $collection = new Collection(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $collection = new Collection(); + $pageSize = $this->parameters->get('limit'); foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getPiggyBankEvents($transactionJournal)->merge($collection); } - $count = $collection->count(); - $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEventEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEventEnrichment(); $enrichment->setUser($admin); - $events = $enrichment->enrich($events); + $events = $enrichment->enrich($events); // make paginator: - $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transactions.piggy-bank-events', [$transactionGroup->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transactions.piggy-bank-events', [$transactionGroup->id]).$this->buildParams()); /** @var PiggyBankEventTransformer $transformer */ $transformer = app(PiggyBankEventTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($events, $transformer, 'piggy_bank_events'); + $resource = new FractalCollection($events, $transformer, 'piggy_bank_events'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); // /** @var PiggyBankEventTransformer $transformer */ // $transformer = app(PiggyBankEventTransformer::class); @@ -147,14 +147,14 @@ class ListController extends Controller $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transaction-journals.transaction-links', [$transactionJournal->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transaction-journals.transaction-links', [$transactionJournal->id]).$this->buildParams()); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); + $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Transaction/ShowController.php b/app/Api/V1/Controllers/Models/Transaction/ShowController.php index 20ed91b321..4f4bcd43df 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ShowController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ShowController.php @@ -54,19 +54,19 @@ class ShowController extends Controller */ public function index(Request $request): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // all info needed for the API: @@ -76,23 +76,24 @@ class ShowController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start') || null !== $this->parameters->get('end')) { $collector->setRange($this->parameters->get('start'), $this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -117,20 +118,21 @@ class ShowController extends Controller */ public function show(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation(); + ->withAPIInformation() + ; $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { @@ -138,14 +140,14 @@ class ShowController extends Controller } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/StoreController.php b/app/Api/V1/Controllers/Models/Transaction/StoreController.php index c65cc0437a..bfecbcd58e 100644 --- a/app/Api/V1/Controllers/Models/Transaction/StoreController.php +++ b/app/Api/V1/Controllers/Models/Transaction/StoreController.php @@ -65,8 +65,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { /** @var User $admin */ - $admin = auth()->user(); - $userGroup = $this->validateUserGroup($request); + $admin = auth()->user(); + $userGroup = $this->validateUserGroup($request); $this->groupRepository = app(TransactionGroupRepositoryInterface::class); $this->groupRepository->setUser($admin); @@ -87,8 +87,8 @@ class StoreController extends Controller public function store(StoreRequest $request): JsonResponse { Log::debug('Now in API StoreController::store()'); - $data = $request->getAll(); - $data['user'] = auth()->user(); + $data = $request->getAll(); + $data['user'] = auth()->user(); $data['user_group'] = $this->userGroup; Log::channel('audit')->info('Store new transaction over API.', $data); @@ -97,8 +97,7 @@ class StoreController extends Controller $transactionGroup = $this->groupRepository->store($data); } catch (DuplicateTransactionException $e) { Log::warning('Caught a duplicate transaction. Return error message.'); - $validator = Validator::make(['transactions' => [['description' => $e->getMessage()]]], ['transactions.0.description' => - new IsDuplicateTransaction()]); + $validator = Validator::make(['transactions' => [['description' => $e->getMessage()]]], ['transactions.0.description' => new IsDuplicateTransaction()]); throw new ValidationException($validator); } catch (FireflyException $e) { @@ -110,40 +109,41 @@ class StoreController extends Controller throw new ValidationException($validator); } Preferences::mark(); - $applyRules = $data['apply_rules'] ?? true; - $fireWebhooks = $data['fire_webhooks'] ?? true; + $applyRules = $data['apply_rules'] ?? true; + $fireWebhooks = $data['fire_webhooks'] ?? true; event(new StoredTransactionGroup($transactionGroup, $applyRules, $fireWebhooks)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) ->setUserGroup($this->userGroup) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation(); + ->withAPIInformation() + ; - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw HttpException::fromStatusCode(410, '200032: Cannot find transaction. Possibly, a rule deleted this transaction after its creation.'); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php index c2108c8299..78e60b2562 100644 --- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php @@ -54,7 +54,7 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); $this->groupRepository = app(TransactionGroupRepositoryInterface::class); $this->groupRepository->setUser($admin); @@ -72,11 +72,11 @@ class UpdateController extends Controller public function update(UpdateRequest $request, TransactionGroup $transactionGroup): JsonResponse { Log::debug('Now in update routine for transaction group'); - $data = $request->getAll(); - $oldHash = $this->groupRepository->getCompareHash($transactionGroup); - $transactionGroup = $this->groupRepository->update($transactionGroup, $data); - $newHash = $this->groupRepository->getCompareHash($transactionGroup); - $manager = $this->getManager(); + $data = $request->getAll(); + $oldHash = $this->groupRepository->getCompareHash($transactionGroup); + $transactionGroup = $this->groupRepository->update($transactionGroup, $data); + $newHash = $this->groupRepository->getCompareHash($transactionGroup); + $manager = $this->getManager(); Preferences::mark(); $applyRules = $data['apply_rules'] ?? true; @@ -85,32 +85,33 @@ class UpdateController extends Controller event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $runRecalculations)); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation(); + ->withAPIInformation() + ; - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw new NotFoundHttpException(); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php index 7f03e61466..d81d0a20a6 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php @@ -50,7 +50,7 @@ class DestroyController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); $this->repository->setUser(auth()->user()); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php index 10496c3c86..52117fdd2f 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php @@ -73,15 +73,15 @@ class ListController extends Controller */ public function accounts(Request $request, TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // read type from URL - $type = $request->get('type') ?? 'all'; + $type = $request->get('type') ?? 'all'; $this->parameters->set('type', $type); // types to get, page size: - $types = $this->mapAccountTypes($this->parameters->get('type')); - $pageSize = $this->parameters->get('limit'); + $types = $this->mapAccountTypes($this->parameters->get('type')); + $pageSize = $this->parameters->get('limit'); // get list of accounts. Count it and split it. /** @var AccountRepositoryInterface $accountRepository */ @@ -89,14 +89,14 @@ class ListController extends Controller $unfiltered = $accountRepository->getAccountsByType($types); // filter list on currency preference: - $collection = $unfiltered->filter(static function (Account $account) use ($currency, $accountRepository): bool { + $collection = $unfiltered->filter(static function (Account $account) use ($currency, $accountRepository): bool { $currencyId = (int) $accountRepository->getMetaValue($account, 'currency_id'); return $currencyId === $currency->id; }); - $count = $collection->count(); - $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // #11007 go to the end of the previous day. $this->parameters->set('start', $this->parameters->get('start')?->subSecond()); @@ -105,22 +105,22 @@ class ListController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.accounts', [$currency->code]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.accounts', [$currency->code]).$this->buildParams()); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); + $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -134,26 +134,26 @@ class ListController extends Controller */ public function availableBudgets(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of available budgets. Count it and split it. /** @var AvailableBudgetRepositoryInterface $abRepository */ - $abRepository = app(AvailableBudgetRepositoryInterface::class); + $abRepository = app(AvailableBudgetRepositoryInterface::class); $collection = $abRepository->getAvailableBudgetsByCurrency($currency); $count = $collection->count(); $availableBudgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($availableBudgets, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.available-budgets', [$currency->code]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($availableBudgets, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.available-budgets', [$currency->code]).$this->buildParams()); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); + $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -167,36 +167,36 @@ class ListController extends Controller */ public function bills(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var BillRepositoryInterface $billRepos */ - $billRepos = app(BillRepositoryInterface::class); - $pageSize = $this->parameters->get('limit'); - $unfiltered = $billRepos->getBills(); + $billRepos = app(BillRepositoryInterface::class); + $pageSize = $this->parameters->get('limit'); + $unfiltered = $billRepos->getBills(); // filter and paginate list: - $collection = $unfiltered->filter(static fn(Bill $bill): bool => $bill->transaction_currency_id === $currency->id); - $count = $collection->count(); - $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $unfiltered->filter(static fn (Bill $bill): bool => $bill->transaction_currency_id === $currency->id); + $count = $collection->count(); + $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); // make paginator: - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.bills', [$currency->code]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.bills', [$currency->code]).$this->buildParams()); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -219,20 +219,20 @@ class ListController extends Controller $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.budget-limits', [$currency->code]) . $this->buildParams()); + $paginator->setPath(route('api.v1.currencies.budget-limits', [$currency->code]).$this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -246,9 +246,9 @@ class ListController extends Controller */ public function recurrences(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. /** @var RecurringRepositoryInterface $recurringRepos */ @@ -256,35 +256,35 @@ class ListController extends Controller $unfiltered = $recurringRepos->get(); // filter selection - $collection = $unfiltered->filter(static function (Recurrence $recurrence) use ($currency): null|Recurrence { // @phpstan-ignore-line + $collection = $unfiltered->filter(static function (Recurrence $recurrence) use ($currency): null|Recurrence { // @phpstan-ignore-line if (array_any( $recurrence->recurrenceTransactions, - static fn($transaction): bool => $transaction->transaction_currency_id === $currency->id || $transaction->foreign_currency_id === $currency->id + static fn ($transaction): bool => $transaction->transaction_currency_id === $currency->id || $transaction->foreign_currency_id === $currency->id )) { return $recurrence; } return null; }); - $count = $collection->count(); - $recurrences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $recurrences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrences = $enrichment->enrich($recurrences); + $recurrences = $enrichment->enrich($recurrences); // make paginator: - $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.recurrences', [$currency->code]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.recurrences', [$currency->code]).$this->buildParams()); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); + $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); + $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -298,18 +298,18 @@ class ListController extends Controller */ public function rules(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. /** @var RuleRepositoryInterface $ruleRepos */ - $ruleRepos = app(RuleRepositoryInterface::class); - $unfiltered = $ruleRepos->getAll(); + $ruleRepos = app(RuleRepositoryInterface::class); + $unfiltered = $ruleRepos->getAll(); - $collection = $unfiltered->filter(static function (Rule $rule) use ($currency): null|Rule { // @phpstan-ignore-line + $collection = $unfiltered->filter(static function (Rule $rule) use ($currency): null|Rule { // @phpstan-ignore-line if (array_any( $rule->ruleTriggers, - static fn($trigger): bool => 'currency_is' === $trigger->trigger_type && $currency->name === $trigger->trigger_value + static fn ($trigger): bool => 'currency_is' === $trigger->trigger_type && $currency->name === $trigger->trigger_value )) { return $rule; } @@ -317,18 +317,18 @@ class ListController extends Controller return null; }); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.index').$this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -342,19 +342,19 @@ class ListController extends Controller */ public function transactions(Request $request, TransactionCurrency $currency): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on currency. @@ -366,26 +366,27 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); } if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.currencies.transactions', [$currency->code]) . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.currencies.transactions', [$currency->code]).$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php index 34f0b39681..18fb36b928 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php @@ -69,21 +69,21 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAll(); - $count = $collection->count(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAll(); + $count = $collection->count(); // slice them: - $currencies = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($currencies, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.index') . $this->buildParams()); - $manager = $this->getManager(); + $currencies = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $paginator = new LengthAwarePaginator($currencies, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.index').$this->buildParams()); + $manager = $this->getManager(); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($currencies, $transformer, 'currencies'); + $resource = new FractalCollection($currencies, $transformer, 'currencies'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -98,8 +98,8 @@ class ShowController extends Controller public function show(TransactionCurrency $currency): JsonResponse { /** @var User $user */ - $user = auth()->user(); - $manager = $this->getManager(); + $user = auth()->user(); + $manager = $this->getManager(); $this->parameters->set('primaryCurrency', $this->primaryCurrency); // update fields with user info. @@ -109,7 +109,7 @@ class ShowController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -120,9 +120,9 @@ class ShowController extends Controller public function showPrimary(): JsonResponse { /** @var User $user */ - $user = auth()->user(); - $manager = $this->getManager(); - $currency = $this->primaryCurrency; + $user = auth()->user(); + $manager = $this->getManager(); + $currency = $this->primaryCurrency; // update fields with user info. $currency->refreshForUser($user); @@ -131,7 +131,7 @@ class ShowController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php index ea8158ff73..4dc5004dd5 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php @@ -67,22 +67,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $currency = $this->repository->store($request->getAll()); + $currency = $this->repository->store($request->getAll()); if (true === $request->boolean('default')) { $this->repository->makePrimary($currency); Preferences::mark(); } - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php index 0af39c7403..3bef404524 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php @@ -82,9 +82,9 @@ class UpdateController extends Controller } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository->disable($currency); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); @@ -92,7 +92,7 @@ class UpdateController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -100,20 +100,20 @@ class UpdateController extends Controller public function makePrimary(TransactionCurrency $currency): JsonResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository->enable($currency); $this->repository->makePrimary($currency); Preferences::mark(); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -127,10 +127,10 @@ class UpdateController extends Controller public function enable(TransactionCurrency $currency): JsonResponse { $this->repository->enable($currency); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $currency->refreshForUser($user); @@ -138,7 +138,7 @@ class UpdateController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -153,14 +153,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, TransactionCurrency $currency): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); Log::debug(__METHOD__, $data); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // safety catch on currency disablement. - $set = $this->repository->get(); + $set = $this->repository->get(); if (array_key_exists('enabled', $data) && false === $data['enabled'] && 1 === count($set) && $set->first()->id === $currency->id) { return response()->json([], 409); } @@ -169,17 +169,17 @@ class UpdateController extends Controller return response()->json([], 409); } - $currency = $this->repository->update($currency, $data); + $currency = $this->repository->update($currency, $data); Preferences::mark(); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php index 88bda8f29f..41b07687ce 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php @@ -46,7 +46,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(LinkTypeRepositoryInterface::class); diff --git a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php index 414b283109..5ec069ffa4 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php @@ -51,7 +51,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(LinkTypeRepositoryInterface::class); @@ -70,13 +70,13 @@ class ShowController extends Controller public function index(Request $request): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); // read type from URL - $name = $request->get('name'); + $name = $request->get('name'); // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $linkType = $this->repository->findByName($name); + $pageSize = $this->parameters->get('limit'); + $linkType = $this->repository->findByName($name); // get list of transaction links. Count it and split it. $collection = $this->repository->getJournalLinks($linkType); @@ -84,14 +84,14 @@ class ShowController extends Controller $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transaction-links.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transaction-links.index').$this->buildParams()); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); + $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -105,13 +105,13 @@ class ShowController extends Controller */ public function show(TransactionJournalLink $journalLink): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionLinkTransformer $transformer */ $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php b/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php index 48ce4827f2..e6893498a6 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php @@ -54,9 +54,9 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); $this->journalRepository = app(JournalRepositoryInterface::class); $this->repository->setUser($user); @@ -76,22 +76,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $manager = $this->getManager(); - $data = $request->getAll(); - $inward = $this->journalRepository->find($data['inward_id'] ?? 0); - $outward = $this->journalRepository->find($data['outward_id'] ?? 0); + $manager = $this->getManager(); + $data = $request->getAll(); + $inward = $this->journalRepository->find($data['inward_id'] ?? 0); + $outward = $this->journalRepository->find($data['outward_id'] ?? 0); if (!$inward instanceof TransactionJournal || !$outward instanceof TransactionJournal) { throw new FireflyException('200024: Source or destination does not exist.'); } $data['direction'] = 'inward'; - $journalLink = $this->repository->storeLink($data, $inward, $outward); + $journalLink = $this->repository->storeLink($data, $inward, $outward); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php index bc9830ec3b..d22bcadea5 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php @@ -50,9 +50,9 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); $this->journalRepository = app(JournalRepositoryInterface::class); $this->repository->setUser($user); @@ -78,7 +78,7 @@ class UpdateController extends Controller $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php index e7804b5d82..5093b5ffd4 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php @@ -50,7 +50,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(LinkTypeRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php index 890348dfc9..6c3d5fdc0a 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php @@ -54,7 +54,7 @@ class ListController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(LinkTypeRepositoryInterface::class); $this->repository->setUser($user); @@ -68,22 +68,22 @@ class ListController extends Controller */ public function transactions(Request $request, LinkType $linkType): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); // whatever is returned by the query, it must be part of these journals: - $journalIds = $this->repository->getJournalIds($linkType); + $journalIds = $this->repository->getJournalIds($linkType); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on journal IDs. @@ -95,26 +95,27 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types); + ->setTypes($types) + ; if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); } if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php index 3fb86002ae..30baed01c1 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php @@ -53,7 +53,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(LinkTypeRepositoryInterface::class); $this->repository->setUser($user); @@ -68,23 +68,23 @@ class ShowController extends Controller public function index(): JsonResponse { // create some objects: - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); // get list of accounts. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $linkTypes = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->get(); + $count = $collection->count(); + $linkTypes = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($linkTypes, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.link-types.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($linkTypes, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.link-types.index').$this->buildParams()); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($linkTypes, $transformer, 'link_types'); + $resource = new FractalCollection($linkTypes, $transformer, 'link_types'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -98,13 +98,13 @@ class ShowController extends Controller */ public function show(LinkType $linkType): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php index d62100b007..0bf672ca49 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php @@ -54,8 +54,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); $this->repository->setUser($user); @@ -74,23 +74,23 @@ class StoreController extends Controller public function store(StoreRequest $request): JsonResponse { /** @var User $admin */ - $admin = auth()->user(); - $rules = ['name' => 'required']; + $admin = auth()->user(); + $rules = ['name' => 'required']; if (!$this->userRepository->hasRole($admin, 'owner')) { // access denied: $messages = ['name' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); } - $data = $request->getAll(); + $data = $request->getAll(); // if currency ID is 0, find the currency by the code: - $linkType = $this->repository->store($data); - $manager = $this->getManager(); + $linkType = $this->repository->store($data); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php index 25c8fa4edc..12b5113c30 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php @@ -56,8 +56,8 @@ class UpdateController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); $this->repository->setUser($user); @@ -81,23 +81,23 @@ class UpdateController extends Controller } /** @var User $admin */ - $admin = auth()->user(); - $rules = ['name' => 'required']; + $admin = auth()->user(); + $rules = ['name' => 'required']; if (!$this->userRepository->hasRole($admin, 'owner')) { $messages = ['name' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); } - $data = $request->getAll(); + $data = $request->getAll(); $this->repository->update($linkType, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/UserGroup/IndexController.php b/app/Api/V1/Controllers/Models/UserGroup/IndexController.php index b0eb562b15..1f60571ffe 100644 --- a/app/Api/V1/Controllers/Models/UserGroup/IndexController.php +++ b/app/Api/V1/Controllers/Models/UserGroup/IndexController.php @@ -52,12 +52,12 @@ class IndexController extends Controller public function index(PaginationRequest $request): JsonResponse { - $administrations = $this->repository->get(); + $administrations = $this->repository->get(); ['page' => $page, 'limit' => $limit, 'offset' => $offset] = $request->attributes->all(); - $count = $administrations->count(); - $administrations = $administrations->slice($offset, $limit); - $paginator = new LengthAwarePaginator($administrations, $count, $limit, $page); - $transformer = new UserGroupTransformer(); + $count = $administrations->count(); + $administrations = $administrations->slice($offset, $limit); + $paginator = new LengthAwarePaginator($administrations, $count, $limit, $page); + $transformer = new UserGroupTransformer(); return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php b/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php index f18ac1be8e..20dd7f70c2 100644 --- a/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php @@ -55,8 +55,8 @@ class UpdateController extends Controller public function update(UpdateRequest $request, UserGroup $userGroup): JsonResponse { Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getData(); - $userGroup = $this->repository->update($userGroup, $data); + $data = $request->getData(); + $userGroup = $this->repository->update($userGroup, $data); $userGroup->refresh(); Preferences::mark(); diff --git a/app/Api/V1/Controllers/Search/AccountController.php b/app/Api/V1/Controllers/Search/AccountController.php index d9e43c380c..caaa0c879b 100644 --- a/app/Api/V1/Controllers/Search/AccountController.php +++ b/app/Api/V1/Controllers/Search/AccountController.php @@ -50,7 +50,7 @@ class AccountController extends Controller AccountSearch::SEARCH_ID, AccountSearch::SEARCH_NAME, AccountSearch::SEARCH_IBAN, - AccountSearch::SEARCH_NUMBER + AccountSearch::SEARCH_NUMBER, ]; public function __construct() @@ -64,41 +64,41 @@ class AccountController extends Controller */ public function search(Request $request): JsonResponse|Response { - $manager = $this->getManager(); - $query = trim((string) $request->get('query')); - $field = trim((string) $request->get('field')); - $type = $request->get('type') ?? 'all'; + $manager = $this->getManager(); + $query = trim((string) $request->get('query')); + $field = trim((string) $request->get('field')); + $type = $request->get('type') ?? 'all'; if ('' === $query || !in_array($field, $this->validFields, true)) { return response(null, 422); } Log::debug(sprintf('Now in account search("%s", "%s")', $field, $query)); - $types = $this->mapAccountTypes($type); + $types = $this->mapAccountTypes($type); /** @var AccountSearch $search */ - $search = app(AccountSearch::class); + $search = app(AccountSearch::class); $search->setUser(auth()->user()); $search->setTypes($types); $search->setField($field); $search->setQuery($query); - $accounts = $search->search(); + $accounts = $search->search(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $count = $accounts->count(); - $perPage = 0 === $count ? 1 : $count; - $paginator = new LengthAwarePaginator($accounts, $count, $perPage, 1); + $count = $accounts->count(); + $perPage = 0 === $count ? 1 : $count; + $paginator = new LengthAwarePaginator($accounts, $count, $perPage, 1); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Search/TransactionController.php b/app/Api/V1/Controllers/Search/TransactionController.php index 386d6cac2f..cc5768fce1 100644 --- a/app/Api/V1/Controllers/Search/TransactionController.php +++ b/app/Api/V1/Controllers/Search/TransactionController.php @@ -44,31 +44,31 @@ class TransactionController extends Controller */ public function search(TransactionSearchRequest $request, SearchInterface $searcher): JsonResponse { - $manager = $this->getManager(); - $fullQuery = (string) $request->attributes->get('query'); - $page = $request->attributes->get('page'); - $pageSize = $request->attributes->get('limit'); + $manager = $this->getManager(); + $fullQuery = (string) $request->attributes->get('query'); + $page = $request->attributes->get('page'); + $pageSize = $request->attributes->get('limit'); $searcher->parseQuery($fullQuery); $searcher->setPage($page); $searcher->setLimit($pageSize); - $groups = $searcher->searchTransactions(); - $parameters = ['search' => $fullQuery]; - $url = route('api.v1.search.transactions') . '?' . http_build_query($parameters); + $groups = $searcher->searchTransactions(); + $parameters = ['search' => $fullQuery]; + $url = route('api.v1.search.transactions').'?'.http_build_query($parameters); $groups->setPath($url); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser(auth()->user()); $transactions = $enrichment->enrich($groups->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Collection($transactions, $transformer, 'transactions'); + $resource = new Collection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($groups)); - $array = $manager->createData($resource)->toArray(); + $array = $manager->createData($resource)->toArray(); return response()->json($array)->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php index 89c25e4946..1df90f32a4 100644 --- a/app/Api/V1/Controllers/Summary/BasicController.php +++ b/app/Api/V1/Controllers/Summary/BasicController.php @@ -67,13 +67,13 @@ class BasicController extends Controller parent::__construct(); $this->middleware(function ($request, $next) { /** @var User $user */ - $user = auth()->user(); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); + $user = auth()->user(); + $this->currencyRepos = app(CurrencyRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); $this->billRepository->setUser($user); $this->currencyRepos->setUser($user); @@ -91,18 +91,18 @@ class BasicController extends Controller // parameters for boxes: ['start' => $start, 'end' => $end, 'code' => $code] = $request->attributes->all(); // balance information: - $balanceData = $this->getBalanceInformation($start, $end); - $billData = $this->getSubscriptionInformation($start, $end); - $spentData = $this->getLeftToSpendInfo($start, $end); - $netWorthData = $this->getNetWorthInfo($end); + $balanceData = $this->getBalanceInformation($start, $end); + $billData = $this->getSubscriptionInformation($start, $end); + $spentData = $this->getLeftToSpendInfo($start, $end); + $netWorthData = $this->getNetWorthInfo($end); // $balanceData = []; // $billData = []; // $spentData = []; // $netWorthData = []; - $total = array_merge($balanceData, $billData, $spentData, $netWorthData); + $total = array_merge($balanceData, $billData, $spentData, $netWorthData); // give new keys - $return = []; + $return = []; foreach ($total as $entry) { if ('' === $code || $code === $entry['currency_code']) { $return[$entry['key']] = $entry; @@ -119,27 +119,28 @@ class BasicController extends Controller $convertToPrimary = Amount::convertToPrimary(); $primary = Amount::getPrimaryCurrency(); // prep some arrays: - $sums = []; - $return = []; - $currencies = [$primary->id => $primary]; + $sums = []; + $return = []; + $currencies = [$primary->id => $primary]; // collect income of user using the new group collector. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $summarizer = new TransactionSummarizer(); - $set = $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->getExtractedJournals(); - $incomes = $summarizer->groupByCurrencyId($set, 'positive', false); + $collector = app(GroupCollectorInterface::class); + $summarizer = new TransactionSummarizer(); + $set = $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->getExtractedJournals(); + $incomes = $summarizer->groupByCurrencyId($set, 'positive', false); // collect expenses of user. // collect expenses of user using the new group collector. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $set = $collector + $collector = app(GroupCollectorInterface::class); + $set = $collector ->setRange($start, $end) ->setPage($this->parameters->get('page')) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->getExtractedJournals(); - $expenses = $summarizer->groupByCurrencyId($set, 'negative', false); + ->getExtractedJournals() + ; + $expenses = $summarizer->groupByCurrencyId($set, 'negative', false); // if convert to primary, do so right now. if ($convertToPrimary) { @@ -149,8 +150,8 @@ class BasicController extends Controller 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0' - ] + 'sum' => '0', + ], ]; $newIncomes = [ $primary->id => [ @@ -158,8 +159,8 @@ class BasicController extends Controller 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0' - ] + 'sum' => '0', + ], ]; $sums = [ $primary->id => [ @@ -167,11 +168,11 @@ class BasicController extends Controller 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0' - ] + 'sum' => '0', + ], ]; - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); // loop over income and expenses foreach ([$expenses, $incomes] as $index => $array) { // loop over either one. @@ -192,7 +193,7 @@ class BasicController extends Controller } $currencies[$entry['currency_id']] ??= $this->currencyRepos->find($entry['currency_id']); - $convertedSum = $converter->convert($currencies[$entry['currency_id']], $primary, $start, $entry['sum']); + $convertedSum = $converter->convert($currencies[$entry['currency_id']], $primary, $start, $entry['sum']); $sums[$primary->id]['sum'] = bcadd($sums[$primary->id]['sum'], $convertedSum); if (0 === $index) { $newExpenses[$primary->id]['sum'] = bcadd($newExpenses[$primary->id]['sum'], $convertedSum); @@ -202,26 +203,26 @@ class BasicController extends Controller } } } - $incomes = $newIncomes; - $expenses = $newExpenses; + $incomes = $newIncomes; + $expenses = $newExpenses; } if (!$convertToPrimary) { foreach ([$expenses, $incomes] as $array) { foreach ($array as $entry) { - $currencyId = $entry['currency_id']; + $currencyId = $entry['currency_id']; $sums[$currencyId] ??= [ 'currency_id' => $entry['currency_id'], 'currency_code' => $entry['currency_code'], 'currency_symbol' => $entry['currency_symbol'], 'currency_decimal_places' => $entry['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $entry['sum']); } } } // format amounts: - $keys = array_keys($sums); + $keys = array_keys($sums); foreach ($keys as $currencyId) { $currency = $currencies[$currencyId] ?? $this->currencyRepos->find($currencyId); if (null === $currency) { @@ -239,8 +240,8 @@ class BasicController extends Controller 'value_parsed' => Amount::formatAnything($currency, $sums[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', 'sub_title' => Amount::formatAnything($currency, $expenses[$currencyId]['sum'] ?? '0', false) - . ' + ' - . Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false) + .' + ' + .Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false), ]; $return[] = [ 'key' => sprintf('spent-in-%s', $currency->code), @@ -252,7 +253,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, $expenses[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '' + 'sub_title' => '', ]; $return[] = [ 'key' => sprintf('earned-in-%s', $currency->code), @@ -264,7 +265,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '' + 'sub_title' => '', ]; } if (0 === count($return)) { @@ -280,7 +281,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => Amount::formatAnything($currency, '0', false) . ' + ' . Amount::formatAnything($currency, '0', false) + 'sub_title' => Amount::formatAnything($currency, '0', false).' + '.Amount::formatAnything($currency, '0', false), ]; $return[] = [ 'key' => sprintf('spent-in-%s', $currency->code), @@ -292,7 +293,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '' + 'sub_title' => '', ]; $return[] = [ 'key' => sprintf('earned-in-%s', $currency->code), @@ -304,7 +305,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '' + 'sub_title' => '', ]; } @@ -323,14 +324,14 @@ class BasicController extends Controller $currencies = [$this->primaryCurrency->id => $this->primaryCurrency]; if ($this->convertToPrimary) { - $converter = new ExchangeRateConverter(); - $newPaidAmount = [[ + $converter = new ExchangeRateConverter(); + $newPaidAmount = [[ 'id' => $this->primaryCurrency->id, 'name' => $this->primaryCurrency->name, 'symbol' => $this->primaryCurrency->symbol, 'code' => $this->primaryCurrency->code, 'decimal_places' => $this->primaryCurrency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]]; $newUnpaidAmount = [[ @@ -339,11 +340,11 @@ class BasicController extends Controller 'symbol' => $this->primaryCurrency->symbol, 'code' => $this->primaryCurrency->code, 'decimal_places' => $this->primaryCurrency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]]; foreach ([$paidAmount, $unpaidAmount] as $index => $array) { foreach ($array as $item) { - $currencyId = (int) $item['id']; + $currencyId = (int) $item['id']; if (0 === $index) { // paid amount if ($currencyId === $this->primaryCurrency->id) { @@ -352,7 +353,7 @@ class BasicController extends Controller continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], $convertedAmount); continue; @@ -364,25 +365,25 @@ class BasicController extends Controller continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], $convertedAmount); } } - $paidAmount = $newPaidAmount; - $unpaidAmount = $newUnpaidAmount; + $paidAmount = $newPaidAmount; + $unpaidAmount = $newUnpaidAmount; } // var_dump($paidAmount); // var_dump($unpaidAmount); // exit; - $return = []; + $return = []; /** * @var array $info */ foreach ($paidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); + $amount = bcmul((string) $info['sum'], '-1'); $return[] = [ 'key' => sprintf('bills-paid-in-%s', $info['code']), 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $info['symbol']]), @@ -393,7 +394,7 @@ class BasicController extends Controller 'currency_decimal_places' => $info['decimal_places'], 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false), 'local_icon' => 'check', - 'sub_title' => '' + 'sub_title' => '', ]; } @@ -401,7 +402,7 @@ class BasicController extends Controller * @var array $info */ foreach ($unpaidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); + $amount = bcmul((string) $info['sum'], '-1'); $return[] = [ 'key' => sprintf('bills-unpaid-in-%s', $info['code']), 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $info['symbol']]), @@ -412,7 +413,7 @@ class BasicController extends Controller 'currency_decimal_places' => $info['decimal_places'], 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false), 'local_icon' => 'calendar-o', - 'sub_title' => '' + 'sub_title' => '', ]; } Log::debug(sprintf('Done with getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-'))); @@ -431,7 +432,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false), 'local_icon' => 'check', - 'sub_title' => '' + 'sub_title' => '', ]; $return[] = [ 'key' => sprintf('bills-unpaid-in-%s', $currency->code), @@ -443,7 +444,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false), 'local_icon' => 'calendar-o', - 'sub_title' => '' + 'sub_title' => '', ]; } @@ -489,20 +490,20 @@ class BasicController extends Controller $currencies[$currencyId]->decimal_places, bcdiv($availableBudget, (string) $days), false - ) + ), ]; } foreach ($spent as $row) { // either an amount was budgeted or 0 is available. - $currencyId = (int) $row['currency_id']; - $amount = (string) ($available[$currencyId] ?? '0'); + $currencyId = (int) $row['currency_id']; + $amount = (string) ($available[$currencyId] ?? '0'); if (0 === bccomp($amount, '0')) { // #9858 skip over currencies with no available budget. continue; } - $spentInCurrency = $row['sum']; - $leftToSpend = bcadd($amount, (string) $spentInCurrency); - $perDay = '0'; + $spentInCurrency = $row['sum']; + $leftToSpend = bcadd($amount, (string) $spentInCurrency); + $perDay = '0'; if (0 !== $days && bccomp($leftToSpend, '0') > -1) { $perDay = bcdiv($leftToSpend, (string) $days); } @@ -520,19 +521,19 @@ class BasicController extends Controller 'currency_decimal_places' => $row['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $leftToSpend, false), 'local_icon' => 'money', - 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false) + 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false), ]; } unset($leftToSpend); if (0 === count($return)) { - $days = (int) $start->diffInDays($end, true) + 1; + $days = (int) $start->diffInDays($end, true) + 1; // a small trick to get every expense in this period, regardless of budget. $spent = $this->opsRepository->sumExpenses($start, $end, null, new Collection()); foreach ($spent as $row) { // either an amount was budgeted or 0 is available. - $currencyId = (int) $row['currency_id']; - $spentInCurrency = $row['sum']; - $perDay = '0'; + $currencyId = (int) $row['currency_id']; + $spentInCurrency = $row['sum']; + $perDay = '0'; if (0 !== $days && -1 === bccomp((string) $spentInCurrency, '0')) { $perDay = bcdiv((string) $spentInCurrency, (string) $days); } @@ -550,7 +551,7 @@ class BasicController extends Controller 'currency_decimal_places' => $row['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $spentInCurrency, false), 'local_icon' => 'money', - 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false) + 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false), ]; } @@ -584,34 +585,34 @@ class BasicController extends Controller private function getNetWorthInfo(Carbon $end): array { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug(sprintf('getNetWorthInfo up until "%s".', $end->format('Y-m-d H:i:s'))); /** @var NetWorthInterface $netWorthHelper */ $netWorthHelper = app(NetWorthInterface::class); $netWorthHelper->setUser($user); - $allAccounts = $this->accountRepository->getActiveAccountsByType([ + $allAccounts = $this->accountRepository->getActiveAccountsByType([ AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::DEBT->value + AccountTypeEnum::DEBT->value, ]); // filter list on preference of being included. - $filtered = $allAccounts->filter(function (Account $account): bool { + $filtered = $allAccounts->filter(function (Account $account): bool { $includeNetWorth = $this->accountRepository->getMetaValue($account, 'include_net_worth'); return null === $includeNetWorth || '1' === $includeNetWorth; }); - $netWorthSet = $netWorthHelper->byAccounts($filtered, $end); - $return = []; + $netWorthSet = $netWorthHelper->byAccounts($filtered, $end); + $return = []; foreach ($netWorthSet as $key => $data) { if ('pc' === $key) { continue; } - $amount = $data['balance']; + $amount = $data['balance']; if (0 === bccomp((string) $amount, '0')) { continue; } @@ -626,7 +627,7 @@ class BasicController extends Controller 'currency_decimal_places' => $data['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($data['currency_symbol'], $data['currency_decimal_places'], $data['balance'], false), 'local_icon' => 'line-chart', - 'sub_title' => '' + 'sub_title' => '', ]; } if (0 === count($return)) { @@ -640,7 +641,7 @@ class BasicController extends Controller 'currency_decimal_places' => $this->primaryCurrency->decimal_places, 'value_parsed' => Amount::formatFlat($this->primaryCurrency->symbol, $this->primaryCurrency->decimal_places, '0', false), 'local_icon' => 'line-chart', - 'sub_title' => '' + 'sub_title' => '', ]; } diff --git a/app/Api/V1/Controllers/System/AboutController.php b/app/Api/V1/Controllers/System/AboutController.php index e1087659e1..2c6d53f038 100644 --- a/app/Api/V1/Controllers/System/AboutController.php +++ b/app/Api/V1/Controllers/System/AboutController.php @@ -55,7 +55,7 @@ class AboutController extends Controller 'api_version' => config('firefly.version'), 'php_version' => $phpVersion, 'os' => $phpOs, - 'driver' => $currentDriver + 'driver' => $currentDriver, ]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); @@ -69,13 +69,13 @@ class AboutController extends Controller */ public function user(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item(auth()->user(), $transformer, 'users'); + $resource = new Item(auth()->user(), $transformer, 'users'); return response()->api($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/System/ConfigurationController.php b/app/Api/V1/Controllers/System/ConfigurationController.php index 7fea3f8058..65cef0479e 100644 --- a/app/Api/V1/Controllers/System/ConfigurationController.php +++ b/app/Api/V1/Controllers/System/ConfigurationController.php @@ -102,7 +102,7 @@ class ConfigurationController extends Controller 'is_demo_site' => $isDemoSite?->data, 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data, 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data, - 'single_user_mode' => $singleUser?->data + 'single_user_mode' => $singleUser?->data, ]; } @@ -137,7 +137,7 @@ class ConfigurationController extends Controller } // fallback - $data = ['title' => $configKey, 'value' => config($shortKey), 'editable' => false]; + $data = ['title' => $configKey, 'value' => config($shortKey), 'editable' => false]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); } @@ -153,7 +153,7 @@ class ConfigurationController extends Controller */ public function update(UpdateRequest $request, string $name): JsonResponse { - $rules = ['value' => 'required']; + $rules = ['value' => 'required']; if (!$this->repository->hasRole(auth()->user(), 'owner')) { $messages = ['value' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); diff --git a/app/Api/V1/Controllers/System/CronController.php b/app/Api/V1/Controllers/System/CronController.php index 4a7d8bc0c6..05a089b9e9 100644 --- a/app/Api/V1/Controllers/System/CronController.php +++ b/app/Api/V1/Controllers/System/CronController.php @@ -44,18 +44,18 @@ class CronController extends Controller */ public function cron(CronRequest $request): JsonResponse { - $config = $request->getAll(); + $config = $request->getAll(); Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Date is %s', $config['date']->toIsoString())); - $return = []; + $return = []; $return['recurring_transactions'] = $this->runRecurring($config['force'], $config['date']); - $return['auto_budgets'] = $this->runAutoBudget($config['force'], $config['date']); + $return['auto_budgets'] = $this->runAutoBudget($config['force'], $config['date']); if (true === FireflyConfig::get('enable_external_rates', config('cer.download_enabled'))->data) { $return['exchange_rates'] = $this->exchangeRatesCronJob($config['force'], $config['date']); } - $return['bill_notifications'] = $this->billWarningCronJob($config['force'], $config['date']); - $return['webhooks'] = $this->webhookCronJob($config['force'], $config['date']); + $return['bill_notifications'] = $this->billWarningCronJob($config['force'], $config['date']); + $return['webhooks'] = $this->webhookCronJob($config['force'], $config['date']); return response()->api($return); } diff --git a/app/Api/V1/Controllers/System/UserController.php b/app/Api/V1/Controllers/System/UserController.php index 0c0191bbde..d299e45157 100644 --- a/app/Api/V1/Controllers/System/UserController.php +++ b/app/Api/V1/Controllers/System/UserController.php @@ -92,24 +92,24 @@ class UserController extends Controller public function index(): JsonResponse { // user preferences - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); // build collection - $collection = $this->repository->all(); - $count = $collection->count(); - $users = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->all(); + $count = $collection->count(); + $users = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($users, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.users.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($users, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.users.index').$this->buildParams()); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($users, $transformer, 'users'); + $resource = new FractalCollection($users, $transformer, 'users'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -124,14 +124,14 @@ class UserController extends Controller public function show(User $user): JsonResponse { // make manager - $manager = $this->getManager(); + $manager = $this->getManager(); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -144,9 +144,9 @@ class UserController extends Controller */ public function store(UserStoreRequest $request): JsonResponse { - $data = $request->getAll(); - $user = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $user = $this->repository->store($data); + $manager = $this->getManager(); // make resource @@ -154,7 +154,7 @@ class UserController extends Controller $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -167,7 +167,7 @@ class UserController extends Controller */ public function update(UserUpdateRequest $request, User $user): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); // can only update 'blocked' when user is admin. if (!$this->repository->hasRole(auth()->user(), 'owner')) { @@ -175,15 +175,15 @@ class UserController extends Controller unset($data['blocked'], $data['blocked_code']); } - $user = $this->repository->update($user, $data); - $manager = $this->getManager(); + $user = $this->repository->update($user, $data); + $manager = $this->getManager(); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php index 107364331e..9c0be7163e 100644 --- a/app/Api/V1/Controllers/User/PreferencesController.php +++ b/app/Api/V1/Controllers/User/PreferencesController.php @@ -60,14 +60,14 @@ class PreferencesController extends Controller $preferences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.preferences.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.preferences.index').$this->buildParams()); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -81,7 +81,7 @@ class PreferencesController extends Controller */ public function show(Preference $preference): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); if ('currencyPreference' === $preference->name) { throw new FireflyException('Please use api/v1/currencies/primary instead.'); @@ -91,7 +91,7 @@ class PreferencesController extends Controller $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($preference, $transformer, 'preferences'); + $resource = new Item($preference, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -104,20 +104,20 @@ class PreferencesController extends Controller */ public function store(PreferenceStoreRequest $request): JsonResponse { - $manager = $this->getManager(); - $data = $request->getAll(); + $manager = $this->getManager(); + $data = $request->getAll(); if ('currencyPreference' === $data['name']) { throw new FireflyException('Please use api/v1/currencies/default instead.'); } - $pref = Preferences::set($data['name'], $data['data']); + $pref = Preferences::set($data['name'], $data['data']); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($pref, $transformer, 'preferences'); + $resource = new Item($pref, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -134,15 +134,15 @@ class PreferencesController extends Controller throw new FireflyException('Please use api/v1/currencies/primary instead.'); } - $manager = $this->getManager(); - $data = $request->getAll(); - $pref = Preferences::set($preference->name, $data['data']); + $manager = $this->getManager(); + $data = $request->getAll(); + $pref = Preferences::set($preference->name, $data['data']); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($pref, $transformer, 'preferences'); + $resource = new Item($pref, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/AttemptController.php b/app/Api/V1/Controllers/Webhook/AttemptController.php index e958c1ad46..469c0508a3 100644 --- a/app/Api/V1/Controllers/Webhook/AttemptController.php +++ b/app/Api/V1/Controllers/Webhook/AttemptController.php @@ -82,21 +82,21 @@ class AttemptController extends Controller } Log::channel('audit')->info(sprintf('User lists webhook attempts of webhook #%d and message #%d.', $webhook->id, $message->id)); - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttempts($message); - $count = $collection->count(); - $attempts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttempts($message); + $count = $collection->count(); + $attempts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attempts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.attempts.index', [$webhook->id, $message->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($attempts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.attempts.index', [$webhook->id, $message->id]).$this->buildParams()); /** @var WebhookAttemptTransformer $transformer */ $transformer = app(WebhookAttemptTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attempts, $transformer, 'webhook_attempts'); + $resource = new FractalCollection($attempts, $transformer, 'webhook_attempts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -132,12 +132,12 @@ class AttemptController extends Controller Log::channel('audit')->info(sprintf('User views single webhook attempt #%d of webhook #%d and message #%d.', $attempt->id, $webhook->id, $message->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var WebhookAttemptTransformer $transformer */ $transformer = app(WebhookAttemptTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($attempt, $transformer, self::RESOURCE_KEY); + $resource = new Item($attempt, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/MessageController.php b/app/Api/V1/Controllers/Webhook/MessageController.php index 893a9c75f3..54bfe830c4 100644 --- a/app/Api/V1/Controllers/Webhook/MessageController.php +++ b/app/Api/V1/Controllers/Webhook/MessageController.php @@ -71,22 +71,22 @@ class MessageController extends Controller throw new NotFoundHttpException('Webhooks are not enabled.'); } Log::channel('audit')->info(sprintf('User views messages of webhook #%d.', $webhook->id)); - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getMessages($webhook); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getMessages($webhook); - $count = $collection->count(); - $messages = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $messages = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($messages, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.messages.index', [$webhook->id]) . $this->buildParams()); + $paginator = new LengthAwarePaginator($messages, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.messages.index', [$webhook->id]).$this->buildParams()); /** @var WebhookMessageTransformer $transformer */ $transformer = app(WebhookMessageTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($messages, $transformer, 'webhook_messages'); + $resource = new FractalCollection($messages, $transformer, 'webhook_messages'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -113,12 +113,12 @@ class MessageController extends Controller Log::channel('audit')->info(sprintf('User views message #%d of webhook #%d.', $message->id, $webhook->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var WebhookMessageTransformer $transformer */ $transformer = app(WebhookMessageTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($message, $transformer, self::RESOURCE_KEY); + $resource = new Item($message, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/ShowController.php b/app/Api/V1/Controllers/Webhook/ShowController.php index d0a0d24a8d..aca55e9248 100644 --- a/app/Api/V1/Controllers/Webhook/ShowController.php +++ b/app/Api/V1/Controllers/Webhook/ShowController.php @@ -79,28 +79,28 @@ class ShowController extends Controller } Log::channel('audit')->info('User views all webhooks.'); - $manager = $this->getManager(); - $collection = $this->repository->all(); - $pageSize = $this->parameters->get('limit'); - $count = $collection->count(); - $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $manager = $this->getManager(); + $collection = $this->repository->all(); + $pageSize = $this->parameters->get('limit'); + $count = $collection->count(); + $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($webhooks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.index') . $this->buildParams()); + $paginator = new LengthAwarePaginator($webhooks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.index').$this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhooks = $enrichment->enrich($webhooks); + $webhooks = $enrichment->enrich($webhooks); /** @var WebhookTransformer $transformer */ $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($webhooks, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($webhooks, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -121,19 +121,19 @@ class ShowController extends Controller } Log::channel('audit')->info(sprintf('User views webhook #%d.', $webhook->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); /** @var WebhookTransformer $transformer */ $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, self::RESOURCE_KEY); + $resource = new Item($webhook, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/StoreController.php b/app/Api/V1/Controllers/Webhook/StoreController.php index 88d3f74ff8..9d0afdd7ca 100644 --- a/app/Api/V1/Controllers/Webhook/StoreController.php +++ b/app/Api/V1/Controllers/Webhook/StoreController.php @@ -62,23 +62,23 @@ class StoreController extends Controller */ public function store(CreateRequest $request): JsonResponse { - $data = $request->getData(); + $data = $request->getData(); if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { Log::channel('audit')->info('User tries to store new webhook, but webhooks are DISABLED.', $data); throw new NotFoundHttpException('Webhooks are not enabled.'); } - $webhook = $this->repository->store($data); + $webhook = $this->repository->store($data); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); - $manager = $this->getManager(); + $manager = $this->getManager(); Log::channel('audit')->info('User stores new webhook', $data); @@ -86,7 +86,7 @@ class StoreController extends Controller $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, 'webhooks'); + $resource = new Item($webhook, $transformer, 'webhooks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/UpdateController.php b/app/Api/V1/Controllers/Webhook/UpdateController.php index 6fb658844f..30ae203b30 100644 --- a/app/Api/V1/Controllers/Webhook/UpdateController.php +++ b/app/Api/V1/Controllers/Webhook/UpdateController.php @@ -61,24 +61,24 @@ class UpdateController extends Controller */ public function update(Webhook $webhook, UpdateRequest $request): JsonResponse { - $data = $request->getData(); + $data = $request->getData(); if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { Log::channel('audit')->info(sprintf('User tries to update webhook #%d, but webhooks are DISABLED.', $webhook->id), $data); throw new NotFoundHttpException('Webhooks are not enabled.'); } - $webhook = $this->repository->update($webhook, $data); - $manager = $this->getManager(); + $webhook = $this->repository->update($webhook, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); /** @var Webhook $webhook */ - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); Log::channel('audit')->info(sprintf('User updates webhook #%d', $webhook->id), $data); @@ -86,7 +86,7 @@ class UpdateController extends Controller $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, 'webhooks'); + $resource = new Item($webhook, $transformer, 'webhooks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Requests/AggregateFormRequest.php b/app/Api/V1/Requests/AggregateFormRequest.php index 152ac7ab16..bc97d9f538 100644 --- a/app/Api/V1/Requests/AggregateFormRequest.php +++ b/app/Api/V1/Requests/AggregateFormRequest.php @@ -57,21 +57,21 @@ abstract class AggregateFormRequest extends ApiRequest /** @var array|string $config */ foreach ($this->getRequests() as $config) { - $requestClass = is_array($config) ? array_shift($config) : $config; + $requestClass = is_array($config) ? array_shift($config) : $config; if (!is_a($requestClass, Request::class, true)) { throw new RuntimeException('getRequests() must return class-strings of subclasses of Request'); } Log::debug(sprintf('Initializing subrequest %s', $requestClass)); - $instance = $this->requests[] = new $requestClass(); - $instance->request = $this->request; - $instance->query = $this->query; + $instance = $this->requests[] = new $requestClass(); + $instance->request = $this->request; + $instance->query = $this->query; $instance->attributes = $this->attributes; - $instance->cookies = $this->cookies; - $instance->files = $this->files; - $instance->server = $this->server; - $instance->headers = $this->headers; + $instance->cookies = $this->cookies; + $instance->files = $this->files; + $instance->server = $this->server; + $instance->headers = $this->headers; if ($instance instanceof ApiRequest) { $instance->handleConfig(is_array($config) ? $config : []); @@ -85,7 +85,7 @@ abstract class AggregateFormRequest extends ApiRequest // check all subrequests for rules and combine them return array_reduce( $this->requests, - static fn(array $rules, FormRequest $request): array => $rules + (method_exists($request, 'rules') ? $request->rules() : []), + static fn (array $rules, FormRequest $request): array => $rules + (method_exists($request, 'rules') ? $request->rules() : []), [] ); } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php index 1b1b8d7ada..c6a1ff1636 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php @@ -41,7 +41,7 @@ class AutocompleteApiRequest extends AggregateFormRequest DateRequest::class, [PaginationRequest::class, 'sort_class' => Account::class], [ObjectTypeApiRequest::class, 'object_type' => Account::class], - QueryRequest::class + QueryRequest::class, ]; } } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php index df2c274cd1..24192b13b5 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php @@ -50,7 +50,7 @@ class AutocompleteRequest extends FormRequest // remove 'initial balance' from allowed types. its internal $array = array_diff($array, [AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::RECONCILIATION->value]); - $date = $this->getCarbonDate('date') ?? today(config('app.timezone')); + $date = $this->getCarbonDate('date') ?? today(config('app.timezone')); return ['types' => $array, 'query' => $this->convertString('query'), 'date' => $date->endOfDay()]; } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php index 4bf484771f..a9bfc4f1be 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php @@ -42,7 +42,7 @@ class AutocompleteTransactionApiRequest extends AggregateFormRequest DateRequest::class, [PaginationRequest::class, 'sort_class' => Account::class], [ObjectTypeApiRequest::class, 'object_type' => Transaction::class], - QueryRequest::class + QueryRequest::class, ]; } } diff --git a/app/Api/V1/Requests/Chart/ChartRequest.php b/app/Api/V1/Requests/Chart/ChartRequest.php index e9a9bf5294..0d7a3b4dad 100644 --- a/app/Api/V1/Requests/Chart/ChartRequest.php +++ b/app/Api/V1/Requests/Chart/ChartRequest.php @@ -50,7 +50,7 @@ class ChartRequest extends FormRequest 'end' => $this->convertDateTime('end')?->endOfDay(), 'preselected' => $this->convertString('preselected', 'empty'), 'period' => $this->convertString('period', '1M'), - 'accounts' => $this->arrayFromValue($this->get('accounts')) + 'accounts' => $this->arrayFromValue($this->get('accounts')), ]; } @@ -65,7 +65,7 @@ class ChartRequest extends FormRequest 'preselected' => sprintf('nullable|in:%s', implode(',', config('firefly.preselected_accounts'))), 'period' => sprintf('nullable|in:%s', implode(',', config('firefly.valid_view_ranges'))), 'accounts' => 'nullable|array', - 'accounts.*' => 'exists:accounts,id' + 'accounts.*' => 'exists:accounts,id', ]; } diff --git a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php index bc02ffec68..e45637c0e1 100644 --- a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php +++ b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php @@ -51,7 +51,7 @@ class MoveTransactionsRequest extends FormRequest { return [ 'original_account' => 'required|different:destination_account|belongsToUser:accounts,id', - 'destination_account' => 'required|different:original_account|belongsToUser:accounts,id' + 'destination_account' => 'required|different:original_account|belongsToUser:accounts,id', ]; } @@ -75,11 +75,11 @@ class MoveTransactionsRequest extends FormRequest private function validateMove(Validator $validator): void { - $data = $validator->getData(); - $repository = app(AccountRepositoryInterface::class); + $data = $validator->getData(); + $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $original = $repository->find((int) $data['original_account']); - $destination = $repository->find((int) $data['destination_account']); + $original = $repository->find((int) $data['original_account']); + $destination = $repository->find((int) $data['destination_account']); // not the same type: if ($original->accountType->type !== $destination->accountType->type) { diff --git a/app/Api/V1/Requests/Data/DestroyRequest.php b/app/Api/V1/Requests/Data/DestroyRequest.php index e1c1745393..c860090e84 100644 --- a/app/Api/V1/Requests/Data/DestroyRequest.php +++ b/app/Api/V1/Requests/Data/DestroyRequest.php @@ -49,10 +49,10 @@ class DestroyRequest extends FormRequest */ public function rules(): array { - $valid = - 'budgets,bills,piggy_banks,rules,recurring,categories,tags,object_groups' - . ',accounts,asset_accounts,expense_accounts,revenue_accounts,liabilities,transactions,withdrawals,deposits,transfers' - . ',not_assets_liabilities'; + $valid + = 'budgets,bills,piggy_banks,rules,recurring,categories,tags,object_groups' + .',accounts,asset_accounts,expense_accounts,revenue_accounts,liabilities,transactions,withdrawals,deposits,transfers' + .',not_assets_liabilities'; return ['objects' => sprintf('required|max:255|min:1|string|in:%s', $valid), 'unused' => 'in:true,false']; } diff --git a/app/Api/V1/Requests/Data/Export/ExportRequest.php b/app/Api/V1/Requests/Data/Export/ExportRequest.php index 6d7c4f6989..67f74a37ea 100644 --- a/app/Api/V1/Requests/Data/Export/ExportRequest.php +++ b/app/Api/V1/Requests/Data/Export/ExportRequest.php @@ -41,16 +41,16 @@ class ExportRequest extends FormRequest public function getAll(): array { - $result = [ + $result = [ 'start' => $this->getCarbonDate('start') ?? today(config('app.timezone'))->subYear(), 'end' => $this->getCarbonDate('end') ?? today(config('app.timezone')), - 'type' => $this->convertString('type') + 'type' => $this->convertString('type'), ]; - $parts = explode(',', $this->convertString('accounts')); - $repository = app(AccountRepositoryInterface::class); + $parts = explode(',', $this->convertString('accounts')); + $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $accounts = new Collection(); + $accounts = new Collection(); foreach ($parts as $part) { $accountId = (int) $part; if (0 !== $accountId) { diff --git a/app/Api/V1/Requests/DateRangeRequest.php b/app/Api/V1/Requests/DateRangeRequest.php index f948e75b56..e53284a003 100644 --- a/app/Api/V1/Requests/DateRangeRequest.php +++ b/app/Api/V1/Requests/DateRangeRequest.php @@ -31,7 +31,7 @@ class DateRangeRequest extends ApiRequest { return [ 'start' => sprintf('date|after:1970-01-02|before:2038-01-17|before:end|required_with:end|%s', $this->required), - 'end' => sprintf('date|after:1970-01-02|before:2038-01-17|after:start|required_with:start|%s', $this->required) + 'end' => sprintf('date|after:1970-01-02|before:2038-01-17|after:start|required_with:start|%s', $this->required), ]; } diff --git a/app/Api/V1/Requests/DateRequest.php b/app/Api/V1/Requests/DateRequest.php index e60b98472b..0f48b9f2bf 100644 --- a/app/Api/V1/Requests/DateRequest.php +++ b/app/Api/V1/Requests/DateRequest.php @@ -30,7 +30,7 @@ class DateRequest extends ApiRequest { public function rules(): array { - return ['date' => 'date|after:1970-01-02|before:2038-01-17|' . $this->required]; + return ['date' => 'date|after:1970-01-02|before:2038-01-17|'.$this->required]; } public function withValidator(Validator $validator): void @@ -39,7 +39,7 @@ class DateRequest extends ApiRequest if ($validator->failed()) { return; } - $date = $this->getCarbonDate('date')?->endOfDay(); + $date = $this->getCarbonDate('date')?->endOfDay(); // if we also have a range, date must be in that range $start = $this->attributes->get('start'); diff --git a/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php b/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php index fe2fd09e2c..d551442cb2 100644 --- a/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php +++ b/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php @@ -41,7 +41,7 @@ class ObjectTypeApiRequest extends ApiRequest use AccountFilter; use TransactionFilter; - private null|string $objectType = null; + private ?string $objectType = null; #[Override] public function handleConfig(array $config): void @@ -57,7 +57,7 @@ class ObjectTypeApiRequest extends ApiRequest public function rules(): array { - $rule = null; + $rule = null; if (Account::class === $this->objectType) { $rule = new IsValidAccountTypeList(); } @@ -85,7 +85,7 @@ class ObjectTypeApiRequest extends ApiRequest default: $this->attributes->set('types', []); - // no break + // no break case Account::class: $types = $this->mapAccountTypes($type); @@ -93,7 +93,7 @@ class ObjectTypeApiRequest extends ApiRequest $types = array_values(array_diff($types, [ AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::RECONCILIATION->value, - AccountTypeEnum::LIABILITY_CREDIT->value + AccountTypeEnum::LIABILITY_CREDIT->value, ])); $this->attributes->set('types', $types); diff --git a/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php b/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php index 6c3b363031..0ac9d037ef 100644 --- a/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php +++ b/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php @@ -40,7 +40,7 @@ class PaginationDateRangeRequest extends AggregateFormRequest return [ DateRangeRequest::class, [ObjectTypeApiRequest::class, 'object_type' => Transaction::class], - [PaginationRequest::class, 'sort_class' => Transaction::class] + [PaginationRequest::class, 'sort_class' => Transaction::class], ]; } } diff --git a/app/Api/V1/Requests/Insight/GenericRequest.php b/app/Api/V1/Requests/Insight/GenericRequest.php index edfbcd11df..a60defe4da 100644 --- a/app/Api/V1/Requests/Insight/GenericRequest.php +++ b/app/Api/V1/Requests/Insight/GenericRequest.php @@ -86,7 +86,7 @@ class GenericRequest extends FormRequest } $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('accounts'); + $array = $this->get('accounts'); if (is_array($array)) { foreach ($array as $accountId) { $accountId = (int) $accountId; @@ -112,7 +112,7 @@ class GenericRequest extends FormRequest } $repository = app(BillRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('bills'); + $array = $this->get('bills'); if (is_array($array)) { foreach ($array as $billId) { $billId = (int) $billId; @@ -138,7 +138,7 @@ class GenericRequest extends FormRequest } $repository = app(BudgetRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('budgets'); + $array = $this->get('budgets'); if (is_array($array)) { foreach ($array as $budgetId) { $budgetId = (int) $budgetId; @@ -164,7 +164,7 @@ class GenericRequest extends FormRequest } $repository = app(CategoryRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('categories'); + $array = $this->get('categories'); if (is_array($array)) { foreach ($array as $categoryId) { $categoryId = (int) $categoryId; @@ -238,7 +238,7 @@ class GenericRequest extends FormRequest } $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('tags'); + $array = $this->get('tags'); if (is_array($array)) { foreach ($array as $tagId) { $tagId = (int) $tagId; @@ -256,11 +256,11 @@ class GenericRequest extends FormRequest public function rules(): array { // this is cheating, but it works to initialize the collections. - $this->accounts = new Collection(); - $this->budgets = new Collection(); + $this->accounts = new Collection(); + $this->budgets = new Collection(); $this->categories = new Collection(); - $this->bills = new Collection(); - $this->tags = new Collection(); + $this->bills = new Collection(); + $this->tags = new Collection(); return ['start' => 'required|date', 'end' => 'required|date|after_or_equal:start']; } diff --git a/app/Api/V1/Requests/Models/Account/ShowRequest.php b/app/Api/V1/Requests/Models/Account/ShowRequest.php index 4c7aa90dd1..b2a0c51095 100644 --- a/app/Api/V1/Requests/Models/Account/ShowRequest.php +++ b/app/Api/V1/Requests/Models/Account/ShowRequest.php @@ -38,7 +38,7 @@ class ShowRequest extends AggregateFormRequest [PaginationRequest::class, 'sort_class' => Account::class], DateRangeRequest::class, DateRequest::class, - AccountTypeApiRequest::class + AccountTypeApiRequest::class, // [ObjectTypeApiRequest::class, 'object_type' => Account::class], ]; } diff --git a/app/Api/V1/Requests/Models/Account/StoreRequest.php b/app/Api/V1/Requests/Models/Account/StoreRequest.php index b05190d7d8..3d04bb7cee 100644 --- a/app/Api/V1/Requests/Models/Account/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Account/StoreRequest.php @@ -53,7 +53,7 @@ class StoreRequest extends FormRequest if (null !== $this->get('include_net_worth')) { $includeNetWorth = $this->boolean('include_net_worth'); } - $data = [ + $data = [ 'name' => $this->convertString('name'), 'active' => $active, 'include_net_worth' => $includeNetWorth, @@ -73,15 +73,15 @@ class StoreRequest extends FormRequest 'cc_monthly_payment_date' => $this->convertString('monthly_payment_date'), 'notes' => $this->stringWithNewlines('notes'), 'interest' => $this->convertString('interest'), - 'interest_period' => $this->convertString('interest_period') + 'interest_period' => $this->convertString('interest_period'), ]; // append location information. - $data = $this->appendLocationData($data, null); + $data = $this->appendLocationData($data, null); if ('liability' === $data['account_type_name'] || 'liabilities' === $data['account_type_name']) { - $data['account_type_name'] = $this->convertString('liability_type'); + $data['account_type_name'] = $this->convertString('liability_type'); $data['liability_direction'] = $this->convertString('liability_direction'); - $data['account_type_id'] = null; + $data['account_type_id'] = null; } return $data; @@ -98,7 +98,7 @@ class StoreRequest extends FormRequest $type = $this->convertString('type'); $rules = [ 'name' => 'required|max:1024|min:1|uniqueAccountForUser', - 'type' => 'required|max:1024|min:1|' . sprintf('in:%s', $types), + 'type' => 'required|max:1024|min:1|'.sprintf('in:%s', $types), 'iban' => ['iban', 'nullable', new UniqueIban(null, $type)], 'bic' => 'bic|nullable', 'account_number' => ['min:1', 'max:255', 'nullable', new UniqueAccountNumber(null, $type)], @@ -119,7 +119,7 @@ class StoreRequest extends FormRequest 'liability_direction' => 'nullable|required_if:type,liability|required_if:type,liabilities|in:credit,debit', 'interest' => 'min:0|max:100|numeric', 'interest_period' => sprintf('nullable|in:%s', implode(',', config('firefly.interest_periods'))), - 'notes' => 'min:0|max:32768' + 'notes' => 'min:0|max:32768', ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Account/UpdateRequest.php b/app/Api/V1/Requests/Models/Account/UpdateRequest.php index fbd7b48b3e..7e52355446 100644 --- a/app/Api/V1/Requests/Models/Account/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Account/UpdateRequest.php @@ -71,7 +71,7 @@ class UpdateRequest extends FormRequest 'currency_code' => ['currency_code', 'convertString'], 'liability_direction' => ['liability_direction', 'convertString'], 'liability_amount' => ['liability_amount', 'convertString'], - 'liability_start_date' => ['liability_start_date', 'date'] + 'liability_start_date' => ['liability_start_date', 'date'], ]; $data = $this->getAllData($fields); @@ -89,7 +89,7 @@ class UpdateRequest extends FormRequest $types = implode(',', array_keys(config('firefly.subTitlesByIdentifier'))); $ccPaymentTypes = implode(',', array_keys(config('firefly.ccTypes'))); - $rules = [ + $rules = [ 'name' => sprintf('min:1|max:1024|uniqueAccountForUser:%d', $account->id), 'type' => sprintf('in:%s', $types), 'iban' => ['iban', 'nullable', new UniqueIban($account, $this->convertString('type'))], @@ -110,7 +110,7 @@ class UpdateRequest extends FormRequest 'liability_direction' => 'required_if:type,liability|in:credit,debit', 'interest' => 'required_if:type,liability|min:0|max:100|numeric', 'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly', - 'notes' => 'min:0|max:32768' + 'notes' => 'min:0|max:32768', ]; return Location::requestRules($rules); @@ -123,10 +123,10 @@ class UpdateRequest extends FormRequest { $validator->after(function (Validator $validator): void { // validate start before end only if both are there. - $data = $validator->getData(); + $data = $validator->getData(); /** @var Account $account */ - $account = $this->route()->parameter('account'); + $account = $this->route()->parameter('account'); /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); diff --git a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php index ca320ff7f3..4dffe9a4d6 100644 --- a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php @@ -47,7 +47,7 @@ class StoreRequest extends FormRequest 'title' => $this->convertString('title'), 'notes' => $this->stringWithNewlines('notes'), 'attachable_type' => $this->convertString('attachable_type'), - 'attachable_id' => $this->convertInteger('attachable_id') + 'attachable_id' => $this->convertInteger('attachable_id'), ]; } @@ -57,7 +57,7 @@ class StoreRequest extends FormRequest public function rules(): array { $models = config('firefly.valid_attachment_models'); - $models = array_map(static fn(string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); + $models = array_map(static fn (string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); $models = implode(',', $models); $model = $this->convertString('attachable_type'); @@ -66,7 +66,7 @@ class StoreRequest extends FormRequest 'title' => ['min:1', 'max:255'], 'notes' => 'min:1|max:32768', 'attachable_type' => sprintf('required|in:%s', $models), - 'attachable_id' => ['required', 'numeric', new IsValidAttachmentModel($model)] + 'attachable_id' => ['required', 'numeric', new IsValidAttachmentModel($model)], ]; } } diff --git a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php index 8af6e65235..f2acb73533 100644 --- a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php @@ -47,7 +47,7 @@ class UpdateRequest extends FormRequest 'title' => ['title', 'convertString'], 'notes' => ['notes', 'stringWithNewlines'], 'attachable_type' => ['attachable_type', 'convertString'], - 'attachable_id' => ['attachable_id', 'convertInteger'] + 'attachable_id' => ['attachable_id', 'convertInteger'], ]; return $this->getAllData($fields); @@ -59,7 +59,7 @@ class UpdateRequest extends FormRequest public function rules(): array { $models = config('firefly.valid_attachment_models'); - $models = array_map(static fn(string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); + $models = array_map(static fn (string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); $models = implode(',', $models); $model = $this->convertString('attachable_type'); @@ -68,7 +68,7 @@ class UpdateRequest extends FormRequest 'title' => ['min:1', 'max:255'], 'notes' => 'min:1|max:32768', 'attachable_type' => sprintf('in:%s', $models), - 'attachable_id' => ['numeric', new IsValidAttachmentModel($model)] + 'attachable_id' => ['numeric', new IsValidAttachmentModel($model)], ]; } } diff --git a/app/Api/V1/Requests/Models/AvailableBudget/Request.php b/app/Api/V1/Requests/Models/AvailableBudget/Request.php index 1cf970ffdf..e3824e40e6 100644 --- a/app/Api/V1/Requests/Models/AvailableBudget/Request.php +++ b/app/Api/V1/Requests/Models/AvailableBudget/Request.php @@ -51,7 +51,7 @@ class Request extends FormRequest 'currency_code' => ['currency_code', 'convertString'], 'amount' => ['amount', 'convertString'], 'start' => ['start', 'date'], - 'end' => ['end', 'date'] + 'end' => ['end', 'date'], ]; return $this->getAllData($fields); @@ -67,7 +67,7 @@ class Request extends FormRequest 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', 'amount' => ['nullable', new IsValidPositiveAmount()], 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after:1970-01-02|before:2038-01-17' + 'end' => 'date|after:1970-01-02|before:2038-01-17', ]; } diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.php index 0328ec21fb..b477319c27 100644 --- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php @@ -63,7 +63,7 @@ class StoreRequest extends FormRequest 'order' => ['order', 'convertInteger'], 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'convertInteger'], - 'object_group_title' => ['object_group_title', 'convertString'] + 'object_group_title' => ['object_group_title', 'convertString'], ]; return $this->getAllData($fields); @@ -86,7 +86,7 @@ class StoreRequest extends FormRequest 'repeat_freq' => 'in:weekly,monthly,quarterly,half-year,yearly|required', 'skip' => 'min:0|max:31|numeric', 'active' => [new IsBoolean()], - 'notes' => 'nullable|min:1|max:32768' + 'notes' => 'nullable|min:1|max:32768', ]; } @@ -96,9 +96,9 @@ class StoreRequest extends FormRequest public function withValidator(Validator $validator): void { $validator->after(static function (Validator $validator): void { - $data = $validator->getData(); - $min = $data['amount_min'] ?? '0'; - $max = $data['amount_max'] ?? '0'; + $data = $validator->getData(); + $min = $data['amount_min'] ?? '0'; + $max = $data['amount_max'] ?? '0'; if (is_array($min) || is_array($max)) { $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); diff --git a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php index 2bccda208b..46432386ef 100644 --- a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php @@ -61,7 +61,7 @@ class UpdateRequest extends FormRequest 'order' => ['order', 'convertInteger'], 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'convertInteger'], - 'object_group_title' => ['object_group_title', 'convertString'] + 'object_group_title' => ['object_group_title', 'convertString'], ]; return $this->getAllData($fields); @@ -87,7 +87,7 @@ class UpdateRequest extends FormRequest 'repeat_freq' => 'in:weekly,monthly,quarterly,half-year,yearly', 'skip' => 'min:0|max:31|numeric', 'active' => [new IsBoolean()], - 'notes' => 'min:1|max:32768' + 'notes' => 'min:1|max:32768', ]; } diff --git a/app/Api/V1/Requests/Models/Budget/StoreRequest.php b/app/Api/V1/Requests/Models/Budget/StoreRequest.php index 86f0e6df03..a062b0a9b3 100644 --- a/app/Api/V1/Requests/Models/Budget/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Budget/StoreRequest.php @@ -48,10 +48,10 @@ class StoreRequest extends FormRequest public function getAll(): array { $fields = [ - 'name' => ['name', 'convertString'], - 'active' => ['active', 'boolean'], - 'order' => ['active', 'convertInteger'], - 'notes' => ['notes', 'convertString'], + 'name' => ['name', 'convertString'], + 'active' => ['active', 'boolean'], + 'order' => ['active', 'convertInteger'], + 'notes' => ['notes', 'convertString'], // auto budget currency: 'currency_id' => ['auto_budget_currency_id', 'convertInteger'], @@ -61,7 +61,7 @@ class StoreRequest extends FormRequest 'auto_budget_period' => ['auto_budget_period', 'convertString'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'] + 'fire_webhooks' => ['fire_webhooks', 'boolean'], ]; return $this->getAllData($fields); @@ -73,23 +73,23 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'name' => 'required|min:1|max:255|uniqueObjectForUser:budgets,name', - 'active' => [new IsBoolean()], - 'currency_id' => 'exists:transaction_currencies,id', - 'currency_code' => 'exists:transaction_currencies,code', - 'notes' => 'nullable|min:1|max:32768', + 'name' => 'required|min:1|max:255|uniqueObjectForUser:budgets,name', + 'active' => [new IsBoolean()], + 'currency_id' => 'exists:transaction_currencies,id', + 'currency_code' => 'exists:transaction_currencies,code', + 'notes' => 'nullable|min:1|max:32768', // auto budget info 'auto_budget_type' => 'in:reset,rollover,adjusted,none', 'auto_budget_amount' => [ 'required_if:auto_budget_type,reset', 'required_if:auto_budget_type,rollover', 'required_if:auto_budget_type,adjusted', - new IsValidPositiveAmount() + new IsValidPositiveAmount(), ], 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly|required_if:auto_budget_type,reset|required_if:auto_budget_type,rollover|required_if:auto_budget_type,adjusted', // webhooks - 'fire_webhooks' => [new IsBoolean()] + 'fire_webhooks' => [new IsBoolean()], ]; } diff --git a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php index a2b8286602..6ce23ba8d0 100644 --- a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php @@ -61,11 +61,11 @@ class UpdateRequest extends FormRequest 'auto_budget_period' => ['auto_budget_period', 'convertString'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'] + 'fire_webhooks' => ['fire_webhooks', 'boolean'], ]; $allData = $this->getAllData($fields); if (array_key_exists('auto_budget_type', $allData)) { - $types = ['none' => 0, 'reset' => 1, 'rollover' => 2, 'adjusted' => 3]; + $types = ['none' => 0, 'reset' => 1, 'rollover' => 2, 'adjusted' => 3]; $allData['auto_budget_type'] = $types[$allData['auto_budget_type']] ?? 0; } @@ -91,7 +91,7 @@ class UpdateRequest extends FormRequest 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', // webhooks - 'fire_webhooks' => [new IsBoolean()] + 'fire_webhooks' => [new IsBoolean()], ]; } diff --git a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php index b02e15a6f1..b02b19dc9f 100644 --- a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php +++ b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php @@ -57,7 +57,7 @@ class StoreRequest extends FormRequest 'notes' => $this->stringWithNewlines('notes'), // for webhooks: - 'fire_webhooks' => $this->boolean('fire_webhooks', true) + 'fire_webhooks' => $this->boolean('fire_webhooks', true), ]; } @@ -75,7 +75,7 @@ class StoreRequest extends FormRequest 'notes' => 'nullable|min:0|max:32768', // webhooks - 'fire_webhooks' => [new IsBoolean()] + 'fire_webhooks' => [new IsBoolean()], ]; } @@ -89,12 +89,12 @@ class StoreRequest extends FormRequest if (0 !== count($validator->failed())) { return; } - $data = $validator->getData(); + $data = $validator->getData(); // if no currency has been provided, use the user's default currency: /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); if (null === $currency) { $currency = Amount::getPrimaryCurrency(); } @@ -102,16 +102,17 @@ class StoreRequest extends FormRequest $currency->save(); // validator already concluded start and end are valid dates: - $start = Carbon::parse($data['start'], config('app.timezone')); - $end = Carbon::parse($data['end'], config('app.timezone')); + $start = Carbon::parse($data['start'], config('app.timezone')); + $end = Carbon::parse($data['end'], config('app.timezone')); // find limit with same date range and currency. - $limit = $budget + $limit = $budget ->budgetlimits() ->where('budget_limits.start_date', $start->format('Y-m-d')) ->where('budget_limits.end_date', $end->format('Y-m-d')) ->where('budget_limits.transaction_currency_id', $currency->id) - ->first(['budget_limits.*']); + ->first(['budget_limits.*']) + ; if (null !== $limit) { $validator->errors()->add('start', trans('validation.limit_exists')); } diff --git a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php index 656a96b8a2..5f2f2d0366 100644 --- a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php @@ -55,7 +55,7 @@ class UpdateRequest extends FormRequest 'notes' => ['notes', 'stringWithNewlines'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'] + 'fire_webhooks' => ['fire_webhooks', 'boolean'], ]; if (false === $this->has('notes')) { // ignore notes, not submitted. @@ -79,7 +79,7 @@ class UpdateRequest extends FormRequest 'notes' => 'nullable|min:0|max:32768', // webhooks - 'fire_webhooks' => [new IsBoolean()] + 'fire_webhooks' => [new IsBoolean()], ]; } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php index 038dd658cb..82ff8ca3de 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php @@ -34,7 +34,7 @@ class DestroyRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): null|Carbon + public function getDate(): ?Carbon { return $this->getCarbonDate('date'); } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php index 29685ec606..6038a65f02 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php @@ -36,7 +36,7 @@ class StoreRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): null|Carbon + public function getDate(): ?Carbon { return $this->getCarbonDate('date'); } @@ -65,7 +65,7 @@ class StoreRequest extends FormRequest 'date' => 'required|date|after:1970-01-02|before:2038-01-17', 'rate' => 'required|numeric|gt:0', 'from' => 'required|exists:transaction_currencies,code', - 'to' => 'required|exists:transaction_currencies,code' + 'to' => 'required|exists:transaction_currencies,code', ]; } } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php index 725a1701c2..8114b7abed 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php @@ -34,7 +34,7 @@ class UpdateRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): null|Carbon + public function getDate(): ?Carbon { return $this->getCarbonDate('date'); } @@ -53,7 +53,7 @@ class UpdateRequest extends FormRequest 'date' => 'date|after:1970-01-02|before:2038-01-17', 'rate' => 'required|numeric|gt:0', 'from' => 'nullable|exists:transaction_currencies,code', - 'to' => 'nullable|exists:transaction_currencies,code' + 'to' => 'nullable|exists:transaction_currencies,code', ]; } } diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php index 55d6d9926c..2e3522b75a 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php @@ -47,18 +47,18 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - $fields = ['order' => ['order', 'convertInteger']]; - $data = $this->getAllData($fields); - $data['name'] = $this->convertString('name'); - $data['accounts'] = $this->parseAccounts($this->get('accounts')); - $data['target_amount'] = $this->convertString('target_amount'); - $data['start_date'] = $this->getCarbonDate('start_date'); - $data['target_date'] = $this->getCarbonDate('target_date'); - $data['notes'] = $this->stringWithNewlines('notes'); - $data['object_group_id'] = $this->convertInteger('object_group_id'); - $data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id'); + $fields = ['order' => ['order', 'convertInteger']]; + $data = $this->getAllData($fields); + $data['name'] = $this->convertString('name'); + $data['accounts'] = $this->parseAccounts($this->get('accounts')); + $data['target_amount'] = $this->convertString('target_amount'); + $data['start_date'] = $this->getCarbonDate('start_date'); + $data['target_date'] = $this->getCarbonDate('target_date'); + $data['notes'] = $this->stringWithNewlines('notes'); + $data['object_group_id'] = $this->convertInteger('object_group_id'); + $data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id'); $data['transaction_currency_code'] = $this->convertString('transaction_currency_code'); - $data['object_group_title'] = $this->convertString('object_group_title'); + $data['object_group_title'] = $this->convertString('object_group_title'); return $data; } @@ -81,7 +81,7 @@ class StoreRequest extends FormRequest 'transaction_currency_id' => 'exists:transaction_currencies,id|required_without:transaction_currency_code', 'transaction_currency_code' => 'exists:transaction_currencies,code|required_without:transaction_currency_id', 'target_date' => 'date|nullable|after:start_date', - 'notes' => 'max:65000' + 'notes' => 'max:65000', ]; } @@ -92,8 +92,8 @@ class StoreRequest extends FormRequest { $validator->after(function (Validator $validator): void { // validate start before end only if both are there. - $data = $validator->getData(); - $currency = $this->getCurrencyFromData($validator, $data); + $data = $validator->getData(); + $currency = $this->getCurrencyFromData($validator, $data); if (!$currency instanceof TransactionCurrency) { return; } @@ -113,7 +113,7 @@ class StoreRequest extends FormRequest if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_currency')); } - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array($type, $types, true)) { $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type')); } @@ -129,7 +129,7 @@ class StoreRequest extends FormRequest } } - private function getCurrencyFromData(Validator $validator, array $data): null|TransactionCurrency + private function getCurrencyFromData(Validator $validator, array $data): ?TransactionCurrency { if (array_key_exists('transaction_currency_code', $data) && '' !== (string) $data['transaction_currency_code']) { return Amount::getTransactionCurrencyByCode((string) $data['transaction_currency_code']); diff --git a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php index 949f7ecf26..0a6b4debf8 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php @@ -45,7 +45,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'name' => ['name', 'convertString'], 'target_amount' => ['target_amount', 'convertString'], 'start_date' => ['start_date', 'convertDateTime'], @@ -55,10 +55,10 @@ class UpdateRequest extends FormRequest 'object_group_title' => ['object_group_title', 'convertString'], 'object_group_id' => ['object_group_id', 'convertInteger'], 'transaction_currency_code' => ['transaction_currency_code', 'convertString'], - 'transaction_currency_id' => ['transaction_currency_id', 'convertInteger'] + 'transaction_currency_id' => ['transaction_currency_id', 'convertInteger'], ]; - $result = $this->getAllData($fields); + $result = $this->getAllData($fields); $result['accounts'] = $this->parseAccounts($this->get('accounts')); return $result; @@ -73,7 +73,7 @@ class UpdateRequest extends FormRequest $piggyBank = $this->route()->parameter('piggyBank'); return [ - 'name' => 'min:1|max:255|uniquePiggyBankForUser:' . $piggyBank->id, + 'name' => 'min:1|max:255|uniquePiggyBankForUser:'.$piggyBank->id, 'current_amount' => ['nullable', new LessThanPiggyTarget(), new IsValidPositiveAmount()], 'target_amount' => ['nullable', new IsValidZeroOrMoreAmount()], 'start_date' => 'date|nullable', @@ -86,7 +86,7 @@ class UpdateRequest extends FormRequest 'object_group_id' => 'numeric|belongsToUser:object_groups,id', 'object_group_title' => ['min:1', 'max:255'], 'transaction_currency_id' => 'exists:transaction_currencies,id|nullable', - 'transaction_currency_code' => 'exists:transaction_currencies,code|nullable' + 'transaction_currency_code' => 'exists:transaction_currencies,code|nullable', ]; } } diff --git a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php index 051f7ca848..3552bf01a8 100644 --- a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php @@ -63,7 +63,7 @@ class StoreRequest extends FormRequest 'nr_of_repetitions' => ['nr_of_repetitions', 'convertInteger'], 'apply_rules' => ['apply_rules', 'boolean'], 'active' => ['active', 'boolean'], - 'notes' => ['notes', 'stringWithNewlines'] + 'notes' => ['notes', 'stringWithNewlines'], ]; $recurrence = $this->getAllData($fields); @@ -76,7 +76,7 @@ class StoreRequest extends FormRequest */ private function getTransactionData(): array { - $return = []; + $return = []; // transaction data: /** @var null|array $transactions */ @@ -98,7 +98,7 @@ class StoreRequest extends FormRequest */ private function getRepetitionData(): array { - $return = []; + $return = []; // repetition data: /** @var null|array $repetitions */ @@ -109,7 +109,7 @@ class StoreRequest extends FormRequest /** @var array $repetition */ foreach ($repetitions as $repetition) { - $current = []; + $current = []; if (array_key_exists('type', $repetition)) { $current['type'] = $repetition['type']; } @@ -135,19 +135,19 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'type' => 'required|in:withdrawal,transfer,deposit', - 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', - 'description' => 'min:1|max:32768', - 'first_date' => 'required|date', - 'apply_rules' => [new IsBoolean()], - 'active' => [new IsBoolean()], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', + 'type' => 'required|in:withdrawal,transfer,deposit', + 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', + 'description' => 'min:1|max:32768', + 'first_date' => 'required|date', + 'apply_rules' => [new IsBoolean()], + 'active' => [new IsBoolean()], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', - 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', - 'repetitions.*.moment' => 'min:0|max:10', - 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', - 'repetitions.*.weekend' => 'numeric|min:1|max:4', + 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', + 'repetitions.*.moment' => 'min:0|max:10', + 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', + 'repetitions.*.weekend' => 'numeric|min:1|max:4', 'transactions.*.description' => 'required|min:1|max:255', 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], @@ -162,13 +162,13 @@ class StoreRequest extends FormRequest 'transactions.*.destination_name' => 'min:1|max:255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.tags' => 'nullable|min:1|max:255' + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.tags' => 'nullable|min:1|max:255', ]; } diff --git a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php index aa93a64951..fded74916b 100644 --- a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php @@ -56,7 +56,7 @@ class UpdateRequest extends FormRequest public function getAll(): array { // this is the way: - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'convertString'], 'first_date' => ['first_date', 'convertDateTime'], @@ -64,11 +64,11 @@ class UpdateRequest extends FormRequest 'nr_of_repetitions' => ['nr_of_repetitions', 'convertInteger'], 'apply_rules' => ['apply_rules', 'boolean'], 'active' => ['active', 'boolean'], - 'notes' => ['notes', 'convertString'] + 'notes' => ['notes', 'convertString'], ]; - $reps = $this->getRepetitionData(); - $transactions = $this->getTransactionData(); - $return = ['recurrence' => $this->getAllData($fields)]; + $reps = $this->getRepetitionData(); + $transactions = $this->getTransactionData(); + $return = ['recurrence' => $this->getAllData($fields)]; if (null !== $reps) { $return['repetitions'] = $reps; } @@ -80,9 +80,9 @@ class UpdateRequest extends FormRequest /** * Returns the repetition data as it is found in the submitted data. */ - private function getRepetitionData(): null|array + private function getRepetitionData(): ?array { - $return = []; + $return = []; // repetition data: /** @var null|array $repetitions */ @@ -93,7 +93,7 @@ class UpdateRequest extends FormRequest /** @var array $repetition */ foreach ($repetitions as $repetition) { - $current = []; + $current = []; if (array_key_exists('type', $repetition)) { $current['type'] = $repetition['type']; } @@ -124,7 +124,7 @@ class UpdateRequest extends FormRequest */ private function getTransactionData(): array { - $return = []; + $return = []; // transaction data: /** @var null|array $transactions */ @@ -150,18 +150,18 @@ class UpdateRequest extends FormRequest $recurrence = $this->route()->parameter('recurrence'); return [ - 'title' => sprintf('min:1|max:255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), - 'description' => 'min:1|max:32768', - 'first_date' => 'date|after:1970-01-02|before:2038-01-17', - 'apply_rules' => [new IsBoolean()], - 'active' => [new IsBoolean()], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', + 'title' => sprintf('min:1|max:255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), + 'description' => 'min:1|max:32768', + 'first_date' => 'date|after:1970-01-02|before:2038-01-17', + 'apply_rules' => [new IsBoolean()], + 'active' => [new IsBoolean()], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', - 'repetitions.*.type' => 'in:daily,weekly,ndom,monthly,yearly', - 'repetitions.*.moment' => 'min:0|max:10|numeric', - 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', - 'repetitions.*.weekend' => 'nullable|numeric|min:1|max:4', + 'repetitions.*.type' => 'in:daily,weekly,ndom,monthly,yearly', + 'repetitions.*.moment' => 'min:0|max:10|numeric', + 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', + 'repetitions.*.weekend' => 'nullable|numeric|min:1|max:4', 'transactions.*.description' => ['min:1', 'max:255'], 'transactions.*.amount' => [new IsValidPositiveAmount()], @@ -176,13 +176,13 @@ class UpdateRequest extends FormRequest 'transactions.*.destination_name' => 'min:1|max:255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.tags' => 'nullable|min:1|max:255' + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.tags' => 'nullable|min:1|max:255', ]; } diff --git a/app/Api/V1/Requests/Models/Rule/StoreRequest.php b/app/Api/V1/Requests/Models/Rule/StoreRequest.php index 9fa4b211f5..9bfbd7fd7b 100644 --- a/app/Api/V1/Requests/Models/Rule/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Rule/StoreRequest.php @@ -47,7 +47,7 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'convertString'], 'rule_group_id' => ['rule_group_id', 'convertInteger'], @@ -56,11 +56,11 @@ class StoreRequest extends FormRequest 'trigger' => ['trigger', 'convertString'], 'strict' => ['strict', 'boolean'], 'stop_processing' => ['stop_processing', 'boolean'], - 'active' => ['active', 'boolean'] + 'active' => ['active', 'boolean'], ]; - $data = $this->getAllData($fields); + $data = $this->getAllData($fields); $data['triggers'] = $this->getRuleTriggers(); - $data['actions'] = $this->getRuleActions(); + $data['actions'] = $this->getRuleActions(); return $data; } @@ -76,7 +76,7 @@ class StoreRequest extends FormRequest 'value' => $trigger['value'] ?? null, 'prohibited' => $this->convertBoolean((string) ($trigger['prohibited'] ?? 'false')), 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'true')), - 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')) + 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')), ]; } } @@ -94,7 +94,7 @@ class StoreRequest extends FormRequest 'type' => $action['type'], 'value' => $action['value'], 'active' => $this->convertBoolean((string) ($action['active'] ?? 'true')), - 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')) + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), ]; } } @@ -107,8 +107,8 @@ class StoreRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); // some triggers and actions require text: $contextTriggers = implode(',', $this->getTriggersWithContext()); @@ -120,17 +120,17 @@ class StoreRequest extends FormRequest 'rule_group_id' => 'belongsToUser:rule_groups|required_without:rule_group_title', 'rule_group_title' => 'nullable|min:1|max:255|required_without:rule_group_id|belongsToUser:rule_groups,title', 'trigger' => 'required|in:store-journal,update-journal,manual-activation', - 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), - 'triggers.*.value' => 'required_if:actions.*.type,' . $contextTriggers . '|min:1|ruleTriggerValue|max:1024', + 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), + 'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024', 'triggers.*.stop_processing' => [new IsBoolean()], 'triggers.*.active' => [new IsBoolean()], - 'actions.*.type' => 'required|in:' . implode(',', $validActions), + 'actions.*.type' => 'required|in:'.implode(',', $validActions), 'actions.*.value' => [sprintf('required_if:actions.*.type,%s', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], 'actions.*.stop_processing' => [new IsBoolean()], 'actions.*.active' => [new IsBoolean()], 'strict' => [new IsBoolean()], 'stop_processing' => [new IsBoolean()], - 'active' => [new IsBoolean()] + 'active' => [new IsBoolean()], ]; } @@ -181,10 +181,10 @@ class StoreRequest extends FormRequest */ protected function atLeastOneActiveTrigger(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); /** @var null|array|int|string $triggers */ - $triggers = $data['triggers'] ?? []; + $triggers = $data['triggers'] ?? []; // need at least one trigger if (!is_countable($triggers) || 0 === count($triggers)) { return; @@ -210,10 +210,10 @@ class StoreRequest extends FormRequest */ protected function atLeastOneActiveAction(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); /** @var null|array|int|string $actions */ - $actions = $data['actions'] ?? []; + $actions = $data['actions'] ?? []; // need at least one trigger if (!is_countable($actions) || 0 === count($actions)) { return; diff --git a/app/Api/V1/Requests/Models/Rule/TestRequest.php b/app/Api/V1/Requests/Models/Rule/TestRequest.php index b0c8e7951b..efc60b79fa 100644 --- a/app/Api/V1/Requests/Models/Rule/TestRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TestRequest.php @@ -47,7 +47,7 @@ class TestRequest extends FormRequest return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page'); } - private function getDate(string $field): null|Carbon + private function getDate(string $field): ?Carbon { $value = $this->query($field); if (is_array($value)) { @@ -69,7 +69,7 @@ class TestRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts' + 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts', ]; } } diff --git a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php index 42639af758..44951621e2 100644 --- a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php @@ -42,7 +42,7 @@ class TriggerRequest extends FormRequest return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): null|Carbon + private function getDate(string $field): ?Carbon { $value = $this->query($field); if (is_array($value)) { @@ -64,7 +64,7 @@ class TriggerRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts' + 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts', ]; } } diff --git a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php index 20b90e5146..cec238f65e 100644 --- a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php @@ -48,7 +48,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'stringWithNewlines'], 'rule_group_id' => ['rule_group_id', 'convertInteger'], @@ -56,7 +56,7 @@ class UpdateRequest extends FormRequest 'strict' => ['strict', 'boolean'], 'stop_processing' => ['stop_processing', 'boolean'], 'active' => ['active', 'boolean'], - 'order' => ['order', 'convertInteger'] + 'order' => ['order', 'convertInteger'], ]; $return = $this->getAllData($fields); @@ -72,7 +72,7 @@ class UpdateRequest extends FormRequest return $return; } - private function getRuleTriggers(): null|array + private function getRuleTriggers(): ?array { if (!$this->has('triggers')) { return null; @@ -84,12 +84,12 @@ class UpdateRequest extends FormRequest $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; $prohibited = array_key_exists('prohibited', $trigger) ? $trigger['prohibited'] : false; $stopProcessing = array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false; - $return[] = [ + $return[] = [ 'type' => $trigger['type'], 'value' => $trigger['value'], 'prohibited' => $prohibited, 'active' => $active, - 'stop_processing' => $stopProcessing + 'stop_processing' => $stopProcessing, ]; } } @@ -97,7 +97,7 @@ class UpdateRequest extends FormRequest return $return; } - private function getRuleActions(): null|array + private function getRuleActions(): ?array { if (!$this->has('actions')) { return null; @@ -110,7 +110,7 @@ class UpdateRequest extends FormRequest 'type' => $action['type'], 'value' => $action['value'], 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')) + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), ]; } } @@ -123,11 +123,11 @@ class UpdateRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); /** @var Rule $rule */ - $rule = $this->route()->parameter('rule'); + $rule = $this->route()->parameter('rule'); // some triggers and actions require text: $contextTriggers = implode(',', $this->getTriggersWithContext()); @@ -139,18 +139,18 @@ class UpdateRequest extends FormRequest 'rule_group_id' => 'belongsToUser:rule_groups', 'rule_group_title' => 'nullable|min:1|max:255|belongsToUser:rule_groups,title', 'trigger' => 'in:store-journal,update-journal.manual-activation', - 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), - 'triggers.*.value' => 'required_if:actions.*.type,' . $contextTriggers . '|min:1|ruleTriggerValue|max:1024', + 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), + 'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024', 'triggers.*.stop_processing' => [new IsBoolean()], 'triggers.*.active' => [new IsBoolean()], - 'actions.*.type' => 'required|in:' . implode(',', $validActions), + 'actions.*.type' => 'required|in:'.implode(',', $validActions), 'actions.*.value' => [sprintf('required_if:actions.*.type,%s', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], 'actions.*.stop_processing' => [new IsBoolean()], 'actions.*.active' => [new IsBoolean()], 'strict' => [new IsBoolean()], 'stop_processing' => [new IsBoolean()], 'active' => [new IsBoolean()], - 'order' => 'numeric|min:1|max:2048' + 'order' => 'numeric|min:1|max:2048', ]; } diff --git a/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php b/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php index 81d47e3b55..f38be5a7e2 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php @@ -55,7 +55,7 @@ class StoreRequest extends FormRequest 'title' => $this->convertString('title'), 'description' => $this->convertString('description'), 'active' => $active, - 'order' => $order + 'order' => $order, ]; } @@ -67,7 +67,7 @@ class StoreRequest extends FormRequest return [ 'title' => 'required|min:1|max:100|uniqueObjectForUser:rule_groups,title', 'description' => 'min:1|max:32768|nullable', - 'active' => [new IsBoolean()] + 'active' => [new IsBoolean()], ]; } } diff --git a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php index 1a181f8497..aeee9b9297 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php @@ -42,7 +42,7 @@ class TestRequest extends FormRequest return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): null|Carbon + private function getDate(string $field): ?Carbon { $value = $this->query($field); if (is_array($value)) { @@ -64,7 +64,7 @@ class TestRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts' + 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts', ]; } } diff --git a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php index 78c4bf9bff..09b24e9071 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php @@ -42,7 +42,7 @@ class TriggerRequest extends FormRequest return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): null|Carbon + private function getDate(string $field): ?Carbon { $value = $this->query($field); if (is_array($value)) { diff --git a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php index 25f58bac70..d2cbae0cab 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php @@ -48,7 +48,7 @@ class UpdateRequest extends FormRequest 'title' => ['title', 'convertString'], 'description' => ['description', 'stringWithNewlines'], 'active' => ['active', 'boolean'], - 'order' => ['order', 'convertInteger'] + 'order' => ['order', 'convertInteger'], ]; return $this->getAllData($fields); @@ -63,9 +63,9 @@ class UpdateRequest extends FormRequest $ruleGroup = $this->route()->parameter('ruleGroup'); return [ - 'title' => 'min:1|max:100|uniqueObjectForUser:rule_groups,title,' . $ruleGroup->id, + 'title' => 'min:1|max:100|uniqueObjectForUser:rule_groups,title,'.$ruleGroup->id, 'description' => 'min:1|max:32768|nullable', - 'active' => [new IsBoolean()] + 'active' => [new IsBoolean()], ]; } } diff --git a/app/Api/V1/Requests/Models/Tag/StoreRequest.php b/app/Api/V1/Requests/Models/Tag/StoreRequest.php index ac35803c0e..aeb51632bd 100644 --- a/app/Api/V1/Requests/Models/Tag/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Tag/StoreRequest.php @@ -48,7 +48,7 @@ class StoreRequest extends FormRequest 'tag' => $this->convertString('tag'), 'date' => $this->getCarbonDate('date'), 'description' => $this->convertString('description'), - 'has_location' => true + 'has_location' => true, ]; return $this->appendLocationData($data, null); @@ -62,7 +62,7 @@ class StoreRequest extends FormRequest $rules = [ 'tag' => 'required|min:1|uniqueObjectForUser:tags,tag|max:1024', 'description' => 'min:1|nullable|max:32768', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Tag/UpdateRequest.php b/app/Api/V1/Requests/Models/Tag/UpdateRequest.php index d9f2036e87..713e6964f4 100644 --- a/app/Api/V1/Requests/Models/Tag/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Tag/UpdateRequest.php @@ -60,9 +60,9 @@ class UpdateRequest extends FormRequest /** @var Tag $tag */ $tag = $this->route()->parameter('tagOrId'); $rules = [ - 'tag' => 'min:1|max:1024|uniqueObjectForUser:tags,tag,' . $tag->id, + 'tag' => 'min:1|max:1024|uniqueObjectForUser:tags,tag,'.$tag->id, 'description' => 'min:1|nullable|max:32768', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php index 19f924ef0f..62666c1d99 100644 --- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php @@ -66,7 +66,7 @@ class StoreRequest extends FormRequest 'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'), 'apply_rules' => $this->boolean('apply_rules', true), 'fire_webhooks' => $this->boolean('fire_webhooks', true), - 'transactions' => $this->getTransactionData() + 'transactions' => $this->getTransactionData(), ]; // TODO include location and ability to process it. @@ -83,89 +83,89 @@ class StoreRequest extends FormRequest * @var array $transaction */ foreach ($this->get('transactions') as $transaction) { - $object = new NullArrayObject($transaction); + $object = new NullArrayObject($transaction); $return[] = [ - 'type' => $this->clearString($object['type']), - 'date' => $this->dateFromValue($object['date']), - 'order' => $this->integerFromValue((string) $object['order']), + 'type' => $this->clearString($object['type']), + 'date' => $this->dateFromValue($object['date']), + 'order' => $this->integerFromValue((string) $object['order']), - 'currency_id' => $this->integerFromValue((string) $object['currency_id']), - 'currency_code' => $this->clearString((string) $object['currency_code']), + 'currency_id' => $this->integerFromValue((string) $object['currency_id']), + 'currency_code' => $this->clearString((string) $object['currency_code']), // location - 'latitude' => $this->floatFromValue((string) $object['latitude']), - 'longitude' => $this->floatFromValue((string) $object['longitude']), - 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']), + 'latitude' => $this->floatFromValue((string) $object['latitude']), + 'longitude' => $this->floatFromValue((string) $object['longitude']), + 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']), // foreign currency info: 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']), // amount and foreign amount. Cannot be 0. - 'amount' => $this->clearString((string) $object['amount']), - 'foreign_amount' => $this->clearString((string) $object['foreign_amount']), + 'amount' => $this->clearString((string) $object['amount']), + 'foreign_amount' => $this->clearString((string) $object['foreign_amount']), // description. - 'description' => $this->clearString($object['description']), + 'description' => $this->clearString($object['description']), // source of transaction. If everything is null, assume cash account. - 'source_id' => $this->integerFromValue((string) $object['source_id']), - 'source_name' => $this->clearString((string) $object['source_name']), - 'source_iban' => $this->clearIban((string) $object['source_iban']), - 'source_number' => $this->clearString((string) $object['source_number']), - 'source_bic' => $this->clearString((string) $object['source_bic']), + 'source_id' => $this->integerFromValue((string) $object['source_id']), + 'source_name' => $this->clearString((string) $object['source_name']), + 'source_iban' => $this->clearIban((string) $object['source_iban']), + 'source_number' => $this->clearString((string) $object['source_number']), + 'source_bic' => $this->clearString((string) $object['source_bic']), // destination of transaction. If everything is null, assume cash account. - 'destination_id' => $this->integerFromValue((string) $object['destination_id']), - 'destination_name' => $this->clearString((string) $object['destination_name']), - 'destination_iban' => $this->clearIban((string) $object['destination_iban']), - 'destination_number' => $this->clearString((string) $object['destination_number']), - 'destination_bic' => $this->clearString((string) $object['destination_bic']), + 'destination_id' => $this->integerFromValue((string) $object['destination_id']), + 'destination_name' => $this->clearString((string) $object['destination_name']), + 'destination_iban' => $this->clearIban((string) $object['destination_iban']), + 'destination_number' => $this->clearString((string) $object['destination_number']), + 'destination_bic' => $this->clearString((string) $object['destination_bic']), // budget info - 'budget_id' => $this->integerFromValue((string) $object['budget_id']), - 'budget_name' => $this->clearString((string) $object['budget_name']), + 'budget_id' => $this->integerFromValue((string) $object['budget_id']), + 'budget_name' => $this->clearString((string) $object['budget_name']), // category info - 'category_id' => $this->integerFromValue((string) $object['category_id']), - 'category_name' => $this->clearString((string) $object['category_name']), + 'category_id' => $this->integerFromValue((string) $object['category_id']), + 'category_name' => $this->clearString((string) $object['category_name']), // journal bill reference. Optional. Will only work for withdrawals - 'bill_id' => $this->integerFromValue((string) $object['bill_id']), - 'bill_name' => $this->clearString((string) $object['bill_name']), + 'bill_id' => $this->integerFromValue((string) $object['bill_id']), + 'bill_name' => $this->clearString((string) $object['bill_name']), // piggy bank reference. Optional. Will only work for transfers - 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), - 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']), + 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), + 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']), // some other interesting properties - 'reconciled' => $this->convertBoolean((string) $object['reconciled']), - 'notes' => $this->clearStringKeepNewlines((string) $object['notes']), - 'tags' => $this->arrayFromValue($object['tags']), + 'reconciled' => $this->convertBoolean((string) $object['reconciled']), + 'notes' => $this->clearStringKeepNewlines((string) $object['notes']), + 'tags' => $this->arrayFromValue($object['tags']), // all custom fields: - 'internal_reference' => $this->clearString((string) $object['internal_reference']), - 'external_id' => $this->clearString((string) $object['external_id']), - 'original_source' => sprintf('ff3-v%s', config('firefly.version')), - 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), - 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), - 'external_url' => $this->clearString((string) $object['external_url']), + 'internal_reference' => $this->clearString((string) $object['internal_reference']), + 'external_id' => $this->clearString((string) $object['external_id']), + 'original_source' => sprintf('ff3-v%s', config('firefly.version')), + 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), + 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), + 'external_url' => $this->clearString((string) $object['external_url']), - 'sepa_cc' => $this->clearString((string) $object['sepa_cc']), - 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), - 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), - 'sepa_db' => $this->clearString((string) $object['sepa_db']), - 'sepa_country' => $this->clearString((string) $object['sepa_country']), - 'sepa_ep' => $this->clearString((string) $object['sepa_ep']), - 'sepa_ci' => $this->clearString((string) $object['sepa_ci']), - 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), + 'sepa_cc' => $this->clearString((string) $object['sepa_cc']), + 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), + 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), + 'sepa_db' => $this->clearString((string) $object['sepa_db']), + 'sepa_country' => $this->clearString((string) $object['sepa_country']), + 'sepa_ep' => $this->clearString((string) $object['sepa_ep']), + 'sepa_ci' => $this->clearString((string) $object['sepa_ci']), + 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), // custom date fields. Must be Carbon objects. Presence is optional. - 'interest_date' => $this->dateFromValue($object['interest_date']), - 'book_date' => $this->dateFromValue($object['book_date']), - 'process_date' => $this->dateFromValue($object['process_date']), - 'due_date' => $this->dateFromValue($object['due_date']), - 'payment_date' => $this->dateFromValue($object['payment_date']), - 'invoice_date' => $this->dateFromValue($object['invoice_date']) + 'interest_date' => $this->dateFromValue($object['interest_date']), + 'book_date' => $this->dateFromValue($object['book_date']), + 'process_date' => $this->dateFromValue($object['process_date']), + 'due_date' => $this->dateFromValue($object['due_date']), + 'payment_date' => $this->dateFromValue($object['payment_date']), + 'invoice_date' => $this->dateFromValue($object['invoice_date']), ]; } @@ -183,20 +183,20 @@ class StoreRequest extends FormRequest return [ // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'error_if_duplicate_hash' => [new IsBoolean()], - 'fire_webhooks' => [new IsBoolean()], - 'apply_rules' => [new IsBoolean()], + 'group_title' => 'min:1|max:1000|nullable', + 'error_if_duplicate_hash' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()], + 'apply_rules' => [new IsBoolean()], // location rules - 'transactions.*.latitude' => $locationRules['latitude'], - 'transactions.*.longitude' => $locationRules['longitude'], - 'transactions.*.zoom_level' => $locationRules['zoom_level'], + 'transactions.*.latitude' => $locationRules['latitude'], + 'transactions.*.longitude' => $locationRules['longitude'], + 'transactions.*.zoom_level' => $locationRules['zoom_level'], // transaction rules (in array for splits): - 'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => ['required', new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', + 'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation', + 'transactions.*.date' => ['required', new IsDateOrTime()], + 'transactions.*.order' => 'numeric|min:0', // currency info 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', @@ -205,66 +205,66 @@ class StoreRequest extends FormRequest 'transactions.*.foreign_currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', // amount - 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], + 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], + 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], // description - 'transactions.*.description' => 'nullable|min:1|max:1000', + 'transactions.*.description' => 'nullable|min:1|max:1000', // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.source_name' => 'min:1|max:255|nullable', - 'transactions.*.source_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.source_number' => 'min:1|max:255|nullable', - 'transactions.*.source_bic' => 'min:1|max:255|nullable|bic', + 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.source_name' => 'min:1|max:255|nullable', + 'transactions.*.source_iban' => 'min:1|max:255|nullable|iban', + 'transactions.*.source_number' => 'min:1|max:255|nullable', + 'transactions.*.source_bic' => 'min:1|max:255|nullable|bic', // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', - 'transactions.*.destination_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.destination_number' => 'min:1|max:255|nullable', - 'transactions.*.destination_bic' => 'min:1|max:255|nullable|bic', + 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.destination_name' => 'min:1|max:255|nullable', + 'transactions.*.destination_iban' => 'min:1|max:255|nullable|iban', + 'transactions.*.destination_number' => 'min:1|max:255|nullable', + 'transactions.*.destination_bic' => 'min:1|max:255|nullable|bic', // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], + 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255', - 'transactions.*.tags.*' => 'min:0|max:255', + 'transactions.*.reconciled' => [new IsBoolean()], + 'transactions.*.notes' => 'min:1|max:32768|nullable', + 'transactions.*.tags' => 'min:0|max:255', + 'transactions.*.tags.*' => 'min:0|max:255', // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), + 'transactions.*.internal_reference' => 'min:1|max:255|nullable', + 'transactions.*.external_id' => 'min:1|max:255|nullable', + 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', + 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', + 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_db' => 'min:1|max:255|nullable', + 'transactions.*.sepa_country' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', + 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable' + 'transactions.*.interest_date' => 'date|nullable', + 'transactions.*.book_date' => 'date|nullable', + 'transactions.*.process_date' => 'date|nullable', + 'transactions.*.due_date' => 'date|nullable', + 'transactions.*.payment_date' => 'date|nullable', + 'transactions.*.invoice_date' => 'date|nullable', ]; } diff --git a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php index 393630b924..9e34449ab9 100644 --- a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php @@ -66,7 +66,7 @@ class UpdateRequest extends FormRequest public function getAll(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $this->integerFields = [ + $this->integerFields = [ 'order', 'currency_id', 'foreign_currency_id', @@ -76,13 +76,13 @@ class UpdateRequest extends FormRequest 'budget_id', 'category_id', 'bill_id', - 'recurrence_id' + 'recurrence_id', ]; - $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; + $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $this->textareaFields = ['notes']; // not really floats, for validation. - $this->floatFields = ['amount', 'foreign_amount']; - $this->stringFields = [ + $this->floatFields = ['amount', 'foreign_amount']; + $this->stringFields = [ 'type', 'currency_code', 'foreign_currency_code', @@ -109,11 +109,11 @@ class UpdateRequest extends FormRequest 'sepa_ep', 'sepa_ci', 'sepa_batch_id', - 'external_url' + 'external_url', ]; - $this->booleanFields = ['reconciled']; - $this->arrayFields = ['tags']; - $data = []; + $this->booleanFields = ['reconciled']; + $this->arrayFields = ['tags']; + $data = []; if ($this->has('transactions')) { $data['transactions'] = $this->getTransactionData(); } @@ -138,7 +138,7 @@ class UpdateRequest extends FormRequest private function getTransactionData(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; + $return = []; /** @var null|array $transactions */ $transactions = $this->get('transactions'); @@ -153,14 +153,14 @@ class UpdateRequest extends FormRequest throw new FireflyException('Invalid data submitted: transaction is not array.'); } // default response is to update nothing in the transaction: - $current = []; - $current = $this->getIntegerData($current, $transaction); - $current = $this->getStringData($current, $transaction); - $current = $this->getNlStringData($current, $transaction); - $current = $this->getDateData($current, $transaction); - $current = $this->getBooleanData($current, $transaction); - $current = $this->getArrayData($current, $transaction); - $current = $this->getFloatData($current, $transaction); + $current = []; + $current = $this->getIntegerData($current, $transaction); + $current = $this->getStringData($current, $transaction); + $current = $this->getNlStringData($current, $transaction); + $current = $this->getDateData($current, $transaction); + $current = $this->getBooleanData($current, $transaction); + $current = $this->getArrayData($current, $transaction); + $current = $this->getFloatData($current, $transaction); $return[] = $current; } @@ -292,76 +292,76 @@ class UpdateRequest extends FormRequest return [ // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'apply_rules' => [new IsBoolean()], + 'group_title' => 'min:1|max:1000|nullable', + 'apply_rules' => [new IsBoolean()], // transaction rules (in array for splits): - 'transactions.*.type' => 'in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => [new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', + 'transactions.*.type' => 'in:withdrawal,deposit,transfer,opening-balance,reconciliation', + 'transactions.*.date' => [new IsDateOrTime()], + 'transactions.*.order' => 'numeric|min:0', // group id: 'transactions.*.transaction_journal_id' => ['nullable', 'numeric', new BelongsUser()], // currency info - 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', - 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', - 'transactions.*.foreign_currency_id' => 'nullable|numeric|exists:transaction_currencies,id', - 'transactions.*.foreign_currency_code' => 'nullable|min:3|max:51|exists:transaction_currencies,code', + 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', + 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', + 'transactions.*.foreign_currency_id' => 'nullable|numeric|exists:transaction_currencies,id', + 'transactions.*.foreign_currency_code' => 'nullable|min:3|max:51|exists:transaction_currencies,code', // amount - 'transactions.*.amount' => [new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], + 'transactions.*.amount' => [new IsValidPositiveAmount()], + 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], // description - 'transactions.*.description' => 'nullable|min:1|max:1000', + 'transactions.*.description' => 'nullable|min:1|max:1000', // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.source_name' => 'min:1|max:255|nullable', + 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.source_name' => 'min:1|max:255|nullable', // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', + 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.destination_name' => 'min:1|max:255|nullable', // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser(), 'nullable'], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser(), 'nullable'], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], + 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255|nullable', - 'transactions.*.tags.*' => 'min:0|max:255', + 'transactions.*.reconciled' => [new IsBoolean()], + 'transactions.*.notes' => 'min:1|max:32768|nullable', + 'transactions.*.tags' => 'min:0|max:255|nullable', + 'transactions.*.tags.*' => 'min:0|max:255', // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), + 'transactions.*.internal_reference' => 'min:1|max:255|nullable', + 'transactions.*.external_id' => 'min:1|max:255|nullable', + 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', + 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', + 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_db' => 'min:1|max:255|nullable', + 'transactions.*.sepa_country' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', + 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable' + 'transactions.*.interest_date' => 'date|nullable', + 'transactions.*.book_date' => 'date|nullable', + 'transactions.*.process_date' => 'date|nullable', + 'transactions.*.due_date' => 'date|nullable', + 'transactions.*.payment_date' => 'date|nullable', + 'transactions.*.invoice_date' => 'date|nullable', ]; } diff --git a/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php index b07ffcba95..d3aa5df6dc 100644 --- a/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php @@ -57,7 +57,7 @@ class StoreRequest extends FormRequest 'symbol' => $this->convertString('symbol'), 'decimal_places' => $this->convertInteger('decimal_places'), 'default' => $default, - 'enabled' => $enabled + 'enabled' => $enabled, ]; } @@ -72,7 +72,7 @@ class StoreRequest extends FormRequest 'symbol' => 'required|min:1|max:32|unique:transaction_currencies,symbol', 'decimal_places' => 'numeric|min:0|max:12', 'enabled' => [new IsBoolean()], - 'default' => [new IsBoolean()] + 'default' => [new IsBoolean()], ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php index 633e1f409e..e4687c0edb 100644 --- a/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php @@ -50,7 +50,7 @@ class UpdateRequest extends FormRequest 'symbol' => ['symbol', 'convertString'], 'decimal_places' => ['decimal_places', 'convertInteger'], 'default' => ['default', 'boolean'], - 'enabled' => ['enabled', 'boolean'] + 'enabled' => ['enabled', 'boolean'], ]; return $this->getAllData($fields); @@ -70,7 +70,7 @@ class UpdateRequest extends FormRequest 'symbol' => sprintf('min:1|max:32|unique:transaction_currencies,symbol,%d', $currency->id), 'decimal_places' => 'numeric|min:0|max:12', 'enabled' => [new IsBoolean()], - 'default' => [new IsBoolean()] + 'default' => [new IsBoolean()], ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php index 93b0e09555..29767ec01d 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php @@ -51,7 +51,7 @@ class StoreRequest extends FormRequest 'link_type_name' => $this->convertString('link_type_name'), 'inward_id' => $this->convertInteger('inward_id'), 'outward_id' => $this->convertInteger('outward_id'), - 'notes' => $this->stringWithNewlines('notes') + 'notes' => $this->stringWithNewlines('notes'), ]; } @@ -65,7 +65,7 @@ class StoreRequest extends FormRequest 'link_type_name' => 'exists:link_types,name|required_without:link_type_id', 'inward_id' => 'required|belongsToUser:transaction_journals,id|different:outward_id', 'outward_id' => 'required|belongsToUser:transaction_journals,id|different:inward_id', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } @@ -85,21 +85,21 @@ class StoreRequest extends FormRequest private function validateExistingLink(Validator $validator): void { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var LinkTypeRepositoryInterface $repository */ - $repository = app(LinkTypeRepositoryInterface::class); + $repository = app(LinkTypeRepositoryInterface::class); $repository->setUser($user); /** @var JournalRepositoryInterface $journalRepos */ $journalRepos = app(JournalRepositoryInterface::class); $journalRepos->setUser($user); - $data = $validator->getData(); - $inwardId = (int) ($data['inward_id'] ?? 0); - $outwardId = (int) ($data['outward_id'] ?? 0); - $inward = $journalRepos->find($inwardId); - $outward = $journalRepos->find($outwardId); + $data = $validator->getData(); + $inwardId = (int) ($data['inward_id'] ?? 0); + $outwardId = (int) ($data['outward_id'] ?? 0); + $inward = $journalRepos->find($inwardId); + $outward = $journalRepos->find($outwardId); if (null === $inward) { $validator->errors()->add('inward_id', 'Invalid inward ID.'); diff --git a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php index 4472a72546..9750a7377a 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php @@ -51,7 +51,7 @@ class UpdateRequest extends FormRequest 'link_type_name' => $this->convertString('link_type_name'), 'inward_id' => $this->convertInteger('inward_id'), 'outward_id' => $this->convertInteger('outward_id'), - 'notes' => $this->stringWithNewlines('notes') + 'notes' => $this->stringWithNewlines('notes'), ]; } @@ -65,7 +65,7 @@ class UpdateRequest extends FormRequest 'link_type_name' => 'exists:link_types,name', 'inward_id' => 'belongsToUser:transaction_journals,id|different:outward_id', 'outward_id' => 'belongsToUser:transaction_journals,id|different:inward_id', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } @@ -85,21 +85,21 @@ class UpdateRequest extends FormRequest private function validateUpdate(Validator $validator): void { /** @var TransactionJournalLink $existing */ - $existing = $this->route()->parameter('journalLink'); - $data = $validator->getData(); + $existing = $this->route()->parameter('journalLink'); + $data = $validator->getData(); /** @var LinkTypeRepositoryInterface $repository */ - $repository = app(LinkTypeRepositoryInterface::class); + $repository = app(LinkTypeRepositoryInterface::class); $repository->setUser(auth()->user()); /** @var JournalRepositoryInterface $journalRepos */ $journalRepos = app(JournalRepositoryInterface::class); $journalRepos->setUser(auth()->user()); - $inwardId = $data['inward_id'] ?? $existing->source_id; - $outwardId = $data['outward_id'] ?? $existing->destination_id; - $inward = $journalRepos->find((int) $inwardId); - $outward = $journalRepos->find((int) $outwardId); + $inwardId = $data['inward_id'] ?? $existing->source_id; + $outwardId = $data['outward_id'] ?? $existing->destination_id; + $inward = $journalRepos->find((int) $inwardId); + $outward = $journalRepos->find((int) $outwardId); if (null === $inward) { $inward = $existing->source; } @@ -111,7 +111,7 @@ class UpdateRequest extends FormRequest $validator->errors()->add('outward_id', 'Inward ID must be different from outward ID.'); } - $inDB = $repository->findSpecificLink($existing->linkType, $inward, $outward); + $inDB = $repository->findSpecificLink($existing->linkType, $inward, $outward); if (null === $inDB) { return; } diff --git a/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php index e0ef99a840..01053640b9 100644 --- a/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php @@ -52,7 +52,7 @@ class StoreRequest extends FormRequest return [ 'name' => 'required|unique:link_types,name|min:1|max:1024', 'outward' => 'required|unique:link_types,outward|min:1|different:inward|max:1024', - 'inward' => 'required|unique:link_types,inward|min:1|different:outward|max:1024' + 'inward' => 'required|unique:link_types,inward|min:1|different:outward|max:1024', ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php index 292bba6898..f8ccd510ad 100644 --- a/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php @@ -57,7 +57,7 @@ class UpdateRequest extends FormRequest return [ 'name' => [Rule::unique('link_types', 'name')->ignore($linkType->id), 'min:1', 'max:1024'], 'outward' => ['different:inward', Rule::unique('link_types', 'outward')->ignore($linkType->id), 'min:1', 'max:1024'], - 'inward' => ['different:outward', Rule::unique('link_types', 'inward')->ignore($linkType->id), 'min:1', 'max:1024'] + 'inward' => ['different:outward', Rule::unique('link_types', 'inward')->ignore($linkType->id), 'min:1', 'max:1024'], ]; } } diff --git a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php index e889f2b96d..20c75a9342 100644 --- a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php @@ -41,7 +41,7 @@ class UpdateRequest extends FormRequest $fields = [ 'title' => ['title', 'convertString'], 'primary_currency_id' => ['primary_currency_id', 'convertInteger'], - 'primary_currency_code' => ['primary_currency_code', 'convertString'] + 'primary_currency_code' => ['primary_currency_code', 'convertString'], ]; return $this->getAllData($fields); @@ -55,7 +55,7 @@ class UpdateRequest extends FormRequest return [ 'title' => ['required', 'min:1', 'max:255'], 'primary_currency_id' => 'exists:transaction_currencies,id', - 'primary_currency_code' => 'exists:transaction_currencies,code' + 'primary_currency_code' => 'exists:transaction_currencies,code', ]; } } diff --git a/app/Api/V1/Requests/Models/Webhook/CreateRequest.php b/app/Api/V1/Requests/Models/Webhook/CreateRequest.php index 6b38178e8b..9de2224782 100644 --- a/app/Api/V1/Requests/Models/Webhook/CreateRequest.php +++ b/app/Api/V1/Requests/Models/Webhook/CreateRequest.php @@ -44,18 +44,18 @@ class CreateRequest extends FormRequest public function getData(): array { - $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; - $triggers = $this->get('triggers', []); - $responses = $this->get('responses', []); - $deliveries = $this->get('deliveries', []); + $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; + $triggers = $this->get('triggers', []); + $responses = $this->get('responses', []); + $deliveries = $this->get('deliveries', []); if (in_array(0, [count($triggers), count($responses), count($deliveries)], true)) { throw new FireflyException('Unexpectedly got no responses, triggers or deliveries.'); } - $return = $this->getAllData($fields); - $return['triggers'] = $triggers; - $return['responses'] = $responses; + $return = $this->getAllData($fields); + $return['triggers'] = $triggers; + $return['responses'] = $responses; $return['deliveries'] = $deliveries; return $return; @@ -83,7 +83,7 @@ class CreateRequest extends FormRequest 'delivery' => 'prohibited', 'deliveries' => 'required|array|min:1|max:1', 'deliveries.*' => sprintf('required|in:%s', $deliveries), - 'url' => ['required', sprintf('url:%s', $validProtocols)] + 'url' => ['required', sprintf('url:%s', $validProtocols)], ]; } } diff --git a/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php b/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php index ec57d9e283..20e56c61ed 100644 --- a/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php @@ -44,19 +44,19 @@ class UpdateRequest extends FormRequest public function getData(): array { - $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; + $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; - $triggers = $this->get('triggers', []); - $responses = $this->get('responses', []); - $deliveries = $this->get('deliveries', []); + $triggers = $this->get('triggers', []); + $responses = $this->get('responses', []); + $deliveries = $this->get('deliveries', []); if (in_array(0, [count($triggers), count($responses), count($deliveries)], true)) { throw new FireflyException('Unexpectedly got no responses, triggers or deliveries.'); } - $return = $this->getAllData($fields); - $return['triggers'] = $triggers; - $return['responses'] = $responses; + $return = $this->getAllData($fields); + $return['triggers'] = $triggers; + $return['responses'] = $responses; $return['deliveries'] = $deliveries; return $return; @@ -73,10 +73,10 @@ class UpdateRequest extends FormRequest $validProtocols = FireflyConfig::get('valid_url_protocols', config('firefly.valid_url_protocols'))->data; /** @var Webhook $webhook */ - $webhook = $this->route()->parameter('webhook'); + $webhook = $this->route()->parameter('webhook'); - return ['title' => sprintf('min:1|max:255|uniqueObjectForUser:webhooks,title,%d', $webhook->id), 'active' => [new IsBoolean()], + return ['title' => sprintf('min:1|max:255|uniqueObjectForUser:webhooks,title,%d', $webhook->id), 'active' => [new IsBoolean()], 'trigger' => 'prohibited', 'triggers' => 'required|array|min:1|max:10', 'triggers.*' => sprintf('required|in:%s', $triggers), 'response' => 'prohibited', 'responses' => 'required|array|min:1|max:1', 'responses.*' => sprintf('required|in:%s', $responses), 'delivery' => 'prohibited', 'deliveries' => 'required|array|min:1|max:1', 'deliveries.*' => sprintf('required|in:%s', $deliveries), - 'url' => [sprintf('url:%s', $validProtocols), sprintf('uniqueExistingWebhook:%d', $webhook->id)]]; + 'url' => [sprintf('url:%s', $validProtocols), sprintf('uniqueExistingWebhook:%d', $webhook->id)]]; } } diff --git a/app/Api/V1/Requests/PaginationRequest.php b/app/Api/V1/Requests/PaginationRequest.php index a8182083eb..3b14e364ab 100644 --- a/app/Api/V1/Requests/PaginationRequest.php +++ b/app/Api/V1/Requests/PaginationRequest.php @@ -32,7 +32,7 @@ use RuntimeException; class PaginationRequest extends ApiRequest { - private null|string $sortClass = null; + private ?string $sortClass = null; #[Override] public function handleConfig(array $config): void @@ -51,7 +51,7 @@ class PaginationRequest extends ApiRequest return [ 'sort' => ['nullable', new IsValidSortInstruction((string) $this->sortClass)], 'limit' => 'numeric|min:1|max:131337', - 'page' => 'numeric|min:1|max:131337' + 'page' => 'numeric|min:1|max:131337', ]; } @@ -62,7 +62,7 @@ class PaginationRequest extends ApiRequest return; } - $limit = $this->convertInteger('limit'); + $limit = $this->convertInteger('limit'); if (0 === $limit) { // get default for user: /** @var User $user */ diff --git a/app/Api/V1/Requests/Search/TransactionSearchRequest.php b/app/Api/V1/Requests/Search/TransactionSearchRequest.php index 79d9b9a18b..a7222c5095 100644 --- a/app/Api/V1/Requests/Search/TransactionSearchRequest.php +++ b/app/Api/V1/Requests/Search/TransactionSearchRequest.php @@ -36,7 +36,7 @@ class TransactionSearchRequest extends AggregateFormRequest { return [ [PaginationRequest::class, 'sort_class' => TransactionJournal::class], - SearchQueryRequest::class + SearchQueryRequest::class, // [ObjectTypeApiRequest::class, 'object_type' => Account::class], ]; } diff --git a/app/Api/V1/Requests/System/UpdateRequest.php b/app/Api/V1/Requests/System/UpdateRequest.php index aa37e43ba9..0482758a5f 100644 --- a/app/Api/V1/Requests/System/UpdateRequest.php +++ b/app/Api/V1/Requests/System/UpdateRequest.php @@ -44,7 +44,7 @@ class UpdateRequest extends FormRequest 'configuration.use_running_balance', 'configuration.enable_external_map', 'configuration.enable_external_rates', - 'configuration.allow_webhooks' + 'configuration.allow_webhooks', ]; private array $integers = ['configuration.permission_update_check', 'configuration.last_update_check']; diff --git a/app/Api/V1/Requests/System/UserStoreRequest.php b/app/Api/V1/Requests/System/UserStoreRequest.php index 9de9da9d89..9ca9409ec8 100644 --- a/app/Api/V1/Requests/System/UserStoreRequest.php +++ b/app/Api/V1/Requests/System/UserStoreRequest.php @@ -59,7 +59,7 @@ class UserStoreRequest extends FormRequest 'email' => $this->convertString('email'), 'blocked' => $blocked, 'blocked_code' => $this->convertString('blocked_code'), - 'role' => $this->convertString('role') + 'role' => $this->convertString('role'), ]; } @@ -72,7 +72,7 @@ class UserStoreRequest extends FormRequest 'email' => 'required|email|unique:users,email', 'blocked' => [new IsBoolean()], 'blocked_code' => 'in:email_changed', - 'role' => 'in:owner,demo' + 'role' => 'in:owner,demo', ]; } } diff --git a/app/Api/V1/Requests/System/UserUpdateRequest.php b/app/Api/V1/Requests/System/UserUpdateRequest.php index 6e186a113e..239f8e0484 100644 --- a/app/Api/V1/Requests/System/UserUpdateRequest.php +++ b/app/Api/V1/Requests/System/UserUpdateRequest.php @@ -62,7 +62,7 @@ class UserUpdateRequest extends FormRequest 'email' => $this->convertString('email'), 'blocked' => $blocked, 'blocked_code' => $this->convertString('blocked_code'), - 'role' => $this->convertString('role') + 'role' => $this->convertString('role'), ]; } @@ -78,7 +78,7 @@ class UserUpdateRequest extends FormRequest 'email' => sprintf('email|unique:users,email,%d', $user->id), 'blocked' => [new IsBoolean()], 'blocked_code' => 'in:email_changed', - 'role' => 'in:owner,demo,' + 'role' => 'in:owner,demo,', ]; } diff --git a/app/Casts/SeparateTimezoneCaster.php b/app/Casts/SeparateTimezoneCaster.php index 4c5a6cecd3..594303b64d 100644 --- a/app/Casts/SeparateTimezoneCaster.php +++ b/app/Casts/SeparateTimezoneCaster.php @@ -42,7 +42,7 @@ class SeparateTimezoneCaster implements CastsAttributes /** * @param array $attributes */ - public function get(Model $model, string $key, mixed $value, array $attributes): null|Carbon + public function get(Model $model, string $key, mixed $value, array $attributes): ?Carbon { if ('' === $value || null === $value) { return null; diff --git a/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php b/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php index 49b0fbd08e..e46b3197db 100644 --- a/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php +++ b/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php @@ -37,7 +37,7 @@ class ClearsEmptyForeignAmounts extends Command * * @var string */ - protected $signature = 'correction:clears-empty-foreign-amounts'; + protected $signature = 'correction:clears-empty-foreign-amounts'; /** * The console command description. diff --git a/app/Console/Commands/Correction/ConvertsDatesToUTC.php b/app/Console/Commands/Correction/ConvertsDatesToUTC.php index d54d78b236..742b0bd18d 100644 --- a/app/Console/Commands/Correction/ConvertsDatesToUTC.php +++ b/app/Console/Commands/Correction/ConvertsDatesToUTC.php @@ -91,9 +91,9 @@ class ConvertsDatesToUTC extends Command } $this->friendlyInfo(sprintf('Converting field "%s" of model "%s" to UTC.', $field, $shortModel)); $items->each(static function ($item) use ($field, $timezoneField): void { - $date = Carbon::parse($item->{$field}, $item->{$timezoneField}); // @phpstan-ignore-line + $date = Carbon::parse($item->{$field}, $item->{$timezoneField}); // @phpstan-ignore-line $date->setTimezone('UTC'); - $item->{$field} = $date->format('Y-m-d H:i:s'); // @phpstan-ignore-line + $item->{$field} = $date->format('Y-m-d H:i:s'); // @phpstan-ignore-line $item->{$timezoneField} = 'UTC'; // @phpstan-ignore-line $item->save(); }); diff --git a/app/Console/Commands/Correction/CorrectsAccountTypes.php b/app/Console/Commands/Correction/CorrectsAccountTypes.php index c37188290f..4366cc184b 100644 --- a/app/Console/Commands/Correction/CorrectsAccountTypes.php +++ b/app/Console/Commands/Correction/CorrectsAccountTypes.php @@ -58,11 +58,11 @@ class CorrectsAccountTypes extends Command public function handle(): int { $this->stupidLaravel(); - $this->factory = app(AccountFactory::class); + $this->factory = app(AccountFactory::class); $this->expected = config('firefly.source_dests'); - $expected = config('firefly.source_dests'); + $expected = config('firefly.source_dests'); - $query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') + $query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') ->leftJoin('transactions as source', static function (JoinClause $join): void { $join->on('transaction_journals.id', '=', 'source.transaction_journal_id')->where('source.amount', '<', 0); }) @@ -72,7 +72,8 @@ class CorrectsAccountTypes extends Command ->leftJoin('accounts as source_account', 'source.account_id', '=', 'source_account.id') ->leftJoin('accounts as destination_account', 'destination.account_id', '=', 'destination_account.id') ->leftJoin('account_types as source_account_type', 'source_account.account_type_id', '=', 'source_account_type.id') - ->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id'); + ->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id') + ; // list all valid combinations, those are allowed. So we select those which are broken. $query->where(static function (Builder $q) use ($expected): void { @@ -89,7 +90,7 @@ class CorrectsAccountTypes extends Command } }); - $resultSet = $query->get([ + $resultSet = $query->get([ 'transaction_journals.id', // 'transaction_type_id as type_id', 'transaction_types.type as journal_type', @@ -100,7 +101,7 @@ class CorrectsAccountTypes extends Command // 'destination.id as destination_transaction_id', // 'destination_account.id as destination_account_id', // 'destination_account_type.id as destination_account_type_id', - 'destination_account_type.type as destination_account_type' + 'destination_account_type.type as destination_account_type', ]); if ($resultSet->count() > 0) { $this->friendlyLine(sprintf('Found %d journals that need to be fixed.', $resultSet->count())); @@ -130,7 +131,7 @@ class CorrectsAccountTypes extends Command private function inspectJournal(TransactionJournal $journal): void { Log::debug(sprintf('Now inspecting journal #%d', $journal->id)); - $transactions = $journal->transactions()->count(); + $transactions = $journal->transactions()->count(); if (2 !== $transactions) { Log::debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions)); $this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions)); @@ -157,7 +158,7 @@ class CorrectsAccountTypes extends Command return; } - $expectedTypes = $this->expected[$type][$sourceAccountType]; + $expectedTypes = $this->expected[$type][$sourceAccountType]; if (!in_array($destAccountType, $expectedTypes, true)) { Log::debug(sprintf('[b] Going to fix journal #%d', $journal->id)); $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction); @@ -177,13 +178,13 @@ class CorrectsAccountTypes extends Command private function fixJournal(TransactionJournal $journal, string $transactionType, Transaction $source, Transaction $dest): void { Log::debug(sprintf('Going to fix journal #%d', $journal->id)); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->repository->setUser($journal->user); ++$this->count; // variables: - $sourceType = $source->account->accountType->type; - $destinationType = $dest->account->accountType->type; - $combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type); + $sourceType = $source->account->accountType->type; + $destinationType = $dest->account->accountType->type; + $combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type); Log::debug(sprintf('Combination is "%s"', $combination)); if ($this->shouldBeTransfer($transactionType, $sourceType, $destinationType)) { @@ -208,9 +209,9 @@ class CorrectsAccountTypes extends Command } // transaction has no valid source. - $validSources = array_keys($this->expected[$transactionType]); - $canCreateSource = $this->canCreateSource($validSources); - $hasValidSource = $this->hasValidAccountType($validSources, $sourceType); + $validSources = array_keys($this->expected[$transactionType]); + $canCreateSource = $this->canCreateSource($validSources); + $hasValidSource = $this->hasValidAccountType($validSources, $sourceType); if (!$hasValidSource && $canCreateSource) { $this->giveNewRevenue($journal, $source); @@ -267,20 +268,18 @@ class CorrectsAccountTypes extends Command private function shouldBeTransfer(string $transactionType, string $sourceType, string $destinationType): bool { - return ( + return TransactionTypeEnum::TRANSFER->value === $transactionType && AccountTypeEnum::ASSET->value === $sourceType - && $this->isLiability($destinationType) - ); + && $this->isLiability($destinationType); } private function isLiability(string $destinationType): bool { - return ( + return AccountTypeEnum::LOAN->value === $destinationType || AccountTypeEnum::DEBT->value === $destinationType - || AccountTypeEnum::MORTGAGE->value === $destinationType - ); + || AccountTypeEnum::MORTGAGE->value === $destinationType; } private function makeTransfer(TransactionJournal $journal): void @@ -289,7 +288,7 @@ class CorrectsAccountTypes extends Command $withdrawal = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); $journal->transactionType()->associate($withdrawal); $journal->save(); - $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id); + $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id); $this->friendlyInfo($message); Log::debug($message); // check it again: @@ -298,11 +297,10 @@ class CorrectsAccountTypes extends Command private function shouldBeDeposit(string $transactionType, string $sourceType, string $destinationType): bool { - return ( + return TransactionTypeEnum::TRANSFER->value === $transactionType && $this->isLiability($sourceType) - && AccountTypeEnum::ASSET->value === $destinationType - ); + && AccountTypeEnum::ASSET->value === $destinationType; } private function makeDeposit(TransactionJournal $journal): void @@ -320,11 +318,10 @@ class CorrectsAccountTypes extends Command private function shouldGoToExpenseAccount(string $transactionType, string $sourceType, string $destinationType): bool { - return ( + return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && AccountTypeEnum::ASSET->value === $sourceType - && AccountTypeEnum::REVENUE->value === $destinationType - ); + && AccountTypeEnum::REVENUE->value === $destinationType; } private function makeExpenseDestination(TransactionJournal $journal, Transaction $destination): void @@ -350,11 +347,10 @@ class CorrectsAccountTypes extends Command private function shouldComeFromRevenueAccount(string $transactionType, string $sourceType, string $destinationType): bool { - return ( + return TransactionTypeEnum::DEPOSIT->value === $transactionType && AccountTypeEnum::EXPENSE->value === $sourceType - && AccountTypeEnum::ASSET->value === $destinationType - ); + && AccountTypeEnum::ASSET->value === $destinationType; } private function makeRevenueSource(TransactionJournal $journal, Transaction $source): void @@ -366,7 +362,7 @@ class CorrectsAccountTypes extends Command $oldSource = $source->account; $source->account()->associate($result); $source->save(); - $message = sprintf( + $message = sprintf( 'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").', $journal->id, $oldSource->id, @@ -437,11 +433,11 @@ class CorrectsAccountTypes extends Command private function giveNewDestinationAccount(TransactionJournal $journal, Account $newDestination): void { - $destTransaction = $this->getDestinationTransaction($journal); - $oldDest = $destTransaction->account; + $destTransaction = $this->getDestinationTransaction($journal); + $oldDest = $destTransaction->account; $destTransaction->account_id = $newDestination->id; $destTransaction->save(); - $message = sprintf( + $message = sprintf( 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").', $journal->id, $oldDest->id, diff --git a/app/Console/Commands/Correction/CorrectsAmounts.php b/app/Console/Commands/Correction/CorrectsAmounts.php index b133ac8504..b2dcb794a5 100644 --- a/app/Console/Commands/Correction/CorrectsAmounts.php +++ b/app/Console/Commands/Correction/CorrectsAmounts.php @@ -87,14 +87,15 @@ class CorrectsAmounts extends Command ->whereNotNull('transactions.foreign_amount') ->where('transaction_journals.transaction_type_id', $type->id) ->distinct() - ->get(['transaction_journals.*']); + ->get(['transaction_journals.*']) + ; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $repository->setUser($journal->user); - $primary = Amount::getPrimaryCurrencyByUserGroup($journal->userGroup); + $primary = Amount::getPrimaryCurrencyByUserGroup($journal->userGroup); - $valid = $this->validateJournal($journal); + $valid = $this->validateJournal($journal); if (false === $valid) { // Log::debug(sprintf('Journal #%d does not need to be fixed or is invalid (see previous messages)', $journal->id)); @@ -112,11 +113,11 @@ class CorrectsAmounts extends Command if ($sourceCurrency->id === $destCurrency->id) { Log::debug('Both accounts have the same currency. Removing foreign currency info.'); - $source->foreign_currency_id = null; - $source->foreign_amount = null; + $source->foreign_currency_id = null; + $source->foreign_amount = null; $source->save(); $destination->foreign_currency_id = null; - $destination->foreign_amount = null; + $destination->foreign_amount = null; $destination->save(); continue; @@ -297,8 +298,8 @@ class CorrectsAmounts extends Command private function validateJournal(TransactionJournal $journal): bool { - $countSource = $journal->transactions()->where('amount', '<', 0)->count(); - $countDest = $journal->transactions()->where('amount', '>', 0)->count(); + $countSource = $journal->transactions()->where('amount', '<', 0)->count(); + $countDest = $journal->transactions()->where('amount', '>', 0)->count(); if (1 !== $countSource || 1 !== $countDest) { $this->friendlyError(sprintf('Transaction journal #%d has bad transaction information. Will delete.', $journal->id)); @@ -309,10 +310,10 @@ class CorrectsAmounts extends Command } /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destination */ - $destination = $journal->transactions()->where('amount', '>', 0)->first(); + $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $source || null === $destination) { $this->friendlyError(sprintf('Could not find source OR destination for journal #%d .', $journal->id)); @@ -328,7 +329,7 @@ class CorrectsAmounts extends Command } if (null === $source->foreign_amount || null === $destination->foreign_amount) { $this->friendlyError(sprintf('Transactions of journal #%d have no foreign amount, but have foreign currency info. Will reset this.', $journal->id)); - $source->foreign_currency_id = null; + $source->foreign_currency_id = null; $source->save(); $destination->foreign_currency_id = null; $source->save(); diff --git a/app/Console/Commands/Correction/CorrectsCurrencies.php b/app/Console/Commands/Correction/CorrectsCurrencies.php index 7e95db0558..ba2fcf776e 100644 --- a/app/Console/Commands/Correction/CorrectsCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsCurrencies.php @@ -61,58 +61,60 @@ class CorrectsCurrencies extends Command private function correctCurrencies(UserGroup $userGroup): void { /** @var CurrencyRepositoryInterface $repos */ - $repos = app(CurrencyRepositoryInterface::class); + $repos = app(CurrencyRepositoryInterface::class); // first check if the user has any default currency (not necessarily the case, so can be forced). $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($userGroup); Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id)); - $found = [$primaryCurrency->id]; + $found = [$primaryCurrency->id]; // get all meta entries - $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->where('accounts.user_group_id', $userGroup->id) ->where('account_meta.name', 'currency_id') ->groupBy('data') - ->get(['data']); + ->get(['data']) + ; foreach ($meta as $entry) { $found[] = (int) $entry->data; } // get all from journals: - $journals = TransactionJournal::where('user_group_id', $userGroup->id)->groupBy('transaction_currency_id')->get(['transaction_currency_id']); + $journals = TransactionJournal::where('user_group_id', $userGroup->id)->groupBy('transaction_currency_id')->get(['transaction_currency_id']); foreach ($journals as $entry) { $found[] = (int) $entry->transaction_currency_id; } // get all from transactions - $transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + $transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_group_id', $userGroup->id) ->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id') - ->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']); + ->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']) + ; foreach ($transactions as $entry) { $found[] = (int) $entry->transaction_currency_id; $found[] = (int) $entry->foreign_currency_id; } // get all from budget limits - $limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')->groupBy('transaction_currency_id')->get([ - 'budget_limits.transaction_currency_id' + $limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')->groupBy('transaction_currency_id')->get([ + 'budget_limits.transaction_currency_id', ]); foreach ($limits as $entry) { $found[] = $entry->transaction_currency_id; } // also get all currencies already enabled. - $alreadyEnabled = $userGroup->currencies()->get(['transaction_currencies.id'])->pluck('id')->toArray(); + $alreadyEnabled = $userGroup->currencies()->get(['transaction_currencies.id'])->pluck('id')->toArray(); foreach ($alreadyEnabled as $currencyId) { $found[] = $currencyId; } - $found = array_values(array_unique($found)); - $found = array_values(array_filter($found, static fn(int $currencyId): bool => 0 !== $currencyId)); + $found = array_values(array_unique($found)); + $found = array_values(array_filter($found, static fn (int $currencyId): bool => 0 !== $currencyId)); - $valid = new Collection(); + $valid = new Collection(); /** @var int $currencyId */ foreach ($found as $currencyId) { @@ -121,7 +123,7 @@ class CorrectsCurrencies extends Command $valid->push($currency); } } - $ids = $valid->pluck('id')->toArray(); + $ids = $valid->pluck('id')->toArray(); Log::debug(sprintf('Found currencies for user group #%d: %s', $userGroup->id, implode(', ', $ids))); $userGroup->currencies()->sync($ids); diff --git a/app/Console/Commands/Correction/CorrectsDatabase.php b/app/Console/Commands/Correction/CorrectsDatabase.php index 412cd8128b..89d2818f07 100644 --- a/app/Console/Commands/Correction/CorrectsDatabase.php +++ b/app/Console/Commands/Correction/CorrectsDatabase.php @@ -79,7 +79,7 @@ class CorrectsDatabase extends Command 'correction:recalculate-pc-amounts', 'correction:remove-links-to-deleted-objects', 'correction:clears-empty-foreign-amounts', - 'firefly-iii:report-integrity' + 'firefly-iii:report-integrity', ]; foreach ($commands as $command) { $this->friendlyLine(sprintf('Now executing command "%s"', $command)); diff --git a/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php b/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php index ee39d81abe..56b4a83ec2 100644 --- a/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php +++ b/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php @@ -59,7 +59,7 @@ class CorrectsFrontpageAccounts extends Command private function fixPreference(Preference $preference): void { - $fixed = []; + $fixed = []; /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); @@ -67,7 +67,7 @@ class CorrectsFrontpageAccounts extends Command return; } $repository->setUser($preference->user); - $data = $preference->data; + $data = $preference->data; if (is_array($data)) { /** @var string $accountId */ foreach ($data as $accountId) { diff --git a/app/Console/Commands/Correction/CorrectsGroupAccounts.php b/app/Console/Commands/Correction/CorrectsGroupAccounts.php index 494f828a51..5a836584bb 100644 --- a/app/Console/Commands/Correction/CorrectsGroupAccounts.php +++ b/app/Console/Commands/Correction/CorrectsGroupAccounts.php @@ -44,8 +44,8 @@ class CorrectsGroupAccounts extends Command */ public function handle(): int { - $groups = []; - $res = TransactionJournal::groupBy('transaction_group_id')->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]); + $groups = []; + $res = TransactionJournal::groupBy('transaction_group_id')->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]); /** @var TransactionJournal $journal */ foreach ($res as $journal) { diff --git a/app/Console/Commands/Correction/CorrectsGroupInformation.php b/app/Console/Commands/Correction/CorrectsGroupInformation.php index 17434a5220..ddb2a400ef 100644 --- a/app/Console/Commands/Correction/CorrectsGroupInformation.php +++ b/app/Console/Commands/Correction/CorrectsGroupInformation.php @@ -79,7 +79,7 @@ class CorrectsGroupInformation extends Command return; } - $set = [ + $set = [ Account::class, Attachment::class, AvailableBudget::class, @@ -95,7 +95,7 @@ class CorrectsGroupInformation extends Command Tag::class, TransactionGroup::class, TransactionJournal::class, - Webhook::class + Webhook::class, ]; foreach ($set as $className) { $this->updateGroupInfoForObject($user, $group, $className); diff --git a/app/Console/Commands/Correction/CorrectsIbans.php b/app/Console/Commands/Correction/CorrectsIbans.php index 487052f721..7ac2b0f73c 100644 --- a/app/Console/Commands/Correction/CorrectsIbans.php +++ b/app/Console/Commands/Correction/CorrectsIbans.php @@ -37,7 +37,7 @@ class CorrectsIbans extends Command protected $description = 'Removes spaces from IBANs'; protected $signature = 'correction:ibans'; - private int $count = 0; + private int $count = 0; /** * Execute the console command. @@ -55,8 +55,8 @@ class CorrectsIbans extends Command { /** @var Account $account */ foreach ($accounts as $account) { - $iban = (string) $account->iban; - $newIban = Steam::filterSpaces($iban); + $iban = (string) $account->iban; + $newIban = Steam::filterSpaces($iban); if ('' !== $iban && $iban !== $newIban) { $account->iban = $newIban; $account->save(); @@ -86,11 +86,11 @@ class CorrectsIbans extends Command foreach ($accounts as $account) { $userId = $account->user_id; $set[$userId] ??= []; - $iban = (string) $account->iban; + $iban = (string) $account->iban; if ('' === $iban) { continue; } - $type = $account->accountType->type; + $type = $account->accountType->type; if (in_array($type, [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], true)) { $type = 'liabilities'; } diff --git a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php index 0a441f6d26..2cd3acdccc 100644 --- a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php +++ b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php @@ -39,7 +39,7 @@ class CorrectsInvertedBudgetLimits extends Command * * @var string */ - protected $signature = 'correction:corrects-inverted-budget-limits'; + protected $signature = 'correction:corrects-inverted-budget-limits'; /** * The console command description. @@ -62,10 +62,10 @@ class CorrectsInvertedBudgetLimits extends Command /** @var BudgetLimit $budgetLimit */ foreach ($set as $budgetLimit) { - $start = $budgetLimit->start_date->copy(); - $end = $budgetLimit->end_date->copy(); + $start = $budgetLimit->start_date->copy(); + $end = $budgetLimit->end_date->copy(); $budgetLimit->start_date = $end; - $budgetLimit->end_date = $start; + $budgetLimit->end_date = $start; $budgetLimit->saveQuietly(); } if (1 === $set->count()) { diff --git a/app/Console/Commands/Correction/CorrectsLongDescriptions.php b/app/Console/Commands/Correction/CorrectsLongDescriptions.php index a865c39ad5..4817a8a750 100644 --- a/app/Console/Commands/Correction/CorrectsLongDescriptions.php +++ b/app/Console/Commands/Correction/CorrectsLongDescriptions.php @@ -36,8 +36,8 @@ class CorrectsLongDescriptions extends Command private const int MAX_LENGTH = 1000; - protected $description = 'Fixes long descriptions in journals and groups.'; - protected $signature = 'correction:long-descriptions'; + protected $description = 'Fixes long descriptions in journals and groups.'; + protected $signature = 'correction:long-descriptions'; /** * Execute the console command. @@ -57,7 +57,7 @@ class CorrectsLongDescriptions extends Command } } - $groups = TransactionGroup::where(DB::raw('LENGTH(title)'), '>', self::MAX_LENGTH)->get(['id', 'title']); + $groups = TransactionGroup::where(DB::raw('LENGTH(title)'), '>', self::MAX_LENGTH)->get(['id', 'title']); /** @var TransactionGroup $group */ foreach ($groups as $group) { diff --git a/app/Console/Commands/Correction/CorrectsMetaDataFields.php b/app/Console/Commands/Correction/CorrectsMetaDataFields.php index a14071592f..82adce9563 100644 --- a/app/Console/Commands/Correction/CorrectsMetaDataFields.php +++ b/app/Console/Commands/Correction/CorrectsMetaDataFields.php @@ -35,7 +35,7 @@ class CorrectsMetaDataFields extends Command protected $description = 'Rename changed meta fields.'; protected $signature = 'correction:meta-fields'; - private int $count = 0; + private int $count = 0; /** * Execute the console command. @@ -54,7 +54,7 @@ class CorrectsMetaDataFields extends Command 'sepa-ep' => 'sepa_ep', 'sepa-ci' => 'sepa_ci', 'sepa-batch-id' => 'sepa_batch_id', - 'external_uri' => 'external_url' + 'external_uri' => 'external_url', ]; foreach ($changes as $original => $update) { $this->rename($original, $update); diff --git a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php index 6364bf380d..2120b3021b 100644 --- a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php @@ -71,7 +71,8 @@ class CorrectsOpeningBalanceCurrencies extends Command return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereNull('transaction_journals.deleted_at') ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value) - ->get(['transaction_journals.*']); + ->get(['transaction_journals.*']) + ; } private function correctJournal(TransactionJournal $journal): int @@ -90,7 +91,7 @@ class CorrectsOpeningBalanceCurrencies extends Command return $this->setCorrectCurrency($account, $journal); } - private function getAccount(TransactionJournal $journal): null|Account + private function getAccount(TransactionJournal $journal): ?Account { $transactions = $journal->transactions()->get(); @@ -113,7 +114,7 @@ class CorrectsOpeningBalanceCurrencies extends Command if ((int) $journal->transaction_currency_id !== $currency->id) { $journal->transaction_currency_id = $currency->id; $journal->save(); - $count = 1; + $count = 1; } /** @var Transaction $transaction */ @@ -121,7 +122,7 @@ class CorrectsOpeningBalanceCurrencies extends Command if ($transaction->transaction_currency_id !== $currency->id) { $transaction->transaction_currency_id = $currency->id; $transaction->save(); - $count = 1; + $count = 1; } } diff --git a/app/Console/Commands/Correction/CorrectsPreferences.php b/app/Console/Commands/Correction/CorrectsPreferences.php index 76c75c8596..1787094c95 100644 --- a/app/Console/Commands/Correction/CorrectsPreferences.php +++ b/app/Console/Commands/Correction/CorrectsPreferences.php @@ -33,7 +33,7 @@ class CorrectsPreferences extends Command { protected $description = 'Give Firefly III preferences a user group ID so they can be made administration specific.'; - protected $signature = 'correction:preferences'; + protected $signature = 'correction:preferences'; /** * Execute the console command. diff --git a/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php index d87fd31470..47c2ae8968 100644 --- a/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php +++ b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php @@ -55,7 +55,7 @@ class CorrectsPrimaryCurrencyAmounts extends Command protected $description = 'Recalculate primary currency amounts for all objects.'; - protected $signature = 'correction:recalculate-pc-amounts'; + protected $signature = 'correction:recalculate-pc-amounts'; /** * Execute the console command. @@ -114,7 +114,8 @@ class CorrectsPrimaryCurrencyAmounts extends Command $q->orWhere('virtual_balance', '!=', ''); } }) - ->get(); + ->get() + ; /** @var Account $account */ foreach ($set as $account) { @@ -125,13 +126,13 @@ class CorrectsPrimaryCurrencyAmounts extends Command private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($userGroup); $converter->setIgnoreSettings(true); $repository = app(PiggyBankRepositoryInterface::class); $repository->setUserGroup($userGroup); - $set = $repository->getPiggyBanks(); - $set = $set->filter(static fn(PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id); + $set = $repository->getPiggyBanks(); + $set = $set->filter(static fn (PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id); foreach ($set as $piggyBank) { $piggyBank->encrypted = false; $piggyBank->save(); @@ -224,7 +225,7 @@ class CorrectsPrimaryCurrencyAmounts extends Command private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void { // custom query because of the potential size of this update. - $set = DB::table('transactions') + $set = DB::table('transactions') ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_group_id', $userGroup->id) ->where(static function (DatabaseBuilder $q1) use ($currency): void { @@ -239,7 +240,8 @@ class CorrectsPrimaryCurrencyAmounts extends Command // ->whereNot('transactions.foreign_currency_id', $currency->id) // ; // }) - ->get(['transactions.id']); + ->get(['transactions.id']) + ; TransactionObserver::$recalculate = false; foreach ($set as $item) { // here we are. diff --git a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php index 836ac6d0de..e043cafdab 100644 --- a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php +++ b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php @@ -39,7 +39,7 @@ class CorrectsRecurringTransactions extends Command protected $description = 'Fixes recurring transactions with the wrong transaction type.'; protected $signature = 'correction:recurring-transactions'; - private int $count = 0; + private int $count = 0; private RecurringRepositoryInterface $recurringRepos; private UserRepositoryInterface $userRepos; @@ -62,7 +62,7 @@ class CorrectsRecurringTransactions extends Command private function stupidLaravel(): void { $this->recurringRepos = app(RecurringRepositoryInterface::class); - $this->userRepos = app(UserRepositoryInterface::class); + $this->userRepos = app(UserRepositoryInterface::class); } private function correctTransactions(): void diff --git a/app/Console/Commands/Correction/CorrectsTimezoneInformation.php b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php index f921dc354d..b746ea7ee9 100644 --- a/app/Console/Commands/Correction/CorrectsTimezoneInformation.php +++ b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php @@ -47,22 +47,22 @@ class CorrectsTimezoneInformation extends Command use ShowsFriendlyMessages; public static array $models = [ - AccountBalance::class => ['date'], // done - AvailableBudget::class => ['start_date', 'end_date'], // done - Bill::class => ['date', 'end_date', 'extension_date'], // done - BudgetLimit::class => ['start_date', 'end_date'], // done + AccountBalance::class => ['date'], // done + AvailableBudget::class => ['start_date', 'end_date'], // done + Bill::class => ['date', 'end_date', 'extension_date'], // done + BudgetLimit::class => ['start_date', 'end_date'], // done CurrencyExchangeRate::class => ['date'], // done - InvitedUser::class => ['expires'], - PiggyBankEvent::class => ['date'], - PiggyBankRepetition::class => ['start_date', 'target_date'], - PiggyBank::class => ['start_date', 'target_date'], // done - Recurrence::class => ['first_date', 'repeat_until', 'latest_date'], - Tag::class => ['date'], - TransactionJournal::class => ['date'] + InvitedUser::class => ['expires'], + PiggyBankEvent::class => ['date'], + PiggyBankRepetition::class => ['start_date', 'target_date'], + PiggyBank::class => ['start_date', 'target_date'], // done + Recurrence::class => ['first_date', 'repeat_until', 'latest_date'], + Tag::class => ['date'], + TransactionJournal::class => ['date'], ]; - protected $description = 'Make sure all dates have a timezone.'; - protected $signature = 'correction:timezones'; + protected $description = 'Make sure all dates have a timezone.'; + protected $signature = 'correction:timezones'; /** * Execute the console command. diff --git a/app/Console/Commands/Correction/CorrectsTransactionTypes.php b/app/Console/Commands/Correction/CorrectsTransactionTypes.php index c16afdff4b..4510cd0587 100644 --- a/app/Console/Commands/Correction/CorrectsTransactionTypes.php +++ b/app/Console/Commands/Correction/CorrectsTransactionTypes.php @@ -77,7 +77,7 @@ class CorrectsTransactionTypes extends Command private function fixJournal(TransactionJournal $journal): bool { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; try { $source = $this->getSourceAccount($journal); @@ -110,7 +110,7 @@ class CorrectsTransactionTypes extends Command */ private function getSourceAccount(TransactionJournal $journal): Account { - $collection = $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount < 0); + $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount < 0); if (0 === $collection->count()) { throw new FireflyException(sprintf('300001: Journal #%d has no source transaction.', $journal->id)); } @@ -122,7 +122,7 @@ class CorrectsTransactionTypes extends Command $transaction = $collection->first(); /** @var null|Account $account */ - $account = $transaction->account; + $account = $transaction->account; if (null === $account) { throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id)); } @@ -135,7 +135,7 @@ class CorrectsTransactionTypes extends Command */ private function getDestinationAccount(TransactionJournal $journal): Account { - $collection = $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount > 0); + $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0); if (0 === $collection->count()) { throw new FireflyException(sprintf('300004: Journal #%d has no destination transaction.', $journal->id)); } @@ -147,7 +147,7 @@ class CorrectsTransactionTypes extends Command $transaction = $collection->first(); /** @var null|Account $account */ - $account = $transaction->account; + $account = $transaction->account; if (null === $account) { throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id)); } diff --git a/app/Console/Commands/Correction/CorrectsTransferBudgets.php b/app/Console/Commands/Correction/CorrectsTransferBudgets.php index 10e10ef388..dacb03b907 100644 --- a/app/Console/Commands/Correction/CorrectsTransferBudgets.php +++ b/app/Console/Commands/Correction/CorrectsTransferBudgets.php @@ -47,7 +47,8 @@ class CorrectsTransferBudgets extends Command ->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') ->whereNotIn('transaction_types.type', [TransactionTypeEnum::WITHDRAWAL->value]) ->whereNotNull('budget_transaction_journal.budget_id') - ->get(['transaction_journals.*']); + ->get(['transaction_journals.*']) + ; $count = 0; /** @var TransactionJournal $entry */ diff --git a/app/Console/Commands/Correction/CorrectsUnevenAmount.php b/app/Console/Commands/Correction/CorrectsUnevenAmount.php index 624108274b..3e575ecac6 100644 --- a/app/Console/Commands/Correction/CorrectsUnevenAmount.php +++ b/app/Console/Commands/Correction/CorrectsUnevenAmount.php @@ -80,13 +80,14 @@ class CorrectsUnevenAmount extends Command ->where('transaction_types.type', TransactionTypeEnum::TRANSFER->value) ->whereNotNull('foreign_currency_id') ->whereNotNull('foreign_amount') - ->get(['transactions.transaction_journal_id']); + ->get(['transactions.transaction_journal_id']) + ; $count = 0; /** @var Transaction $transaction */ foreach ($transactions as $transaction) { /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($transaction->transaction_journal_id); + $journal = TransactionJournal::find($transaction->transaction_journal_id); if (null === $journal) { Log::debug('Found no journal, continue.'); @@ -103,7 +104,7 @@ class CorrectsUnevenAmount extends Command $destination = $journal->transactions()->where('amount', '>', 0)->first(); /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $destination || null === $source) { Log::debug('Source or destination transaction is NULL, continue.'); @@ -112,12 +113,12 @@ class CorrectsUnevenAmount extends Command } if ($source->transaction_currency_id === $destination->transaction_currency_id) { Log::debug('Ready to swap data between transactions.'); - $destination->foreign_currency_id = $source->transaction_currency_id; - $destination->foreign_amount = Steam::positive($source->amount); + $destination->foreign_currency_id = $source->transaction_currency_id; + $destination->foreign_amount = Steam::positive($source->amount); $destination->transaction_currency_id = $source->foreign_currency_id; - $destination->amount = Steam::positive($source->foreign_amount); - $destination->balance_dirty = true; - $source->balance_dirty = true; + $destination->amount = Steam::positive($source->foreign_amount); + $destination->balance_dirty = true; + $source->balance_dirty = true; $destination->save(); $source->save(); $this->friendlyWarning(sprintf('Corrected foreign amounts of transfer #%d.', $journal->id)); @@ -136,7 +137,8 @@ class CorrectsUnevenAmount extends Command $journals = DB::table('transactions') ->groupBy('transaction_journal_id') ->whereNull('deleted_at') - ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]); + ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]) + ; /** @var stdClass $entry */ foreach ($journals as $entry) { @@ -173,13 +175,13 @@ class CorrectsUnevenAmount extends Command private function fixJournal(int $param): void { // one of the transactions is bad. - $journal = TransactionJournal::find($param); + $journal = TransactionJournal::find($param); if (null === $journal) { return; } /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $source) { $this->friendlyError(sprintf( @@ -194,11 +196,11 @@ class CorrectsUnevenAmount extends Command return; } - $amount = bcmul('-1', (string) $source->amount); + $amount = bcmul('-1', (string) $source->amount); // fix amount of destination: /** @var null|Transaction $destination */ - $destination = $journal->transactions()->where('amount', '>', 0)->first(); + $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { $this->friendlyError(sprintf( @@ -221,7 +223,7 @@ class CorrectsUnevenAmount extends Command return; } - $message = sprintf('Sum of journal #%d is not zero, journal is broken and now fixed.', $journal->id); + $message = sprintf('Sum of journal #%d is not zero, journal is broken and now fixed.', $journal->id); $this->friendlyWarning($message); Log::warning($message); @@ -229,7 +231,7 @@ class CorrectsUnevenAmount extends Command $destination->amount = $amount; $destination->save(); - $message = sprintf('Corrected amount in transaction journal #%d', $param); + $message = sprintf('Corrected amount in transaction journal #%d', $param); $this->friendlyInfo($message); ++$this->count; } @@ -244,7 +246,7 @@ class CorrectsUnevenAmount extends Command $destination = $journal->transactions()->where('amount', '>', 0)->first(); /** @var Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); // safety catch on NULL should not be necessary, we just had that catch. // source amount = dest foreign amount @@ -255,12 +257,11 @@ class CorrectsUnevenAmount extends Command // Log::debug(sprintf('[b] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($destination->amount), \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount)))); // Log::debug(sprintf('[c] %s', var_export($source->transaction_currency_id === $destination->foreign_currency_id,true))); // Log::debug(sprintf('[d] %s', var_export((int) $destination->transaction_currency_id ===(int) $source->foreign_currency_id, true))); - return ( + return 0 === bccomp(Steam::positive($source->amount), Steam::positive($destination->foreign_amount)) && $source->transaction_currency_id === $destination->foreign_currency_id && 0 === bccomp(Steam::positive($destination->amount), Steam::positive($source->foreign_amount)) - && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id - ); + && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id; } private function matchCurrencies(): void @@ -271,7 +272,7 @@ class CorrectsUnevenAmount extends Command DB::raw('transaction_journals.transaction_currency_id') )->get(['transaction_journals.*']); - $count = 0; + $count = 0; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { @@ -293,7 +294,7 @@ class CorrectsUnevenAmount extends Command private function isBetweenAssetAndLiability(TransactionJournal $journal): bool { /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); + $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destinationTransaction */ $destinationTransaction = $journal->transactions()->where('amount', '>', 0)->first(); @@ -308,15 +309,15 @@ class CorrectsUnevenAmount extends Command return false; } - $source = $sourceTransaction->account; - $destination = $destinationTransaction->account; + $source = $sourceTransaction->account; + $destination = $destinationTransaction->account; if (null === $source || null === $destination) { Log::warning('Either is false, stop.'); return false; } - $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; // source is liability, destination is asset if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) { @@ -337,7 +338,7 @@ class CorrectsUnevenAmount extends Command private function convertOldStyleTransactions(): void { /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); Log::debug('convertOldStyleTransactions()'); $count = 0; $transactions = Transaction::distinct() @@ -352,14 +353,15 @@ class CorrectsUnevenAmount extends Command AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::LOAN->value + AccountTypeEnum::LOAN->value, ]) - ->get(['transactions.transaction_journal_id']); + ->get(['transactions.transaction_journal_id']) + ; /** @var Transaction $transaction */ foreach ($transactions as $transaction) { /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($transaction->transaction_journal_id); + $journal = TransactionJournal::find($transaction->transaction_journal_id); $repository->setUser($journal->user); if (null === $journal) { Log::debug('Found no journal, continue.'); @@ -394,12 +396,12 @@ class CorrectsUnevenAmount extends Command if ((int) $source->transaction_currency_id !== (int) $sourceCurrency->id) { Log::debug(sprintf('Ready to swap data in transaction #%d.', $source->id)); // swap amounts. - $amount = $source->amount; - $currency = $source->transaction_currency_id; - $source->amount = $source->foreign_amount; + $amount = $source->amount; + $currency = $source->transaction_currency_id; + $source->amount = $source->foreign_amount; $source->transaction_currency_id = $source->foreign_currency_id; - $source->foreign_amount = $amount; - $source->foreign_currency_id = $currency; + $source->foreign_amount = $amount; + $source->foreign_currency_id = $currency; $source->saveQuietly(); $source->refresh(); // Log::debug(sprintf('source->amount = %s', $source->amount)); @@ -413,13 +415,13 @@ class CorrectsUnevenAmount extends Command ++$count; Log::debug(sprintf('Ready to swap data in transaction #%d.', $destination->id)); // swap amounts. - $amount = $destination->amount; - $currency = $destination->transaction_currency_id; - $destination->amount = $destination->foreign_amount; + $amount = $destination->amount; + $currency = $destination->transaction_currency_id; + $destination->amount = $destination->foreign_amount; $destination->transaction_currency_id = $destination->foreign_currency_id; - $destination->foreign_amount = $amount; - $destination->foreign_currency_id = $currency; - $destination->balance_dirty = true; + $destination->foreign_amount = $amount; + $destination->foreign_currency_id = $currency; + $destination->balance_dirty = true; $destination->saveQuietly(); $destination->refresh(); diff --git a/app/Console/Commands/Correction/CreatesAccessTokens.php b/app/Console/Commands/Correction/CreatesAccessTokens.php index 38b1a678c3..ef478d8da2 100644 --- a/app/Console/Commands/Correction/CreatesAccessTokens.php +++ b/app/Console/Commands/Correction/CreatesAccessTokens.php @@ -37,7 +37,7 @@ class CreatesAccessTokens extends Command protected $description = 'Creates user access tokens which are used for command line access to personal data.'; - protected $signature = 'correction:access-tokens'; + protected $signature = 'correction:access-tokens'; /** * Execute the console command. @@ -50,8 +50,8 @@ class CreatesAccessTokens extends Command /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $count = 0; - $users = $repository->all(); + $count = 0; + $users = $repository->all(); /** @var User $user */ foreach ($users as $user) { diff --git a/app/Console/Commands/Correction/CreatesGroupMemberships.php b/app/Console/Commands/Correction/CreatesGroupMemberships.php index 2823ae4156..bf35bcfdef 100644 --- a/app/Console/Commands/Correction/CreatesGroupMemberships.php +++ b/app/Console/Commands/Correction/CreatesGroupMemberships.php @@ -39,8 +39,8 @@ class CreatesGroupMemberships extends Command public const string CONFIG_NAME = '560_create_group_memberships'; - protected $description = 'Update group memberships'; - protected $signature = 'correction:create-group-memberships'; + protected $description = 'Update group memberships'; + protected $signature = 'correction:create-group-memberships'; /** * Execute the console command. @@ -75,12 +75,12 @@ class CreatesGroupMemberships extends Command public static function createGroupMembership(User $user): void { // check if membership exists - $userGroup = UserGroup::where('title', $user->email)->first(); + $userGroup = UserGroup::where('title', $user->email)->first(); if (null === $userGroup) { $userGroup = UserGroup::create(['title' => $user->email]); } - $userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); + $userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); if (null === $userRole) { throw new FireflyException('Firefly III could not find a user role. Please make sure all migrations have run.'); @@ -88,7 +88,8 @@ class CreatesGroupMemberships extends Command $membership = GroupMembership::where('user_id', $user->id) ->where('user_group_id', $userGroup->id) ->where('user_role_id', $userRole->id) - ->first(); + ->first() + ; if (null === $membership) { GroupMembership::create(['user_id' => $user->id, 'user_role_id' => $userRole->id, 'user_group_id' => $userGroup->id]); } diff --git a/app/Console/Commands/Correction/CreatesLinkTypes.php b/app/Console/Commands/Correction/CreatesLinkTypes.php index 097a4b88a2..1cdbb05b25 100644 --- a/app/Console/Commands/Correction/CreatesLinkTypes.php +++ b/app/Console/Commands/Correction/CreatesLinkTypes.php @@ -34,7 +34,7 @@ class CreatesLinkTypes extends Command protected $description = 'Creates all link types.'; - protected $signature = 'correction:link-types'; + protected $signature = 'correction:link-types'; /** * Execute the console command. @@ -46,14 +46,14 @@ class CreatesLinkTypes extends Command 'Related' => ['relates to', 'relates to'], 'Refund' => ['(partially) refunds', 'is (partially) refunded by'], 'Paid' => ['(partially) pays for', 'is (partially) paid for by'], - 'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'] + 'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'], ]; foreach ($set as $name => $values) { - $link = LinkType::where('name', $name)->first(); + $link = LinkType::where('name', $name)->first(); if (null === $link) { - $link = new LinkType(); - $link->name = $name; - $link->inward = $values[1]; + $link = new LinkType(); + $link->name = $name; + $link->inward = $values[1]; $link->outward = $values[0]; ++$count; $this->friendlyInfo(sprintf('Created missing link type "%s"', $name)); diff --git a/app/Console/Commands/Correction/RemovesBills.php b/app/Console/Commands/Correction/RemovesBills.php index 9a30b25887..a47ad03fc7 100644 --- a/app/Console/Commands/Correction/RemovesBills.php +++ b/app/Console/Commands/Correction/RemovesBills.php @@ -47,7 +47,7 @@ class RemovesBills extends Command if (null === $withdrawal) { return 0; } - $journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get(); + $journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get(); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { diff --git a/app/Console/Commands/Correction/RemovesEmptyGroups.php b/app/Console/Commands/Correction/RemovesEmptyGroups.php index 063ecc3988..64c9f25420 100644 --- a/app/Console/Commands/Correction/RemovesEmptyGroups.php +++ b/app/Console/Commands/Correction/RemovesEmptyGroups.php @@ -47,9 +47,10 @@ class RemovesEmptyGroups extends Command ->whereNull('transaction_journals.id') ->get(['transaction_groups.id']) ->pluck('id') - ->toArray(); + ->toArray() + ; - $total = count($groupIds); + $total = count($groupIds); if ($total > 0) { $this->friendlyInfo(sprintf('Deleted %d empty transaction group(s).', $total)); diff --git a/app/Console/Commands/Correction/RemovesEmptyJournals.php b/app/Console/Commands/Correction/RemovesEmptyJournals.php index 127cf9db11..12c6efd5db 100644 --- a/app/Console/Commands/Correction/RemovesEmptyJournals.php +++ b/app/Console/Commands/Correction/RemovesEmptyJournals.php @@ -38,7 +38,7 @@ class RemovesEmptyJournals extends Command protected $description = 'Delete empty and uneven transaction journals.'; - protected $signature = 'correction:empty-journals'; + protected $signature = 'correction:empty-journals'; /** * Execute the console command. @@ -58,7 +58,7 @@ class RemovesEmptyJournals extends Command { $set = Transaction::whereNull('deleted_at')->groupBy('transactions.transaction_journal_id')->get([ DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), - 'transaction_journal_id' + 'transaction_journal_id', ]); $total = 0; @@ -92,7 +92,8 @@ class RemovesEmptyJournals extends Command $set = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->groupBy('transaction_journals.id') ->whereNull('transactions.transaction_journal_id') - ->get(['transaction_journals.id']); + ->get(['transaction_journals.id']) + ; foreach ($set as $entry) { try { diff --git a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php index 0637143f8f..a0e6b86413 100644 --- a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php +++ b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php @@ -41,7 +41,7 @@ class RemovesLinksToDeletedObjects extends Command * * @var string */ - protected $signature = 'correction:remove-links-to-deleted-objects'; + protected $signature = 'correction:remove-links-to-deleted-objects'; /** * The console command description. @@ -59,22 +59,26 @@ class RemovesLinksToDeletedObjects extends Command ->whereNotNull('deleted_at') ->get('tags.id') ->pluck('id') - ->toArray(); + ->toArray() + ; $deletedJournals = TransactionJournal::withTrashed() ->whereNotNull('deleted_at') ->get('transaction_journals.id') ->pluck('id') - ->toArray(); + ->toArray() + ; $deletedBudgets = Budget::withTrashed() ->whereNotNull('deleted_at') ->get('budgets.id') ->pluck('id') - ->toArray(); + ->toArray() + ; $deletedCategories = Category::withTrashed() ->whereNotNull('deleted_at') ->get('categories.id') ->pluck('id') - ->toArray(); + ->toArray() + ; if (count($deletedTags) > 0) { $this->cleanupTags($deletedTags); diff --git a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php index f3a42f2b96..7f005aeedc 100644 --- a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php +++ b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php @@ -40,7 +40,7 @@ class RemovesOrphanedTransactions extends Command protected $description = 'Deletes orphaned transactions.'; - protected $signature = 'correction:orphaned-transactions'; + protected $signature = 'correction:orphaned-transactions'; /** * Execute the console command. @@ -61,7 +61,8 @@ class RemovesOrphanedTransactions extends Command $set = TransactionJournal::leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id') ->whereNotNull('transaction_groups.deleted_at') ->whereNull('transaction_journals.deleted_at') - ->get(['transaction_journals.id', 'transaction_journals.transaction_group_id']); + ->get(['transaction_journals.id', 'transaction_journals.transaction_group_id']) + ; $count = $set->count(); if (0 === $count) { // $this->friendlyPositive('No orphaned journals.'); @@ -93,7 +94,8 @@ class RemovesOrphanedTransactions extends Command ->whereNotNull('transaction_journals.deleted_at') ->whereNull('transactions.deleted_at') ->whereNotNull('transactions.id') - ->get(['transaction_journals.id as journal_id', 'transactions.id as transaction_id']); + ->get(['transaction_journals.id as journal_id', 'transactions.id as transaction_id']) + ; /** @var stdClass $entry */ foreach ($set as $entry) { diff --git a/app/Console/Commands/Correction/RemovesZeroAmount.php b/app/Console/Commands/Correction/RemovesZeroAmount.php index 77bddaaaa0..1dd02c5775 100644 --- a/app/Console/Commands/Correction/RemovesZeroAmount.php +++ b/app/Console/Commands/Correction/RemovesZeroAmount.php @@ -35,7 +35,7 @@ class RemovesZeroAmount extends Command protected $description = 'Delete transactions with zero amount.'; - protected $signature = 'correction:zero-amounts'; + protected $signature = 'correction:zero-amounts'; /** * Execute the console command. @@ -45,7 +45,8 @@ class RemovesZeroAmount extends Command $set = Transaction::where('amount', 0) ->get(['transaction_journal_id']) ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $set = array_unique($set); $journals = TransactionJournal::whereIn('id', $set)->get(); diff --git a/app/Console/Commands/Explain/ExplainAvailableBudget.php b/app/Console/Commands/Explain/ExplainAvailableBudget.php index 92a78af629..d22935d49e 100644 --- a/app/Console/Commands/Explain/ExplainAvailableBudget.php +++ b/app/Console/Commands/Explain/ExplainAvailableBudget.php @@ -40,7 +40,7 @@ class ExplainAvailableBudget extends Command * * @var string */ - protected $signature = 'explain:available-budget + protected $signature = 'explain:available-budget {--date=now : A date formatted YYYY-MM-DD or the word "now"} {--user=1 : The user ID.} {--token= : The user\'s access token.} diff --git a/app/Console/Commands/Export/ExportsData.php b/app/Console/Commands/Export/ExportsData.php index 7fa6898f5e..2a9b55292c 100644 --- a/app/Console/Commands/Export/ExportsData.php +++ b/app/Console/Commands/Export/ExportsData.php @@ -50,7 +50,7 @@ class ExportsData extends Command protected $description = 'Command to export data from Firefly III.'; - protected $signature = 'firefly-iii:export-data + protected $signature = 'firefly-iii:export-data {--user=1 : The user ID that the export should run for.} {--token= : The user\'s access token.} {--start= : First transaction to export. Defaults to your very first transaction. Only applies to transaction export.} @@ -85,7 +85,7 @@ class ExportsData extends Command } // set up repositories. $this->stupidLaravel(); - $user = $this->getUser(); + $user = $this->getUser(); $this->journalRepository->setUser($user); $this->accountRepository->setUser($user); @@ -100,7 +100,7 @@ class ExportsData extends Command // make export object and configure it. /** @var ExportDataGenerator $exporter */ - $exporter = app(ExportDataGenerator::class); + $exporter = app(ExportDataGenerator::class); $exporter->setUser($user); $exporter->setStart($options['start']); @@ -115,7 +115,7 @@ class ExportsData extends Command $exporter->setExportRules($options['export']['rules']); $exporter->setExportBills($options['export']['bills']); $exporter->setExportPiggies($options['export']['piggies']); - $data = $exporter->export(); + $data = $exporter->export(); if (0 === count($data)) { $this->friendlyError('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org'); } @@ -165,13 +165,13 @@ class ExportsData extends Command 'recurring' => $this->option('export-recurring'), 'rules' => $this->option('export-rules'), 'bills' => $this->option('export-subscriptions'), - 'piggies' => $this->option('export-piggies') + 'piggies' => $this->option('export-piggies'), ], 'start' => $start, 'end' => $end, 'accounts' => $accounts, 'directory' => $export, - 'force' => $this->option('force') + 'force' => $this->option('force'), ]; } diff --git a/app/Console/Commands/Integrity/ReportsEmptyObjects.php b/app/Console/Commands/Integrity/ReportsEmptyObjects.php index 25204cd21e..b234d646c7 100644 --- a/app/Console/Commands/Integrity/ReportsEmptyObjects.php +++ b/app/Console/Commands/Integrity/ReportsEmptyObjects.php @@ -38,7 +38,7 @@ class ReportsEmptyObjects extends Command protected $description = 'Reports on empty database objects.'; - protected $signature = 'integrity:empty-objects'; + protected $signature = 'integrity:empty-objects'; /** * Execute the console command. @@ -64,7 +64,8 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('budget_transaction_journal.budget_id') ->whereNull('budgets.deleted_at') - ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']); + ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']) + ; /** @var stdClass $entry */ foreach ($set as $entry) { @@ -83,7 +84,8 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('category_transaction_journal.category_id') ->whereNull('categories.deleted_at') - ->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']); + ->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']) + ; /** @var stdClass $entry */ foreach ($set as $entry) { @@ -99,7 +101,8 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('tag_transaction_journal.tag_id') ->whereNull('tags.deleted_at') - ->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']); + ->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']) + ; /** @var stdClass $entry */ foreach ($set as $entry) { @@ -117,7 +120,8 @@ class ReportsEmptyObjects extends Command ->leftJoin('users', 'accounts.user_id', '=', 'users.id') ->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']) ->whereNull('transactions.account_id') - ->get(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']); + ->get(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']) + ; /** @var stdClass $entry */ foreach ($set as $entry) { @@ -136,7 +140,8 @@ class ReportsEmptyObjects extends Command ->leftJoin('users', 'budgets.user_id', '=', 'users.id') ->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email']) ->whereNull('budget_limits.id') - ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email']); + ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email']) + ; /** @var Budget $entry */ foreach ($set as $entry) { diff --git a/app/Console/Commands/Integrity/ReportsIntegrity.php b/app/Console/Commands/Integrity/ReportsIntegrity.php index dabee7ebb3..6f66b89df1 100644 --- a/app/Console/Commands/Integrity/ReportsIntegrity.php +++ b/app/Console/Commands/Integrity/ReportsIntegrity.php @@ -34,7 +34,7 @@ class ReportsIntegrity extends Command protected $description = 'Will report on the integrity of your database.'; - protected $signature = 'firefly-iii:report-integrity'; + protected $signature = 'firefly-iii:report-integrity'; /** * Execute the console command. diff --git a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php index 4a72b828c7..820250d252 100644 --- a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php +++ b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php @@ -57,9 +57,9 @@ class ValidatesEnvironmentVariables extends Command private function validateLanguage(): bool { - $language = config('firefly.default_language'); - $locale = config('firefly.default_locale'); - $options = array_keys(config('firefly.languages')); + $language = config('firefly.default_language'); + $locale = config('firefly.default_locale'); + $options = array_keys(config('firefly.languages')); if (!in_array($language, $options, true)) { $this->friendlyError(sprintf('DEFAULT_LANGUAGE "%s" is not a valid language for Firefly III.', $language)); diff --git a/app/Console/Commands/Integrity/ValidatesFilePermissions.php b/app/Console/Commands/Integrity/ValidatesFilePermissions.php index 606c9eba0d..324ec43752 100644 --- a/app/Console/Commands/Integrity/ValidatesFilePermissions.php +++ b/app/Console/Commands/Integrity/ValidatesFilePermissions.php @@ -36,7 +36,7 @@ class ValidatesFilePermissions extends Command * * @var string */ - protected $signature = 'integrity:file-permissions'; + protected $signature = 'integrity:file-permissions'; /** * The console command description. diff --git a/app/Console/Commands/System/CreatesDatabase.php b/app/Console/Commands/System/CreatesDatabase.php index e6eb9436f2..685aaf101d 100644 --- a/app/Console/Commands/System/CreatesDatabase.php +++ b/app/Console/Commands/System/CreatesDatabase.php @@ -35,7 +35,7 @@ class CreatesDatabase extends Command protected $description = 'Tries to create the database if it doesn\'t exist yet.'; - protected $signature = 'firefly-iii:create-database'; + protected $signature = 'firefly-iii:create-database'; public function handle(): int { @@ -45,8 +45,8 @@ class CreatesDatabase extends Command return 0; } // try to set up a raw connection: - $exists = false; - $dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', env('DB_HOST'), env('DB_PORT')); + $exists = false; + $dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', env('DB_HOST'), env('DB_PORT')); if ('' !== (string) env('DB_SOCKET')) { $dsn = sprintf('mysql:unix_socket=%s;charset=utf8mb4', env('DB_SOCKET')); @@ -56,7 +56,7 @@ class CreatesDatabase extends Command $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, - PDO::ATTR_EMULATE_PREPARES => false + PDO::ATTR_EMULATE_PREPARES => false, ]; // when it fails, display error @@ -71,7 +71,7 @@ class CreatesDatabase extends Command // only continue when no error. // with PDO, try to list DB's ( /** @var array $stmt */ - $stmt = $pdo->query('SHOW DATABASES;'); + $stmt = $pdo->query('SHOW DATABASES;'); // slightly more complex but less error-prone. foreach ($stmt as $row) { $name = $row['Database'] ?? false; diff --git a/app/Console/Commands/System/CreatesFirstUser.php b/app/Console/Commands/System/CreatesFirstUser.php index 82513efb11..63ed750986 100644 --- a/app/Console/Commands/System/CreatesFirstUser.php +++ b/app/Console/Commands/System/CreatesFirstUser.php @@ -36,7 +36,7 @@ class CreatesFirstUser extends Command protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.'; - protected $signature = 'system:create-first-user {email}'; + protected $signature = 'system:create-first-user {email}'; private UserRepositoryInterface $repository; /** @@ -50,15 +50,15 @@ class CreatesFirstUser extends Command return 1; } $this->stupidLaravel(); - $count = $this->repository->count(); + $count = $this->repository->count(); if ($count > 0) { $this->friendlyError('Already have more than zero users in DB.'); return 1; } - $data = ['blocked' => false, 'blocked_code' => null, 'email' => $this->argument('email'), 'role' => 'owner']; - $password = Str::random(24); - $user = $this->repository->store($data); + $data = ['blocked' => false, 'blocked_code' => null, 'email' => $this->argument('email'), 'role' => 'owner']; + $password = Str::random(24); + $user = $this->repository->store($data); $user->password = Hash::make($password); $user->save(); $user->setRememberToken(Str::random(60)); diff --git a/app/Console/Commands/System/ForcesDecimalSize.php b/app/Console/Commands/System/ForcesDecimalSize.php index 75fc51149f..bbd3b6637e 100644 --- a/app/Console/Commands/System/ForcesDecimalSize.php +++ b/app/Console/Commands/System/ForcesDecimalSize.php @@ -68,12 +68,12 @@ class ForcesDecimalSize extends Command 'piggy_bank_repetitions' => PiggyBankRepetition::class, 'piggy_banks' => PiggyBank::class, 'recurrences_transactions' => RecurrenceTransaction::class, - 'transactions' => Transaction::class + 'transactions' => Transaction::class, ]; private string $operator; private string $regularExpression; - private array $tables = [ + private array $tables = [ 'accounts' => ['virtual_balance'], 'auto_budgets' => ['amount'], 'available_budgets' => ['amount'], @@ -85,7 +85,7 @@ class ForcesDecimalSize extends Command 'piggy_bank_repetitions' => ['current_amount'], 'piggy_banks' => ['target_amount'], 'recurrences_transactions' => ['amount', 'foreign_amount'], - 'transactions' => ['amount', 'foreign_amount'] + 'transactions' => ['amount', 'foreign_amount'], ]; /** @@ -115,13 +115,13 @@ class ForcesDecimalSize extends Command private function determineDatabaseType(): void { // switch stuff based on database connection: - $this->operator = 'REGEXP'; + $this->operator = 'REGEXP'; $this->regularExpression = '\'\\\.[\\\d]{%d}[1-9]+\''; - $this->cast = 'CHAR'; + $this->cast = 'CHAR'; if ('pgsql' === config('database.default')) { - $this->operator = 'SIMILAR TO'; + $this->operator = 'SIMILAR TO'; $this->regularExpression = '\'%%\.[\d]{%d}[1-9]+%%\''; - $this->cast = 'TEXT'; + $this->cast = 'TEXT'; } if ('sqlite' === config('database.default')) { $this->regularExpression = '"\.[\d]{%d}[1-9]+"'; @@ -142,7 +142,8 @@ class ForcesDecimalSize extends Command $pattern = trim($pattern, '"'); return mb_ereg($pattern, (string) $value) ? 1 : 0; - }); + }) + ; } if (!in_array((string) config('database.default'), ['mysql', 'pgsql', 'sqlite'], true)) { @@ -239,9 +240,10 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') + $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', json_encode((string) $currency->id)); + ->where('account_meta.data', json_encode((string) $currency->id)) + ; $query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -251,7 +253,7 @@ class ForcesDecimalSize extends Command ); } }); - $result = $query->get(['accounts.*']); + $result = $query->get(['accounts.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code)); @@ -262,13 +264,13 @@ class ForcesDecimalSize extends Command foreach ($result as $account) { /** @var string $field */ foreach ($fields as $field) { - $value = $account->{$field}; + $value = $account->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyInfo(sprintf('Account #%d has %s with value "%s", this has been corrected to "%s".', $account->id, $field, $value, $correct)); /** @var null|Account $updateAccount */ @@ -290,15 +292,16 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = $class::where('transaction_currency_id', $currency->id) + $query = $class::where('transaction_currency_id', $currency->id) ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { /** @var string $field */ foreach ($fields as $field) { $q->orWhere(DB::raw(sprintf('CAST(%s AS %s)', $field, $cast)), $operator, DB::raw(sprintf($regularExpression, $currency->decimal_places))); } - }); + }) + ; - $result = $query->get(); + $result = $query->get(); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code)); @@ -309,7 +312,7 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value || '' === $value) { continue; } @@ -319,7 +322,7 @@ class ForcesDecimalSize extends Command $this->friendlyWarning(sprintf('%s #%d has %s with value "%s", this has been corrected to "%s".', $table, $item->id, $field, $value, $correct)); /** @var null|Model $model */ - $model = $class::find($item->id); + $model = $class::find($item->id); $model?->update([$field => $correct]); } } @@ -335,7 +338,7 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id') + $query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') @@ -348,9 +351,10 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }); + }) + ; - $result = $query->get(['piggy_bank_events.*']); + $result = $query->get(['piggy_bank_events.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy bank events in %s are OK', $currency->code)); @@ -361,7 +365,7 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } @@ -377,7 +381,7 @@ class ForcesDecimalSize extends Command )); /** @var null|PiggyBankEvent $event */ - $event = PiggyBankEvent::find($item->id); + $event = PiggyBankEvent::find($item->id); $event?->update([$field => $correct]); } } @@ -394,7 +398,7 @@ class ForcesDecimalSize extends Command // select all piggy bank repetitions with this currency and issue. /** @var Builder $query */ - $query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id') + $query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') @@ -407,9 +411,10 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }); + }) + ; - $result = $query->get(['piggy_bank_repetitions.*']); + $result = $query->get(['piggy_bank_repetitions.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy bank repetitions in %s', $currency->code)); @@ -420,13 +425,13 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf( 'Piggy bank repetition #%d has %s with value "%s", this has been corrected to "%s".', $item->id, @@ -452,7 +457,7 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') + $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') ->where('account_meta.data', json_encode((string) $currency->id)) @@ -464,9 +469,10 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }); + }) + ; - $result = $query->get(['piggy_banks.*']); + $result = $query->get(['piggy_banks.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code)); @@ -477,13 +483,13 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf('Piggy bank #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct)); /** @var null|PiggyBank $piggyBank */ @@ -500,7 +506,7 @@ class ForcesDecimalSize extends Command { // select all transactions with this currency and issue. /** @var Builder $query */ - $query = Transaction::where('transaction_currency_id', $currency->id)->where( + $query = Transaction::where('transaction_currency_id', $currency->id)->where( DB::raw(sprintf('CAST(amount as %s)', $this->cast)), $this->operator, DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) @@ -513,13 +519,13 @@ class ForcesDecimalSize extends Command /** @var Transaction $item */ foreach ($result as $item) { - $value = $item->amount; + $value = $item->amount; if ('' === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10.0 ** $currency->decimal_places; - $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); + $pow = 10.0 ** $currency->decimal_places; + $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf('Transaction #%d has amount with value "%s", this has been corrected to "%s".', $item->id, $value, $correct)); /** @var null|Transaction $transaction */ @@ -529,7 +535,7 @@ class ForcesDecimalSize extends Command // select all transactions with this FOREIGN currency and issue. /** @var Builder $query */ - $query = Transaction::where('foreign_currency_id', $currency->id)->where( + $query = Transaction::where('foreign_currency_id', $currency->id)->where( DB::raw(sprintf('CAST(foreign_amount as %s)', $this->cast)), $this->operator, DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) @@ -544,13 +550,13 @@ class ForcesDecimalSize extends Command /** @var Transaction $item */ foreach ($result as $item) { - $value = $item->foreign_amount; + $value = $item->foreign_amount; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10.0 ** $currency->decimal_places; - $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); + $pow = 10.0 ** $currency->decimal_places; + $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf( 'Transaction #%d has foreign amount with value "%s", this has been corrected to "%s".', $item->id, diff --git a/app/Console/Commands/System/ForcesMigrations.php b/app/Console/Commands/System/ForcesMigrations.php index 0a913928cc..bbbd6c831a 100644 --- a/app/Console/Commands/System/ForcesMigrations.php +++ b/app/Console/Commands/System/ForcesMigrations.php @@ -40,7 +40,7 @@ class ForcesMigrations extends Command protected $description = 'This command will force-run all database migrations.'; - protected $signature = 'firefly-iii:force-migrations + protected $signature = 'firefly-iii:force-migrations {--user=1 : The user ID.} {--token= : The user\'s access token.}'; diff --git a/app/Console/Commands/System/OutputsInstructions.php b/app/Console/Commands/System/OutputsInstructions.php index c1dfda51a4..8f8c47317a 100644 --- a/app/Console/Commands/System/OutputsInstructions.php +++ b/app/Console/Commands/System/OutputsInstructions.php @@ -37,7 +37,7 @@ class OutputsInstructions extends Command protected $description = 'Instructions in case of upgrade trouble.'; - protected $signature = 'firefly-iii:instructions {task=install}'; + protected $signature = 'firefly-iii:instructions {task=install}'; /** * Execute the console command. @@ -63,8 +63,8 @@ class OutputsInstructions extends Command $version = (string) config('firefly.version'); /** @var array $config */ - $config = config('upgrade.text.upgrade'); - $text = ''; + $config = config('upgrade.text.upgrade'); + $text = ''; /** @var string $compare */ foreach (array_keys($config) as $compare) { @@ -79,7 +79,7 @@ class OutputsInstructions extends Command $text = 'Please set APP_ENV=production for a safer environment.'; } - $prefix = 'v'; + $prefix = 'v'; if (str_starts_with($version, 'develop') || str_starts_with($version, 'branch')) { $prefix = ''; } @@ -116,8 +116,8 @@ class OutputsInstructions extends Command */ private function showLogo(): void { - $today = Carbon::now()->format('m-d'); - $month = Carbon::now()->format('m'); + $today = Carbon::now()->format('m-d'); + $month = Carbon::now()->format('m'); // variation in colors and effects just because I can! // default is Ukraine flag: $colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default']; @@ -166,7 +166,7 @@ class OutputsInstructions extends Command { $parts = explode("\n", wordwrap($text)); foreach ($parts as $string) { - $this->line('| ' . sprintf('%-77s', $string) . '|'); + $this->line('| '.sprintf('%-77s', $string).'|'); } } @@ -177,7 +177,7 @@ class OutputsInstructions extends Command { $parts = explode("\n", wordwrap($text)); foreach ($parts as $string) { - $this->info('| ' . sprintf('%-77s', $string) . '|'); + $this->info('| '.sprintf('%-77s', $string).'|'); } } @@ -196,8 +196,8 @@ class OutputsInstructions extends Command $version = (string) config('firefly.version'); /** @var array $config */ - $config = config('upgrade.text.install'); - $text = ''; + $config = config('upgrade.text.install'); + $text = ''; /** @var string $compare */ foreach (array_keys($config) as $compare) { @@ -212,7 +212,7 @@ class OutputsInstructions extends Command $text = 'Please set APP_ENV=production for a safer environment.'; } - $prefix = 'v'; + $prefix = 'v'; if (str_starts_with($version, 'develop')) { $prefix = ''; } @@ -251,7 +251,7 @@ class OutputsInstructions extends Command '"Be there or forever wonder."', '"A year from now you will wish you had started today."', '🇺🇦 Слава Україні!', - '🇺🇦 Slava Ukraini!' + '🇺🇦 Slava Ukraini!', ]; // fuck the Russian aggression in Ukraine. diff --git a/app/Console/Commands/System/OutputsVersion.php b/app/Console/Commands/System/OutputsVersion.php index 86a523f364..56050f3cd4 100644 --- a/app/Console/Commands/System/OutputsVersion.php +++ b/app/Console/Commands/System/OutputsVersion.php @@ -30,7 +30,7 @@ class OutputsVersion extends Command { protected $description = 'Outputs the Firefly III version'; - protected $signature = 'firefly-iii:output-version'; + protected $signature = 'firefly-iii:output-version'; /** * Execute the console command. diff --git a/app/Console/Commands/System/RecalculatesRunningBalance.php b/app/Console/Commands/System/RecalculatesRunningBalance.php index baa9b2c3d5..d7d94223b6 100644 --- a/app/Console/Commands/System/RecalculatesRunningBalance.php +++ b/app/Console/Commands/System/RecalculatesRunningBalance.php @@ -45,7 +45,7 @@ class RecalculatesRunningBalance extends Command * * @var string */ - protected $signature = 'firefly-iii:refresh-running-balance {--F|force : Force the execution of this command.}'; + protected $signature = 'firefly-iii:refresh-running-balance {--F|force : Force the execution of this command.}'; /** * Execute the console command. diff --git a/app/Console/Commands/System/ResetsErrorMailLimit.php b/app/Console/Commands/System/ResetsErrorMailLimit.php index c13de1d935..15dbda250d 100644 --- a/app/Console/Commands/System/ResetsErrorMailLimit.php +++ b/app/Console/Commands/System/ResetsErrorMailLimit.php @@ -40,7 +40,7 @@ class ResetsErrorMailLimit extends Command * * @var string */ - protected $signature = 'firefly-iii:reset-error-mail-limit'; + protected $signature = 'firefly-iii:reset-error-mail-limit'; /** * The console command description. diff --git a/app/Console/Commands/System/ScansAttachments.php b/app/Console/Commands/System/ScansAttachments.php index 3fbb970cef..0225cf0008 100644 --- a/app/Console/Commands/System/ScansAttachments.php +++ b/app/Console/Commands/System/ScansAttachments.php @@ -46,7 +46,7 @@ class ScansAttachments extends Command protected $description = 'Rescan all attachments and re-set the correct MD5 hash and mime.'; - protected $signature = 'firefly-iii:scan-attachments'; + protected $signature = 'firefly-iii:scan-attachments'; /** * Execute the console command. @@ -76,9 +76,9 @@ class ScansAttachments extends Command Log::error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage())); $decryptedContent = $encryptedContent; } - $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); + $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); file_put_contents($tempFileName, $decryptedContent); - $attachment->md5 = md5_file($tempFileName); + $attachment->md5 = md5_file($tempFileName); $attachment->mime = mime_content_type($tempFileName); $attachment->save(); $this->friendlyInfo(sprintf('Fixed attachment #%d', $attachment->id)); diff --git a/app/Console/Commands/System/SetsLatestVersion.php b/app/Console/Commands/System/SetsLatestVersion.php index 391bb59f30..823f69fec6 100644 --- a/app/Console/Commands/System/SetsLatestVersion.php +++ b/app/Console/Commands/System/SetsLatestVersion.php @@ -34,7 +34,7 @@ class SetsLatestVersion extends Command protected $description = 'Set latest version in DB.'; - protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; + protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; /** * Execute the console command. diff --git a/app/Console/Commands/System/VerifySecurityAlerts.php b/app/Console/Commands/System/VerifySecurityAlerts.php index 568255035a..2872b071b7 100644 --- a/app/Console/Commands/System/VerifySecurityAlerts.php +++ b/app/Console/Commands/System/VerifySecurityAlerts.php @@ -41,7 +41,7 @@ class VerifySecurityAlerts extends Command protected $description = 'Verify security alerts'; - protected $signature = 'firefly-iii:verify-security-alerts'; + protected $signature = 'firefly-iii:verify-security-alerts'; /** * Execute the console command. diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index f7fad16a85..5685ec6593 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -47,7 +47,7 @@ class ApplyRules extends Command protected $description = 'This command will apply your rules and rule groups on a selection of your transactions.'; - protected $signature = 'firefly-iii:apply-rules + protected $signature = 'firefly-iii:apply-rules {--user=1 : The user ID.} {--token= : The user\'s access token.} {--accounts= : A comma-separated list of asset accounts or liabilities to apply your rules to.} @@ -74,7 +74,7 @@ class ApplyRules extends Command */ public function handle(): int { - $start = microtime(true); + $start = microtime(true); $this->stupidLaravel(); if (!$this->verifyAccessToken()) { $this->friendlyError('Invalid access token.'); @@ -86,19 +86,19 @@ class ApplyRules extends Command $this->ruleRepository->setUser($this->getUser()); $this->ruleGroupRepository->setUser($this->getUser()); - $result = $this->verifyInput(); + $result = $this->verifyInput(); if (false === $result) { return 1; } - $this->allRules = $this->option('all_rules'); + $this->allRules = $this->option('all_rules'); // always get all the rules of the user. $this->grabAllRules(); // loop all groups and rules and indicate if they're included: - $rulesToApply = $this->getRulesToApply(); - $count = $rulesToApply->count(); + $rulesToApply = $this->getRulesToApply(); + $count = $rulesToApply->count(); if (0 === $count) { $this->friendlyError('No rules or rule groups have been included.'); $this->friendlyWarning('Make a selection using:'); @@ -111,7 +111,7 @@ class ApplyRules extends Command // create new rule engine: /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules($rulesToApply); $ruleEngine->setUser($this->getUser()); @@ -120,7 +120,7 @@ class ApplyRules extends Command foreach ($this->accounts as $account) { $filterAccountList[] = $account->id; } - $list = implode(',', $filterAccountList); + $list = implode(',', $filterAccountList); $ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]); // add the date as a filter: @@ -134,7 +134,7 @@ class ApplyRules extends Command $ruleEngine->fire(); $this->friendlyLine(''); - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyPositive(sprintf('Done in %s seconds!', $end)); return 0; @@ -147,20 +147,20 @@ class ApplyRules extends Command */ private function stupidLaravel(): void { - $this->allRules = false; - $this->accounts = new Collection(); - $this->ruleSelection = []; - $this->ruleGroupSelection = []; - $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->allRules = false; + $this->accounts = new Collection(); + $this->ruleSelection = []; + $this->ruleGroupSelection = []; + $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->acceptedAccounts = [ + $this->acceptedAccounts = [ AccountTypeEnum::DEFAULT->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]; - $this->groups = new Collection(); + $this->groups = new Collection(); } /** @@ -190,14 +190,14 @@ class ApplyRules extends Command */ private function verifyInputAccounts(): bool { - $accountString = $this->option('accounts'); + $accountString = $this->option('accounts'); if (null === $accountString || '' === $accountString) { $this->friendlyError('Please use the --accounts option to indicate the accounts to apply rules to.'); return false; } - $finalList = new Collection(); - $accountList = explode(',', $accountString); + $finalList = new Collection(); + $accountList = explode(',', $accountString); /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); @@ -209,13 +209,13 @@ class ApplyRules extends Command continue; } - $account = $accountRepository->find($accountId); + $account = $accountRepository->find($accountId); if (null === $account) { $this->friendlyWarning(sprintf('There is no account with ID #%d, it cannot be added.', $accountId)); continue; } - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array($account->accountType->type, $this->acceptedAccounts, true)) { $this->friendlyWarning(sprintf('Account "%s" with ID #%d is of type "%s" and cannot be added.', $account->name, $accountId, $type)); @@ -229,7 +229,7 @@ class ApplyRules extends Command return false; } - $this->accounts = $finalList; + $this->accounts = $finalList; return true; } @@ -241,10 +241,10 @@ class ApplyRules extends Command // can be empty. return true; } - $ruleGroupList = explode(',', $ruleGroupString); + $ruleGroupList = explode(',', $ruleGroupString); foreach ($ruleGroupList as $ruleGroupId) { - $ruleGroupId = (int) $ruleGroupId; + $ruleGroupId = (int) $ruleGroupId; if (0 === $ruleGroupId) { $this->friendlyWarning('You added a rule group with ID 0 (zero). It will be skipped.'); @@ -252,7 +252,7 @@ class ApplyRules extends Command continue; } - $ruleGroup = $this->ruleGroupRepository->find($ruleGroupId); + $ruleGroup = $this->ruleGroupRepository->find($ruleGroupId); if (null === $ruleGroup) { $this->friendlyWarning(sprintf('There is no rule group with ID #%d, this ID will be ignored.', $ruleGroupId)); @@ -277,16 +277,16 @@ class ApplyRules extends Command // can be empty. return true; } - $ruleList = explode(',', $ruleString); + $ruleList = explode(',', $ruleString); foreach ($ruleList as $ruleId) { - $ruleId = (int) $ruleId; + $ruleId = (int) $ruleId; if (0 === $ruleId) { $this->friendlyWarning('You added a rule with ID 0 (zero). It will be skipped.'); continue; } - $rule = $this->ruleRepository->find($ruleId); + $rule = $this->ruleRepository->find($ruleId); if (null === $rule) { $this->friendlyWarning(sprintf('There is no rule with ID #%d, this ID will be ignored.', $ruleId)); @@ -309,13 +309,13 @@ class ApplyRules extends Command private function verifyInputDates(): void { // parse start date. - $inputStart = today(config('app.timezone'))->startOfMonth(); - $startString = $this->option('start_date'); + $inputStart = today(config('app.timezone'))->startOfMonth(); + $startString = $this->option('start_date'); if (null === $startString) { /** @var JournalRepositoryInterface $repository */ $repository = app(JournalRepositoryInterface::class); $repository->setUser($this->getUser()); - $first = $repository->firstNull(); + $first = $repository->firstNull(); if (null !== $first) { $inputStart = $first->date; } @@ -325,8 +325,8 @@ class ApplyRules extends Command } // parse end date - $inputEnd = today(config('app.timezone')); - $endString = $this->option('end_date'); + $inputEnd = today(config('app.timezone')); + $endString = $this->option('end_date'); if (null !== $endString && '' !== $endString) { $inputEnd = Carbon::createFromFormat('Y-m-d', $endString); } @@ -341,7 +341,7 @@ class ApplyRules extends Command } $this->startDate = $inputStart; - $this->endDate = $inputEnd; + $this->endDate = $inputEnd; } private function grabAllRules(): void diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index 46a38852c0..184b6eed5d 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -44,7 +44,7 @@ class Cron extends Command protected $description = 'Runs all Firefly III cron-job related commands. Configure a cron job according to the official Firefly III documentation.'; - protected $signature = 'firefly-iii:cron + protected $signature = 'firefly-iii:cron {--F|force : Force the cron job(s) to execute.} {--date= : Set the date in YYYY-MM-DD to make Firefly III think that\'s the current date.} {--check-version : Check if there is a new Firefly III version. Other tasks will be skipped unless also requested.} @@ -142,7 +142,7 @@ class Cron extends Command return 0; } - private function exchangeRatesCronJob(bool $force, null|Carbon $date): void + private function exchangeRatesCronJob(bool $force, ?Carbon $date): void { Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); $exchangeRates = new ExchangeRatesCronjob(); @@ -185,7 +185,7 @@ class Cron extends Command /** * @throws FireflyException */ - private function recurringCronJob(bool $force, null|Carbon $date): void + private function recurringCronJob(bool $force, ?Carbon $date): void { $recurring = new RecurringCronjob(); $recurring->setForce($force); @@ -207,7 +207,7 @@ class Cron extends Command } } - private function autoBudgetCronJob(bool $force, null|Carbon $date): void + private function autoBudgetCronJob(bool $force, ?Carbon $date): void { $autoBudget = new AutoBudgetCronjob(); $autoBudget->setForce($force); @@ -232,7 +232,7 @@ class Cron extends Command /** * @throws FireflyException */ - private function subscriptionWarningCronJob(bool $force, null|Carbon $date): void + private function subscriptionWarningCronJob(bool $force, ?Carbon $date): void { $subscriptionWarningJob = new BillWarningCronjob(); $subscriptionWarningJob->setForce($force); @@ -254,7 +254,7 @@ class Cron extends Command } } - private function webhookCronJob(bool $force, null|Carbon $date): void + private function webhookCronJob(bool $force, ?Carbon $date): void { $webhook = new WebhookCronjob(); $webhook->setForce($force); diff --git a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php index 5b632c210f..cab149c144 100644 --- a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php +++ b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php @@ -40,8 +40,8 @@ class AddsTransactionIdentifiers extends Command public const string CONFIG_NAME = '480_transaction_identifier'; - protected $description = 'Fixes transaction identifiers.'; - protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}'; + protected $description = 'Fixes transaction identifiers.'; + protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}'; private JournalCLIRepositoryInterface $cliRepository; private int $count; @@ -94,7 +94,7 @@ class AddsTransactionIdentifiers extends Command private function stupidLaravel(): void { $this->cliRepository = app(JournalCLIRepositoryInterface::class); - $this->count = 0; + $this->count = 0; } private function isExecuted(): bool @@ -110,8 +110,8 @@ class AddsTransactionIdentifiers extends Command */ private function updateJournalIdentifiers(TransactionJournal $transactionJournal): void { - $identifier = 0; - $exclude = []; // transactions already processed. + $identifier = 0; + $exclude = []; // transactions already processed. $transactions = $transactionJournal->transactions()->where('amount', '>', 0)->get(); /** @var Transaction $transaction */ @@ -120,18 +120,18 @@ class AddsTransactionIdentifiers extends Command if ($opposing instanceof Transaction) { // give both a new identifier: $transaction->identifier = $identifier; - $opposing->identifier = $identifier; + $opposing->identifier = $identifier; $transaction->save(); $opposing->save(); - $exclude[] = $transaction->id; - $exclude[] = $opposing->id; + $exclude[] = $transaction->id; + $exclude[] = $opposing->id; ++$this->count; } ++$identifier; } } - private function findOpposing(Transaction $transaction, array $exclude): null|Transaction + private function findOpposing(Transaction $transaction, array $exclude): ?Transaction { // find opposing: $amount = bcmul($transaction->amount, '-1'); @@ -142,7 +142,8 @@ class AddsTransactionIdentifiers extends Command ->where('amount', $amount) ->where('identifier', '=', 0) ->whereNotIn('id', $exclude) - ->first(); + ->first() + ; } catch (QueryException $e) { Log::error($e->getMessage()); $this->friendlyError('Firefly III could not find the "identifier" field in the "transactions" table.'); diff --git a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php index 5212a172e2..b410c1fb8f 100644 --- a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php +++ b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php @@ -61,7 +61,7 @@ class RemovesDatabaseDecryption extends Command 'tags' => ['tag', 'description'], 'transaction_journals' => ['description'], 'transactions' => ['description'], - 'journal_links' => ['comment'] + 'journal_links' => ['comment'], ]; /** @@ -119,8 +119,8 @@ class RemovesDatabaseDecryption extends Command if (null === $original) { return; } - $id = (int) $row->id; - $value = ''; + $id = (int) $row->id; + $value = ''; try { $value = $this->tryDecrypt($original); diff --git a/app/Console/Commands/Upgrade/RepairsAccountBalances.php b/app/Console/Commands/Upgrade/RepairsAccountBalances.php index 48f7153a90..8651ccac38 100644 --- a/app/Console/Commands/Upgrade/RepairsAccountBalances.php +++ b/app/Console/Commands/Upgrade/RepairsAccountBalances.php @@ -35,8 +35,8 @@ class RepairsAccountBalances extends Command public const string CONFIG_NAME = '610_correct_balances'; - protected $description = 'Recalculate all account balance amounts'; - protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}'; + protected $description = 'Recalculate all account balance amounts'; + protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}'; public function handle(): int { diff --git a/app/Console/Commands/Upgrade/RepairsPostgresSequences.php b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php index ecd442868d..8b545364fc 100644 --- a/app/Console/Commands/Upgrade/RepairsPostgresSequences.php +++ b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php @@ -34,7 +34,7 @@ class RepairsPostgresSequences extends Command protected $description = 'Fixes issues with PostgreSQL sequences.'; - protected $signature = 'upgrade:600-pgsql-sequences'; + protected $signature = 'upgrade:600-pgsql-sequences'; /** * Execute the console command. @@ -100,7 +100,7 @@ class RepairsPostgresSequences extends Command 'users', 'webhook_attempts', 'webhook_messages', - 'webhooks' + 'webhooks', ]; foreach ($tablesToCheck as $tableToCheck) { diff --git a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php index 89b09dc56a..dfed8b1d1c 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php @@ -44,8 +44,8 @@ class UpgradesAccountCurrencies extends Command public const string CONFIG_NAME = '480_account_currencies'; - protected $description = 'Give all accounts proper currency info.'; - protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}'; + protected $description = 'Give all accounts proper currency info.'; + protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}'; private AccountRepositoryInterface $accountRepos; private int $count; private UserRepositoryInterface $userRepos; @@ -81,8 +81,8 @@ class UpgradesAccountCurrencies extends Command private function stupidLaravel(): void { $this->accountRepos = app(AccountRepositoryInterface::class); - $this->userRepos = app(UserRepositoryInterface::class); - $this->count = 0; + $this->userRepos = app(UserRepositoryInterface::class); + $this->count = 0; } private function isExecuted(): bool @@ -103,7 +103,7 @@ class UpgradesAccountCurrencies extends Command private function updateCurrenciesForUser(User $user): void { $this->accountRepos->setUser($user); - $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]); + $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]); // get user's currency preference: $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); diff --git a/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php index bd00983bb3..0aedf414a1 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php @@ -36,9 +36,9 @@ class UpgradesAccountMetaData extends Command public const string CONFIG_NAME = '480_rename_account_meta'; - protected $description = 'Rename account meta-data to new format.'; + protected $description = 'Rename account meta-data to new format.'; - protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -57,7 +57,7 @@ class UpgradesAccountMetaData extends Command 'accountRole' => 'account_role', 'ccType' => 'cc_type', 'accountNumber' => 'account_number', - 'ccMonthlyPaymentDate' => 'cc_monthly_payment_date' + 'ccMonthlyPaymentDate' => 'cc_monthly_payment_date', ]; $count = 0; diff --git a/app/Console/Commands/Upgrade/UpgradesAttachments.php b/app/Console/Commands/Upgrade/UpgradesAttachments.php index 50032f5c66..538f62f23b 100644 --- a/app/Console/Commands/Upgrade/UpgradesAttachments.php +++ b/app/Console/Commands/Upgrade/UpgradesAttachments.php @@ -38,9 +38,9 @@ class UpgradesAttachments extends Command public const string CONFIG_NAME = '480_migrate_attachments'; - protected $description = 'Migrates attachment meta-data.'; + protected $description = 'Migrates attachment meta-data.'; - protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -49,7 +49,7 @@ class UpgradesAttachments extends Command */ public function handle(): int { - $start = microtime(true); + $start = microtime(true); if ($this->isExecuted() && true !== $this->option('force')) { $this->friendlyInfo('This command has already been executed.'); @@ -65,12 +65,12 @@ class UpgradesAttachments extends Command $attDescription = (string) $att->description; if ('' !== $attDescription) { // find or create note: - $note = $att->notes()->first(); + $note = $att->notes()->first(); if (null === $note) { $note = new Note(); $note->noteable()->associate($att); } - $note->text = $attDescription; + $note->text = $attDescription; $note->save(); // clear description: @@ -84,7 +84,7 @@ class UpgradesAttachments extends Command if (0 !== $count) { $this->friendlyInfo(sprintf('Updated %d attachment(s).', $count)); } - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyInfo(sprintf('Migrated attachment notes in %s seconds.', $end)); $this->markAsExecuted(); diff --git a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php index 05c6975bab..22dd1a67ec 100644 --- a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php +++ b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php @@ -44,9 +44,9 @@ class UpgradesBillsToRules extends Command public const string CONFIG_NAME = '480_bills_to_rules'; - protected $description = 'Migrate bills to rules.'; + protected $description = 'Migrate bills to rules.'; - protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}'; private BillRepositoryInterface $billRepository; private int $count; private RuleGroupRepositoryInterface $ruleGroupRepository; @@ -91,11 +91,11 @@ class UpgradesBillsToRules extends Command */ private function stupidLaravel(): void { - $this->count = 0; - $this->userRepository = app(UserRepositoryInterface::class); + $this->count = 0; + $this->userRepository = app(UserRepositoryInterface::class); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->ruleRepository = app(RuleRepositoryInterface::class); } private function isExecuted(): bool @@ -124,10 +124,10 @@ class UpgradesBillsToRules extends Command $ruleGroup = $this->ruleGroupRepository->store([ 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language), 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $language), - 'active' => true + 'active' => true, ]); } - $bills = $this->billRepository->getBills(); + $bills = $this->billRepository->getBills(); /** @var Bill $bill */ foreach ($bills as $bill) { @@ -143,17 +143,17 @@ class UpgradesBillsToRules extends Command $languageString = null !== $language->data && !is_array($language->data) ? (string) $language->data : 'en_US'; // get match thing: - $match = implode(' ', explode(',', $bill->match)); - $newRule = [ + $match = implode(' ', explode(',', $bill->match)); + $newRule = [ 'rule_group_id' => $ruleGroup->id, 'active' => true, 'strict' => false, 'stop_processing' => false, // field is no longer used. - 'title' => (string) trans('firefly.rule_for_bill_title', ['name' => $bill->name], $languageString), - 'description' => (string) trans('firefly.rule_for_bill_description', ['name' => $bill->name], $languageString), - 'trigger' => 'store-journal', - 'triggers' => [['type' => 'description_contains', 'value' => $match]], - 'actions' => [['type' => 'link_to_bill', 'value' => $bill->name]] + 'title' => (string) trans('firefly.rule_for_bill_title', ['name' => $bill->name], $languageString), + 'description' => (string) trans('firefly.rule_for_bill_description', ['name' => $bill->name], $languageString), + 'trigger' => 'store-journal', + 'triggers' => [['type' => 'description_contains', 'value' => $match]], + 'actions' => [['type' => 'link_to_bill', 'value' => $bill->name]], ]; // two triggers or one, depends on bill content: @@ -168,7 +168,7 @@ class UpgradesBillsToRules extends Command $this->ruleRepository->store($newRule); // update bill: - $newBillData = [ + $newBillData = [ 'currency_id' => $bill->transaction_currency_id, 'name' => $bill->name, 'match' => 'MIGRATED_TO_RULES', @@ -177,7 +177,7 @@ class UpgradesBillsToRules extends Command 'date' => $bill->date, 'repeat_freq' => $bill->repeat_freq, 'skip' => $bill->skip, - 'active' => $bill->active + 'active' => $bill->active, ]; $this->billRepository->update($bill, $newBillData); ++$this->count; diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php index f55742ed47..4c1327760c 100644 --- a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php +++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php @@ -36,9 +36,9 @@ class UpgradesBudgetLimitPeriods extends Command public const string CONFIG_NAME = '550_budget_limit_periods'; - protected $description = 'Append budget limits with their (estimated) timeframe.'; + protected $description = 'Append budget limits with their (estimated) timeframe.'; - protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -76,7 +76,7 @@ class UpgradesBudgetLimitPeriods extends Command private function fixLimit(BudgetLimit $limit): void { - $period = $this->getLimitPeriod($limit); + $period = $this->getLimitPeriod($limit); if (null === $period) { $message = sprintf( @@ -93,7 +93,7 @@ class UpgradesBudgetLimitPeriods extends Command $limit->period = $period; $limit->save(); - $msg = sprintf( + $msg = sprintf( 'Budget limit #%d (%s - %s) period is "%s".', $limit->id, $limit->start_date->format('Y-m-d'), @@ -103,7 +103,7 @@ class UpgradesBudgetLimitPeriods extends Command Log::debug($msg); } - private function getLimitPeriod(BudgetLimit $limit): null|string + private function getLimitPeriod(BudgetLimit $limit): ?string { // is daily if ($limit->end_date->isSameDay($limit->start_date)) { diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php index 5e95ff7a76..e85705c3a2 100644 --- a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php +++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php @@ -39,9 +39,9 @@ class UpgradesBudgetLimits extends Command public const string CONFIG_NAME = '480_bl_currency'; - protected $description = 'Give budget limits a currency'; + protected $description = 'Give budget limits a currency'; - protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -68,7 +68,7 @@ class UpgradesBudgetLimits extends Command /** @var null|User $user */ $user = $budget->user; if (null !== $user) { - $currency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $currency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); $budgetLimit->transaction_currency_id = $currency->id; $budgetLimit->save(); $this->friendlyInfo(sprintf( diff --git a/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php index 1d74564b6f..ca34b5256a 100644 --- a/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php @@ -39,8 +39,8 @@ class UpgradesCreditCardLiabilities extends Command public const string CONFIG_NAME = '480_cc_liabilities'; - protected $description = 'Convert old credit card liabilities.'; - protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}'; + protected $description = 'Convert old credit card liabilities.'; + protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. diff --git a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php index 4aaef02fea..4a6affcd3d 100644 --- a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php +++ b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php @@ -41,9 +41,9 @@ class UpgradesCurrencyPreferences extends Command public const string CONFIG_NAME = '610_upgrade_currency_prefs'; - protected $description = 'Upgrade user currency preferences'; + protected $description = 'Upgrade user currency preferences'; - protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -80,7 +80,7 @@ class UpgradesCurrencyPreferences extends Command $this->upgradeGroupPreferences($group); } - $users = User::get(); + $users = User::get(); /** @var User $user */ foreach ($users as $user) { @@ -131,7 +131,8 @@ class UpgradesCurrencyPreferences extends Command { $preference = Preference::where('user_id', $user->id) ->where('name', 'currencyPreference') - ->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at']); + ->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at']) + ; if (null === $preference) { return 'EUR'; diff --git a/app/Console/Commands/Upgrade/UpgradesDatabase.php b/app/Console/Commands/Upgrade/UpgradesDatabase.php index e9476c4322..5d34881400 100644 --- a/app/Console/Commands/Upgrade/UpgradesDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradesDatabase.php @@ -76,7 +76,7 @@ class UpgradesDatabase extends Command 'upgrade:620-piggy-banks', 'upgrade:620-pc-amounts', 'upgrade:640-upgrade-webhooks', - 'firefly-iii:correct-database' + 'firefly-iii:correct-database', ]; $args = []; if ($this->option('force')) { diff --git a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php index 3bf810cd00..96696feb35 100644 --- a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php @@ -40,9 +40,9 @@ class UpgradesJournalMetaData extends Command public const string CONFIG_NAME = '480_back_to_journals'; - protected $description = 'Move meta data back to journals, not individual transactions.'; + protected $description = 'Move meta data back to journals, not individual transactions.'; - protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -113,7 +113,8 @@ class UpgradesJournalMetaData extends Command $transactions = DB::table('budget_transaction') ->distinct() ->pluck('transaction_id') - ->toArray(); + ->toArray() + ; $array = []; $chunks = array_chunk($transactions, 500); @@ -121,7 +122,8 @@ class UpgradesJournalMetaData extends Command $set = DB::table('transactions') ->whereIn('transactions.id', $chunk) ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $array = array_merge($array, $set); } @@ -132,7 +134,7 @@ class UpgradesJournalMetaData extends Command { // grab category from first transaction /** @var null|Transaction $transaction */ - $transaction = $journal->transactions->first(); + $transaction = $journal->transactions->first(); if (null === $transaction) { $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); @@ -140,7 +142,7 @@ class UpgradesJournalMetaData extends Command } /** @var null|Budget $budget */ - $budget = $transaction->budgets->first(); + $budget = $transaction->budgets->first(); /** @var null|Budget $journalBudget */ $journalBudget = $journal->budgets->first(); @@ -165,7 +167,7 @@ class UpgradesJournalMetaData extends Command $journals = new Collection(); $allIds = $this->getIdsForCategories(); - $chunks = array_chunk($allIds, 500); + $chunks = array_chunk($allIds, 500); foreach ($chunks as $chunk) { $collected = TransactionJournal::whereIn('id', $chunk)->with(['transactions', 'categories', 'transactions.categories'])->get(); $journals = $journals->merge($collected); @@ -182,7 +184,8 @@ class UpgradesJournalMetaData extends Command $transactions = DB::table('category_transaction') ->distinct() ->pluck('transaction_id') - ->toArray(); + ->toArray() + ; $array = []; $chunks = array_chunk($transactions, 500); @@ -190,7 +193,8 @@ class UpgradesJournalMetaData extends Command $set = DB::table('transactions') ->whereIn('transactions.id', $chunk) ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $array = array_merge($array, $set); } @@ -201,7 +205,7 @@ class UpgradesJournalMetaData extends Command { // grab category from first transaction /** @var null|Transaction $transaction */ - $transaction = $journal->transactions->first(); + $transaction = $journal->transactions->first(); if (null === $transaction) { $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); @@ -209,7 +213,7 @@ class UpgradesJournalMetaData extends Command } /** @var null|Category $category */ - $category = $transaction->categories->first(); + $category = $transaction->categories->first(); /** @var null|Category $journalCategory */ $journalCategory = $journal->categories->first(); diff --git a/app/Console/Commands/Upgrade/UpgradesJournalNotes.php b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php index fde7316d81..7d043c9ef2 100644 --- a/app/Console/Commands/Upgrade/UpgradesJournalNotes.php +++ b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php @@ -37,9 +37,9 @@ class UpgradesJournalNotes extends Command public const string CONFIG_NAME = '480_migrate_notes'; - protected $description = 'Migrate notes for transaction journals.'; + protected $description = 'Migrate notes for transaction journals.'; - protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -59,8 +59,8 @@ class UpgradesJournalNotes extends Command /** @var TransactionJournalMeta $meta */ foreach ($set as $meta) { - $journal = $meta->transactionJournal; - $note = $journal->notes()->first(); + $journal = $meta->transactionJournal; + $note = $journal->notes()->first(); if (null === $note) { $note = new Note(); $note->noteable()->associate($journal); @@ -78,7 +78,7 @@ class UpgradesJournalNotes extends Command $this->friendlyInfo(sprintf('Migrated %d note(s).', $count)); } - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyInfo(sprintf('Migrated notes in %s seconds.', $end)); $this->markAsExecuted(); diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilities.php b/app/Console/Commands/Upgrade/UpgradesLiabilities.php index fd1b91307f..0ead19729b 100644 --- a/app/Console/Commands/Upgrade/UpgradesLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradesLiabilities.php @@ -41,8 +41,8 @@ class UpgradesLiabilities extends Command public const string CONFIG_NAME = '560_upgrade_liabilities'; - protected $description = 'Upgrade liabilities to new 5.6.0 structure.'; - protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}'; + protected $description = 'Upgrade liabilities to new 5.6.0 structure.'; + protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -84,7 +84,8 @@ class UpgradesLiabilities extends Command ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('account_types.type', config('firefly.valid_liabilities')) - ->get(['accounts.*']); + ->get(['accounts.*']) + ; /** @var Account $account */ foreach ($accounts as $account) { @@ -98,7 +99,7 @@ class UpgradesLiabilities extends Command private function upgradeLiability(Account $account): void { /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); // get opening balance, and correct if necessary. @@ -109,7 +110,7 @@ class UpgradesLiabilities extends Command } // add liability direction property (if it does not yet exist!) - $value = $repository->getMetaValue($account, 'liability_direction'); + $value = $repository->getMetaValue($account, 'liability_direction'); if (null === $value) { /** @var AccountMetaFactory $factory */ $factory = app(AccountMetaFactory::class); @@ -127,21 +128,21 @@ class UpgradesLiabilities extends Command // source MUST be the liability. if ($destination->account_id === $account->id) { // so if not, switch things around: - $sourceAccountId = $source->account_id; - $source->account_id = $destination->account_id; + $sourceAccountId = $source->account_id; + $source->account_id = $destination->account_id; $destination->account_id = $sourceAccountId; $source->save(); $destination->save(); } } - private function getSourceTransaction(TransactionJournal $journal): null|Transaction + private function getSourceTransaction(TransactionJournal $journal): ?Transaction { /** @var null|Transaction */ return $journal->transactions()->where('amount', '<', 0)->first(); } - private function getDestinationTransaction(TransactionJournal $journal): null|Transaction + private function getDestinationTransaction(TransactionJournal $journal): ?Transaction { /** @var null|Transaction */ return $journal->transactions()->where('amount', '>', 0)->first(); diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php index f3589195d5..7efa427a11 100644 --- a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php +++ b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php @@ -44,8 +44,8 @@ class UpgradesLiabilitiesEight extends Command public const string CONFIG_NAME = '600_upgrade_liabilities'; - protected $description = 'Upgrade liabilities to new 6.0.0 structure.'; - protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}'; + protected $description = 'Upgrade liabilities to new 6.0.0 structure.'; + protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -86,7 +86,8 @@ class UpgradesLiabilitiesEight extends Command ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('account_types.type', config('firefly.valid_liabilities')) - ->get(['accounts.*']); + ->get(['accounts.*']) + ; /** @var Account $account */ foreach ($accounts as $account) { @@ -103,7 +104,7 @@ class UpgradesLiabilitiesEight extends Command $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); - $direction = $repository->getMetaValue($account, 'liability_direction'); + $direction = $repository->getMetaValue($account, 'liability_direction'); if ('credit' === $direction && $this->hasBadOpening($account)) { $this->deleteCreditTransaction($account); $this->reverseOpeningBalance($account); @@ -124,14 +125,16 @@ class UpgradesLiabilitiesEight extends Command $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $openingBalanceType->id) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; if (null === $openingJournal) { return false; } - $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $liabilityType->id) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; if (null === $liabilityJournal) { return false; } @@ -145,7 +148,8 @@ class UpgradesLiabilitiesEight extends Command $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $liabilityType->id) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; if (null !== $liabilityJournal && null !== $liabilityJournal->transactionGroup) { $group = $liabilityJournal->transactionGroup; $service = new TransactionGroupDestroyService(); @@ -158,20 +162,21 @@ class UpgradesLiabilitiesEight extends Command $openingBalanceType = TransactionType::whereType(TransactionTypeEnum::OPENING_BALANCE->value)->first(); /** @var TransactionJournal $openingJournal */ - $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $openingBalanceType->id) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; /** @var null|Transaction $source */ - $source = $openingJournal->transactions()->where('amount', '<', 0)->first(); + $source = $openingJournal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $dest */ - $dest = $openingJournal->transactions()->where('amount', '>', 0)->first(); + $dest = $openingJournal->transactions()->where('amount', '>', 0)->first(); if (null !== $source && null !== $dest) { - $sourceId = $source->account_id; - $destId = $dest->account_id; - $dest->account_id = $sourceId; + $sourceId = $source->account_id; + $destId = $dest->account_id; + $dest->account_id = $sourceId; $source->account_id = $destId; $source->save(); $dest->save(); @@ -189,7 +194,7 @@ class UpgradesLiabilitiesEight extends Command $account->id )->get(['transaction_journals.*']); - $service = app(TransactionGroupDestroyService::class); + $service = app(TransactionGroupDestroyService::class); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { diff --git a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php index 69d05194ab..60ee70b36c 100644 --- a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php +++ b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php @@ -39,9 +39,9 @@ class UpgradesMultiPiggyBanks extends Command public const string CONFIG_NAME = '620_make_multi_piggies'; - protected $description = 'Upgrade piggy banks so they can use multiple accounts.'; + protected $description = 'Upgrade piggy banks so they can use multiple accounts.'; - protected $signature = 'upgrade:620-piggy-banks {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:620-piggy-banks {--F|force : Force the execution of this command.}'; private AccountRepositoryInterface $accountRepository; private PiggyBankRepositoryInterface $repository; @@ -72,9 +72,9 @@ class UpgradesMultiPiggyBanks extends Command private function upgradePiggyBanks(): void { - $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository = app(PiggyBankRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); - $set = PiggyBank::whereNotNull('account_id')->get(); + $set = PiggyBank::whereNotNull('account_id')->get(); Log::debug(sprintf('Will update %d piggy banks(s).', $set->count())); /** @var PiggyBank $piggyBank */ @@ -93,8 +93,8 @@ class UpgradesMultiPiggyBanks extends Command } $this->repository->setUser($piggyBank->account->user); $this->accountRepository->setUser($piggyBank->account->user); - $repetition = $this->repository->getRepetition($piggyBank, true); - $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? Amount::getPrimaryCurrencyByUserGroup($piggyBank->account->user->userGroup); + $repetition = $this->repository->getRepetition($piggyBank, true); + $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? Amount::getPrimaryCurrencyByUserGroup($piggyBank->account->user->userGroup); // update piggy bank to have a currency. $piggyBank->transaction_currency_id = $currency->id; @@ -102,7 +102,7 @@ class UpgradesMultiPiggyBanks extends Command // store current amount in account association. $piggyBank->accounts()->sync([$piggyBank->account->id => ['current_amount' => $repetition->current_amount]]); - $piggyBank->account_id = null; + $piggyBank->account_id = null; $piggyBank->saveQuietly(); // remove all repetitions (no longer used) diff --git a/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php index 8c8283ff69..ff8ed340d6 100644 --- a/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php +++ b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php @@ -35,9 +35,9 @@ class UpgradesPrimaryCurrencyAmounts extends Command public const string CONFIG_NAME = '620_pc_amounts'; - protected $description = 'Runs the primary currency amounts calculations.'; + protected $description = 'Runs the primary currency amounts calculations.'; - protected $signature = 'upgrade:620-pc-amounts {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:620-pc-amounts {--F|force : Force the execution of this command.}'; /** * Execute the console command. diff --git a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php index 7bea6084c9..c000d3b646 100644 --- a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php @@ -39,9 +39,9 @@ class UpgradesRecurrenceMetaData extends Command public const string CONFIG_NAME = '481_migrate_recurrence_meta'; - protected $description = 'Migrate recurrence meta data'; + protected $description = 'Migrate recurrence meta data'; - protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -73,7 +73,7 @@ class UpgradesRecurrenceMetaData extends Command private function migrateMetaData(): int { - $count = 0; + $count = 0; // get all recurrence meta data: $collection = RecurrenceMeta::with('recurrence')->get(); @@ -88,7 +88,7 @@ class UpgradesRecurrenceMetaData extends Command private function migrateEntry(RecurrenceMeta $meta): int { /** @var null|Recurrence $recurrence */ - $recurrence = $meta->recurrence; + $recurrence = $meta->recurrence; if (null === $recurrence) { return 0; } @@ -96,7 +96,7 @@ class UpgradesRecurrenceMetaData extends Command if (null === $firstTransaction) { return 0; } - $value = $meta->value; + $value = $meta->value; if ('tags' === $meta->name) { $array = explode(',', $meta->value); diff --git a/app/Console/Commands/Upgrade/UpgradesRuleActions.php b/app/Console/Commands/Upgrade/UpgradesRuleActions.php index c5c7a7019c..0e74393759 100644 --- a/app/Console/Commands/Upgrade/UpgradesRuleActions.php +++ b/app/Console/Commands/Upgrade/UpgradesRuleActions.php @@ -35,9 +35,9 @@ class UpgradesRuleActions extends Command public const string CONFIG_NAME = '610_migrate_rule_actions'; - protected $description = 'Migrate rule actions away from expression engine'; + protected $description = 'Migrate rule actions away from expression engine'; - protected $signature = 'upgrade:600-rule-actions {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:600-rule-actions {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -99,7 +99,7 @@ class UpgradesRuleActions extends Command 'append_descr_to_notes', 'append_notes_to_descr', 'move_descr_to_notes', - 'move_notes_to_descr' + 'move_notes_to_descr', ]; $actions = RuleAction::whereIn('action_type', $obsolete)->get(); @@ -114,7 +114,7 @@ class UpgradesRuleActions extends Command break; case 'append_description': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = sprintf('=description~"%s"', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -122,7 +122,7 @@ class UpgradesRuleActions extends Command break; case 'prepend_description': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = sprintf('="%s"~description', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -130,7 +130,7 @@ class UpgradesRuleActions extends Command break; case 'append_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = sprintf('=notes~"%s"', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -138,7 +138,7 @@ class UpgradesRuleActions extends Command break; case 'prepend_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = sprintf('="%s"~notes', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -146,7 +146,7 @@ class UpgradesRuleActions extends Command break; case 'append_descr_to_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = '=notes~" "~description'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -154,7 +154,7 @@ class UpgradesRuleActions extends Command break; case 'append_notes_to_descr': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = '=description~" "~notes'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -162,7 +162,7 @@ class UpgradesRuleActions extends Command break; case 'move_descr_to_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = '=description'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -170,7 +170,7 @@ class UpgradesRuleActions extends Command break; case 'move_notes_to_descr': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = '=notes'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); diff --git a/app/Console/Commands/Upgrade/UpgradesTagLocations.php b/app/Console/Commands/Upgrade/UpgradesTagLocations.php index 94b49f4811..45a5b9e0a5 100644 --- a/app/Console/Commands/Upgrade/UpgradesTagLocations.php +++ b/app/Console/Commands/Upgrade/UpgradesTagLocations.php @@ -36,9 +36,9 @@ class UpgradesTagLocations extends Command public const string CONFIG_NAME = '500_migrate_tag_locations'; - protected $description = 'Migrate tag locations.'; + protected $description = 'Migrate tag locations.'; - protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -82,16 +82,16 @@ class UpgradesTagLocations extends Command private function migrateLocationDetails(Tag $tag): void { - $location = new Location(); - $location->longitude = $tag->longitude; - $location->latitude = $tag->latitude; + $location = new Location(); + $location->longitude = $tag->longitude; + $location->latitude = $tag->latitude; $location->zoom_level = $tag->zoomLevel; $location->locatable()->associate($tag); $location->save(); - $tag->longitude = null; - $tag->latitude = null; - $tag->zoomLevel = null; + $tag->longitude = null; + $tag->latitude = null; + $tag->zoomLevel = null; $tag->save(); } diff --git a/app/Console/Commands/Upgrade/UpgradesToGroups.php b/app/Console/Commands/Upgrade/UpgradesToGroups.php index d8d9104cd1..1b2a1acccf 100644 --- a/app/Console/Commands/Upgrade/UpgradesToGroups.php +++ b/app/Console/Commands/Upgrade/UpgradesToGroups.php @@ -47,8 +47,8 @@ class UpgradesToGroups extends Command public const string CONFIG_NAME = '480_migrated_to_groups'; - protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.'; - protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; + protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.'; + protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; private JournalCLIRepositoryInterface $cliRepository; private int $count; private TransactionGroupFactory $groupFactory; @@ -90,11 +90,11 @@ class UpgradesToGroups extends Command */ private function stupidLaravel(): void { - $this->count = 0; + $this->count = 0; $this->journalRepository = app(JournalRepositoryInterface::class); - $this->service = app(JournalDestroyService::class); - $this->groupFactory = app(TransactionGroupFactory::class); - $this->cliRepository = app(JournalCLIRepositoryInterface::class); + $this->service = app(JournalDestroyService::class); + $this->groupFactory = app(TransactionGroupFactory::class); + $this->cliRepository = app(JournalCLIRepositoryInterface::class); } private function isMigrated(): bool @@ -140,7 +140,7 @@ class UpgradesToGroups extends Command $data = [ // mandatory fields. 'group_title' => $journal->description, - 'transactions' => [] + 'transactions' => [], ]; $destTransactions = $this->getDestinationTransactions($journal); @@ -151,7 +151,7 @@ class UpgradesToGroups extends Command $data['transactions'][] = $this->generateTransaction($journal, $transaction); } Log::debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions']))); - $group = $this->groupFactory->create($data); + $group = $this->groupFactory->create($data); Log::debug('Done calling transaction journal factory'); // delete the old transaction journal. @@ -176,7 +176,7 @@ class UpgradesToGroups extends Command private function getDestinationTransactions(TransactionJournal $journal): Collection { - return $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount > 0); + return $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0); } /** @@ -185,7 +185,7 @@ class UpgradesToGroups extends Command private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array { Log::debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id)); - $opposingTr = $this->findOpposingTransaction($journal, $transaction); + $opposingTr = $this->findOpposingTransaction($journal, $transaction); if (!$opposingTr instanceof Transaction) { $this->friendlyError(sprintf( @@ -224,8 +224,8 @@ class UpgradesToGroups extends Command $invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date'); // overrule journal category with transaction category. - $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; - $categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId; + $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; + $categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId; return [ 'type' => strtolower((string) $journal->transactionType->type), @@ -264,14 +264,14 @@ class UpgradesToGroups extends Command 'process_date' => $processDate, 'due_date' => $dueDate, 'payment_date' => $paymentDate, - 'invoice_date' => $invoiceDate + 'invoice_date' => $invoiceDate, ]; } - private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): null|Transaction + private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): ?Transaction { $set = $journal->transactions->filter(static function (Transaction $subject) use ($transaction): bool { - $amount = ((float) $transaction->amount * -1) === (float) $subject->amount; // intentional float + $amount = ((float) $transaction->amount * -1) === (float) $subject->amount; // intentional float $identifier = $transaction->identifier === $subject->identifier; Log::debug(sprintf('Amount the same? %s', var_export($amount, true))); Log::debug(sprintf('ID the same? %s', var_export($identifier, true))); @@ -282,7 +282,7 @@ class UpgradesToGroups extends Command return $set->first(); } - private function getTransactionBudget(Transaction $left, Transaction $right): null|int + private function getTransactionBudget(Transaction $left, Transaction $right): ?int { Log::debug('Now in getTransactionBudget()'); @@ -309,7 +309,7 @@ class UpgradesToGroups extends Command return null; } - private function getTransactionCategory(Transaction $left, Transaction $right): null|int + private function getTransactionCategory(Transaction $left, Transaction $right): ?int { Log::debug('Now in getTransactionCategory()'); @@ -360,7 +360,7 @@ class UpgradesToGroups extends Command 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), 'title' => null, - 'user_id' => $array['user_id'] + 'user_id' => $array['user_id'], ]); DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]); ++$this->count; diff --git a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php index b0943475cf..463e9355a3 100644 --- a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php @@ -40,21 +40,21 @@ class UpgradesTransferCurrencies extends Command { use ShowsFriendlyMessages; - public const string CONFIG_NAME = '480_transfer_currencies'; + public const string CONFIG_NAME = '480_transfer_currencies'; - protected $description = 'Updates transfer currency information.'; - protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}'; + protected $description = 'Updates transfer currency information.'; + protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}'; private array $accountCurrencies; private AccountRepositoryInterface $accountRepos; private JournalCLIRepositoryInterface $cliRepos; private int $count; - private null|Account $destinationAccount = null; - private null|TransactionCurrency $destinationCurrency = null; - private null|Transaction $destinationTransaction = null; - private null|Account $sourceAccount = null; - private null|TransactionCurrency $sourceCurrency = null; - private null|Transaction $sourceTransaction = null; + private ?Account $destinationAccount = null; + private ?TransactionCurrency $destinationCurrency = null; + private ?Transaction $destinationTransaction = null; + private ?Account $sourceAccount = null; + private ?TransactionCurrency $sourceCurrency = null; + private ?Transaction $sourceTransaction = null; /** * Execute the console command. @@ -85,9 +85,9 @@ class UpgradesTransferCurrencies extends Command */ private function stupidLaravel(): void { - $this->count = 0; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); + $this->count = 0; + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); $this->accountCurrencies = []; $this->resetInformation(); } @@ -97,12 +97,12 @@ class UpgradesTransferCurrencies extends Command */ private function resetInformation(): void { - $this->sourceTransaction = null; - $this->sourceAccount = null; - $this->sourceCurrency = null; + $this->sourceTransaction = null; + $this->sourceAccount = null; + $this->sourceCurrency = null; $this->destinationTransaction = null; - $this->destinationAccount = null; - $this->destinationCurrency = null; + $this->destinationAccount = null; + $this->destinationCurrency = null; } private function isExecuted(): bool @@ -202,26 +202,26 @@ class UpgradesTransferCurrencies extends Command private function getSourceInformation(TransactionJournal $journal): void { $this->sourceTransaction = $this->getSourceTransaction($journal); - $this->sourceAccount = $this->sourceTransaction?->account; - $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null; + $this->sourceAccount = $this->sourceTransaction?->account; + $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null; } - private function getSourceTransaction(TransactionJournal $transfer): null|Transaction + private function getSourceTransaction(TransactionJournal $transfer): ?Transaction { /** @var null|Transaction */ return $transfer->transactions()->where('amount', '<', 0)->first(); } - private function getCurrency(Account $account): null|TransactionCurrency + private function getCurrency(Account $account): ?TransactionCurrency { - $accountId = $account->id; + $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { return $this->accountCurrencies[$accountId]; } - $currency = $this->accountRepos->getAccountCurrency($account); + $currency = $this->accountRepos->getAccountCurrency($account); if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; @@ -238,11 +238,11 @@ class UpgradesTransferCurrencies extends Command private function getDestinationInformation(TransactionJournal $journal): void { $this->destinationTransaction = $this->getDestinationTransaction($journal); - $this->destinationAccount = $this->destinationTransaction?->account; - $this->destinationCurrency = $this->destinationAccount instanceof Account ? $this->getCurrency($this->destinationAccount) : null; + $this->destinationAccount = $this->destinationTransaction?->account; + $this->destinationCurrency = $this->destinationAccount instanceof Account ? $this->getCurrency($this->destinationAccount) : null; } - private function getDestinationTransaction(TransactionJournal $transfer): null|Transaction + private function getDestinationTransaction(TransactionJournal $transfer): ?Transaction { /** @var null|Transaction */ return $transfer->transactions()->where('amount', '>', 0)->first(); @@ -253,12 +253,11 @@ class UpgradesTransferCurrencies extends Command */ private function isEmptyTransactions(): bool { - return ( + return !$this->sourceTransaction instanceof Transaction || !$this->destinationTransaction instanceof Transaction || !$this->sourceAccount instanceof Account - || !$this->destinationAccount instanceof Account - ); + || !$this->destinationAccount instanceof Account; } private function isNoCurrencyPresent(): bool @@ -296,7 +295,7 @@ class UpgradesTransferCurrencies extends Command { if (null === $this->sourceTransaction->transaction_currency_id && $this->sourceCurrency instanceof TransactionCurrency) { $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; - $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->sourceTransaction->id, $this->sourceCurrency->code); + $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->sourceTransaction->id, $this->sourceCurrency->code); $this->friendlyInfo($message); ++$this->count; $this->sourceTransaction->save(); @@ -314,7 +313,7 @@ class UpgradesTransferCurrencies extends Command && null === $this->sourceTransaction->foreign_amount && (int) $this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id ) { - $message = sprintf( + $message = sprintf( 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', $this->sourceTransaction->id, $this->sourceTransaction->transaction_currency_id, @@ -336,7 +335,7 @@ class UpgradesTransferCurrencies extends Command { if (null === $this->destinationTransaction->transaction_currency_id && $this->destinationCurrency instanceof TransactionCurrency) { $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id; - $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->destinationTransaction->id, $this->destinationCurrency->code); + $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->destinationTransaction->id, $this->destinationCurrency->code); $this->friendlyInfo($message); ++$this->count; $this->destinationTransaction->save(); @@ -354,7 +353,7 @@ class UpgradesTransferCurrencies extends Command && null === $this->destinationTransaction->foreign_amount && (int) $this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id ) { - $message = sprintf( + $message = sprintf( 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', $this->destinationTransaction->id, $this->destinationTransaction->transaction_currency_id, @@ -377,10 +376,10 @@ class UpgradesTransferCurrencies extends Command { if ($this->destinationCurrency->id === $this->sourceCurrency->id) { // update both transactions to match: - $this->sourceTransaction->foreign_amount = null; - $this->sourceTransaction->foreign_currency_id = null; + $this->sourceTransaction->foreign_amount = null; + $this->sourceTransaction->foreign_currency_id = null; - $this->destinationTransaction->foreign_amount = null; + $this->destinationTransaction->foreign_amount = null; $this->destinationTransaction->foreign_currency_id = null; $this->sourceTransaction->save(); @@ -396,10 +395,10 @@ class UpgradesTransferCurrencies extends Command private function fixMismatchedForeignCurrency(): void { if ($this->sourceCurrency->id !== $this->destinationCurrency->id) { - $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; - $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id; + $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; + $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id; $this->destinationTransaction->transaction_currency_id = $this->sourceCurrency->id; - $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id; + $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id; $this->sourceTransaction->save(); $this->destinationTransaction->save(); @@ -454,9 +453,9 @@ class UpgradesTransferCurrencies extends Command private function fixTransactionJournalCurrency(TransactionJournal $journal): void { if ((int) $journal->transaction_currency_id !== $this->sourceCurrency->id) { - $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; + $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; $journal->transaction_currency_id = $this->sourceCurrency->id; - $message = sprintf( + $message = sprintf( 'Transfer #%d ("%s") has been updated to use %s instead of %s.', $journal->id, $journal->description, diff --git a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php index 95647b23fd..58439f0d71 100644 --- a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php +++ b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php @@ -43,8 +43,8 @@ class UpgradesVariousCurrencyInformation extends Command public const string CONFIG_NAME = '480_other_currencies'; - protected $description = 'Update all journal currency information.'; - protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}'; + protected $description = 'Update all journal currency information.'; + protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}'; private array $accountCurrencies; private AccountRepositoryInterface $accountRepos; private JournalCLIRepositoryInterface $cliRepos; @@ -79,11 +79,11 @@ class UpgradesVariousCurrencyInformation extends Command */ private function stupidLaravel(): void { - $this->count = 0; + $this->count = 0; $this->accountCurrencies = []; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->journalRepos = app(JournalRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->journalRepos = app(JournalRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); } private function isExecuted(): bool @@ -105,7 +105,7 @@ class UpgradesVariousCurrencyInformation extends Command TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::OPENING_BALANCE->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ]); /** @var TransactionJournal $journal */ @@ -151,8 +151,8 @@ class UpgradesVariousCurrencyInformation extends Command // when mismatch in transaction: if ($transaction->transaction_currency_id !== $currency->id && !$isMultiCurrency) { - $transaction->foreign_currency_id = $transaction->transaction_currency_id; - $transaction->foreign_amount = $transaction->amount; + $transaction->foreign_currency_id = $transaction->transaction_currency_id; + $transaction->foreign_amount = $transaction->amount; $transaction->transaction_currency_id = $currency->id; $transaction->save(); } @@ -169,7 +169,7 @@ class UpgradesVariousCurrencyInformation extends Command * Gets the transaction that determines the transaction that "leads" and will determine * the currency to be used by all transactions, and the journal itself. */ - private function getLeadTransaction(TransactionJournal $journal): null|Transaction + private function getLeadTransaction(TransactionJournal $journal): ?Transaction { /** @var null|Transaction $lead */ $lead = null; @@ -195,7 +195,8 @@ class UpgradesVariousCurrencyInformation extends Command ->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') ->where('account_types.type', '!=', AccountTypeEnum::INITIAL_BALANCE->value) - ->first(['transactions.*']); + ->first(['transactions.*']) + ; break; @@ -206,7 +207,8 @@ class UpgradesVariousCurrencyInformation extends Command ->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') ->where('account_types.type', '!=', AccountTypeEnum::RECONCILIATION->value) - ->first(['transactions.*']); + ->first(['transactions.*']) + ; break; } @@ -214,16 +216,16 @@ class UpgradesVariousCurrencyInformation extends Command return $lead; } - private function getCurrency(Account $account): null|TransactionCurrency + private function getCurrency(Account $account): ?TransactionCurrency { - $accountId = $account->id; + $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { return $this->accountCurrencies[$accountId]; } - $currency = $this->accountRepos->getAccountCurrency($account); + $currency = $this->accountRepos->getAccountCurrency($account); if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; diff --git a/app/Console/Commands/Upgrade/UpgradesWebhooks.php b/app/Console/Commands/Upgrade/UpgradesWebhooks.php index 5cddf0e8b4..1249e8d425 100644 --- a/app/Console/Commands/Upgrade/UpgradesWebhooks.php +++ b/app/Console/Commands/Upgrade/UpgradesWebhooks.php @@ -41,8 +41,8 @@ class UpgradesWebhooks extends Command public const string CONFIG_NAME = '640_upgrade_webhooks'; - protected $description = 'Upgrade webhooks so they can handle multiple triggers.'; - protected $signature = 'upgrade:640-upgrade-webhooks {--F|force : Force the execution of this command.}'; + protected $description = 'Upgrade webhooks so they can handle multiple triggers.'; + protected $signature = 'upgrade:640-upgrade-webhooks {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -74,7 +74,8 @@ class UpgradesWebhooks extends Command $set = Webhook::where('delivery', '>', 1) ->orWhere('trigger', '>', 1) ->orWhere('response', '>', 1) - ->get(); + ->get() + ; /** @var Webhook $webhook */ foreach ($set as $webhook) { @@ -84,17 +85,17 @@ class UpgradesWebhooks extends Command private function upgradeWebhook(Webhook $webhook): void { - $delivery = WebhookDelivery::tryFrom((int) $webhook->delivery); - $response = WebhookResponse::tryFrom((int) $webhook->response); - $trigger = WebhookTrigger::tryFrom((int) $webhook->trigger); + $delivery = WebhookDelivery::tryFrom((int) $webhook->delivery); + $response = WebhookResponse::tryFrom((int) $webhook->response); + $trigger = WebhookTrigger::tryFrom((int) $webhook->trigger); if (in_array(null, [$delivery, $response, $trigger], true)) { $this->friendlyError(sprintf('[a] Webhook #%d has an invalid delivery, response or trigger value. Will not upgrade.', $webhook->id)); return; } - $deliveryModel = WebhookDeliveryModel::where('key', $delivery->value)->first(); - $responseModel = WebhookResponseModel::where('key', $response->value)->first(); - $triggerModel = WebhookTriggerModel::where('key', $trigger->value)->first(); + $deliveryModel = WebhookDeliveryModel::where('key', $delivery->value)->first(); + $responseModel = WebhookResponseModel::where('key', $response->value)->first(); + $triggerModel = WebhookTriggerModel::where('key', $trigger->value)->first(); if (in_array(null, [$deliveryModel, $responseModel, $triggerModel], true)) { $this->friendlyError(sprintf('[b] Webhook #%d has an invalid delivery, response or trigger model. Will not upgrade.', $webhook->id)); @@ -105,7 +106,7 @@ class UpgradesWebhooks extends Command $webhook->webhookTriggers()->attach([$triggerModel->id]); $webhook->delivery = 1; $webhook->response = 1; - $webhook->trigger = 1; + $webhook->trigger = 1; $webhook->save(); $this->friendlyPositive(sprintf('Webhook #%d upgraded.', $webhook->id)); } diff --git a/app/Console/Commands/VerifiesAccessToken.php b/app/Console/Commands/VerifiesAccessToken.php index 5c11ef0434..3726eb6a36 100644 --- a/app/Console/Commands/VerifiesAccessToken.php +++ b/app/Console/Commands/VerifiesAccessToken.php @@ -42,7 +42,7 @@ trait VerifiesAccessToken */ public function getUser(): User { - $userId = (int) $this->option('user'); + $userId = (int) $this->option('user'); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); @@ -68,12 +68,12 @@ trait VerifiesAccessToken */ protected function verifyAccessToken(): bool { - $userId = (int) $this->option('user'); - $token = (string) $this->option('token'); + $userId = (int) $this->option('user'); + $token = (string) $this->option('token'); /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $repository->find($userId); + $repository = app(UserRepositoryInterface::class); + $user = $repository->find($userId); if (null === $user) { Log::error(sprintf('verifyAccessToken(): no such user for input "%d"', $userId)); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 82e28c88eb..f60ba1b4f7 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -40,7 +40,7 @@ class Kernel extends ConsoleKernel #[Override] protected function commands(): void { - $this->load(__DIR__ . '/Commands'); + $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } diff --git a/app/Entities/AccountBalance.php b/app/Entities/AccountBalance.php index cbc31fbd08..b7e6247126 100644 --- a/app/Entities/AccountBalance.php +++ b/app/Entities/AccountBalance.php @@ -34,10 +34,10 @@ class AccountBalance public static function fromArray(): self { - $balance = new self(); - $balance->id = (string) random_int(1, 1000); + $balance = new self(); + $balance->id = (string) random_int(1, 1000); // $balance->name = (string) random_int(1, 1000); - $balance->amount = (string) random_int(1, 1000); + $balance->amount = (string) random_int(1, 1000); $balance->currencyId = '1'; return $balance; diff --git a/app/Enums/UserRoleEnum.php b/app/Enums/UserRoleEnum.php index 70503f74c1..8df1fcf9af 100644 --- a/app/Enums/UserRoleEnum.php +++ b/app/Enums/UserRoleEnum.php @@ -31,22 +31,22 @@ enum UserRoleEnum: string { // most basic rights, cannot see other members, can see everything else. // includes reading of metadata - case READ_ONLY = 'ro'; + case READ_ONLY = 'ro'; // required to even USE the group properly (in this order) - case MANAGE_TRANSACTIONS = 'mng_trx'; + case MANAGE_TRANSACTIONS = 'mng_trx'; // required to edit, add or change categories/tags/object-groups - case MANAGE_META = 'mng_meta'; + case MANAGE_META = 'mng_meta'; // read other objects and things. - case READ_BUDGETS = 'read_budgets'; - case READ_PIGGY_BANKS = 'read_piggies'; - case READ_SUBSCRIPTIONS = 'read_subscriptions'; - case READ_RULES = 'read_rules'; - case READ_RECURRING = 'read_recurring'; - case READ_WEBHOOKS = 'read_webhooks'; - case READ_CURRENCIES = 'read_currencies'; + case READ_BUDGETS = 'read_budgets'; + case READ_PIGGY_BANKS = 'read_piggies'; + case READ_SUBSCRIPTIONS = 'read_subscriptions'; + case READ_RULES = 'read_rules'; + case READ_RECURRING = 'read_recurring'; + case READ_WEBHOOKS = 'read_webhooks'; + case READ_CURRENCIES = 'read_currencies'; // manage other financial objects: case MANAGE_BUDGETS = 'mng_budgets'; @@ -58,14 +58,14 @@ enum UserRoleEnum: string case MANAGE_CURRENCIES = 'mng_currencies'; // view and generate reports - case VIEW_REPORTS = 'view_reports'; + case VIEW_REPORTS = 'view_reports'; // view memberships AND roles. needs FULL to manage them. - case VIEW_MEMBERSHIPS = 'view_memberships'; + case VIEW_MEMBERSHIPS = 'view_memberships'; // everything the creator can, except remove/change original creator and delete group - case FULL = 'full'; + case FULL = 'full'; // reserved for original creator - case OWNER = 'owner'; + case OWNER = 'owner'; } diff --git a/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php b/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php index 0fa86a457e..e69f21658f 100644 --- a/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php +++ b/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php @@ -47,11 +47,11 @@ class PiggyBankAmountIsChanged extends Event public function __construct( PiggyBank $piggyBank, string $amount, - public null|TransactionJournal $transactionJournal, - public null|TransactionGroup $transactionGroup + public ?TransactionJournal $transactionJournal, + public ?TransactionGroup $transactionGroup ) { Log::debug(sprintf('Created piggy bank event for piggy bank #%d with amount %s', $piggyBank->id, $amount)); $this->piggyBank = $piggyBank; - $this->amount = $amount; + $this->amount = $amount; } } diff --git a/app/Events/Model/TransactionGroup/TriggeredStoredTransactionGroup.php b/app/Events/Model/TransactionGroup/TriggeredStoredTransactionGroup.php index 76fa224c32..37b1598f71 100644 --- a/app/Events/Model/TransactionGroup/TriggeredStoredTransactionGroup.php +++ b/app/Events/Model/TransactionGroup/TriggeredStoredTransactionGroup.php @@ -33,14 +33,14 @@ class TriggeredStoredTransactionGroup extends Event { use SerializesModels; - public null|RuleGroup $ruleGroup = null; + public ?RuleGroup $ruleGroup = null; /** * Create a new event instance. */ public function __construct( public TransactionGroup $transactionGroup, - null|RuleGroup $ruleGroup = null + ?RuleGroup $ruleGroup = null ) { $this->ruleGroup = $ruleGroup; } diff --git a/app/Events/Security/User/UserSuccessfullyLoggedIn.php b/app/Events/Security/User/UserSuccessfullyLoggedIn.php index c7ae13a7a4..95f43d3ce9 100644 --- a/app/Events/Security/User/UserSuccessfullyLoggedIn.php +++ b/app/Events/Security/User/UserSuccessfullyLoggedIn.php @@ -41,6 +41,7 @@ class UserSuccessfullyLoggedIn extends Event if ($user instanceof User) { $this->user = $user; } + throw new InvalidArgumentException('User must be an instance of User.'); } } diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php index 9e4e8f978b..1b53d0456d 100644 --- a/app/Exceptions/GracefulNotFoundHandler.php +++ b/app/Exceptions/GracefulNotFoundHandler.php @@ -59,7 +59,7 @@ class GracefulNotFoundHandler extends ExceptionHandler if (null === $route) { return parent::render($request, $e); } - $name = $route->getName(); + $name = $route->getName(); if (!auth()->check()) { return parent::render($request, $e); } @@ -168,7 +168,7 @@ class GracefulNotFoundHandler extends ExceptionHandler } /** @var null|Account $account */ - $account = $user->accounts()->withTrashed()->with(['accountType'])->find($accountId); + $account = $user->accounts()->withTrashed()->with(['accountType'])->find($accountId); if (null === $account) { Log::error(sprintf('Could not find account %d, so give big fat error.', $accountId)); @@ -197,7 +197,7 @@ class GracefulNotFoundHandler extends ExceptionHandler $groupId = is_object($param) ? 0 : (int) $param; /** @var null|TransactionGroup $group */ - $group = $user->transactionGroups()->withTrashed()->find($groupId); + $group = $user->transactionGroups()->withTrashed()->find($groupId); if (null === $group) { Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId)); @@ -211,7 +211,7 @@ class GracefulNotFoundHandler extends ExceptionHandler return parent::render($request, $exception); } - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; $request->session()->reflash(); if (TransactionTypeEnum::RECONCILIATION->value === $type) { @@ -237,7 +237,7 @@ class GracefulNotFoundHandler extends ExceptionHandler $attachmentId = is_object($param) ? 0 : (int) $param; /** @var null|Attachment $attachment */ - $attachment = $user->attachments()->withTrashed()->find($attachmentId); + $attachment = $user->attachments()->withTrashed()->find($attachmentId); if (null === $attachment) { Log::error(sprintf('Could not find attachment %d, so give big fat error.', $attachmentId)); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 75061da7d1..c39c2ae044 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -62,12 +62,12 @@ use function Safe\parse_url; */ class Handler extends ExceptionHandler { - public static null|Throwable $lastError = null; + public static ?Throwable $lastError = null; /** * @var array> */ - protected $dontReport = [ + protected $dontReport = [ AuthenticationException::class, LaravelValidationException::class, NotFoundHttpException::class, @@ -77,16 +77,14 @@ class Handler extends ExceptionHandler TokenMismatchException::class, HttpException::class, SuspiciousOperationException::class, - BadHttpHeaderException::class + BadHttpHeaderException::class, ]; /** * Register the exception handling callbacks for the application. */ #[Override] - public function register(): void - { - } + public function register(): void {} /** * Render an exception into an HTTP response. It's complex but lucky for us, we never use it because @@ -157,7 +155,7 @@ class Handler extends ExceptionHandler return response()->json([ 'message' => sprintf('Validation exception: %s', $e->getMessage()), - 'errors' => ['field' => 'Field is invalid'] + 'errors' => ['field' => 'Field is invalid'], ], $errorCode); } @@ -165,7 +163,7 @@ class Handler extends ExceptionHandler $errorCode = 500; $errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode; - $isDebug = (bool) config('app.debug', false); + $isDebug = (bool) config('app.debug', false); if ($isDebug) { Log::debug(sprintf('Return JSON %s with debug.', $e::class)); @@ -174,14 +172,14 @@ class Handler extends ExceptionHandler 'exception' => $e::class, 'line' => $e->getLine(), 'file' => $e->getFile(), - 'trace' => $e->getTrace() + 'trace' => $e->getTrace(), ], $errorCode); } Log::debug(sprintf('Return JSON %s.', $e::class)); return response()->json([ 'message' => sprintf('Internal Firefly III Exception: %s', $e->getMessage()), - 'exception' => 'UndisclosedException' + 'exception' => 'UndisclosedException', ], $errorCode); } @@ -221,21 +219,21 @@ class Handler extends ExceptionHandler public function report(Throwable $e): void { self::$lastError = $e; - $doMailError = (bool) config('firefly.send_error_message'); + $doMailError = (bool) config('firefly.send_error_message'); if ($this->shouldntReportLocal($e) || !$doMailError) { parent::report($e); return; } - $userData = ['id' => 0, 'email' => 'unknown@example.com']; + $userData = ['id' => 0, 'email' => 'unknown@example.com']; if (auth()->check()) { - $userData['id'] = auth()->user()->id; + $userData['id'] = auth()->user()->id; $userData['email'] = auth()->user()->email; } - $headers = request()->headers->all(); + $headers = request()->headers->all(); - $data = [ + $data = [ 'class' => $e::class, 'errorMessage' => $e->getMessage(), 'time' => Carbon::now()->format('r'), @@ -249,12 +247,12 @@ class Handler extends ExceptionHandler 'json' => request()->acceptsJson(), 'method' => request()->method(), 'headers' => $headers, - 'post' => 'POST' === request()->method() ? json_encode(request()->all()) : '' + 'post' => 'POST' === request()->method() ? json_encode(request()->all()) : '', ]; // create job that will mail. - $ipAddress = request()->ip() ?? '0.0.0.0'; - $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data); + $ipAddress = request()->ip() ?? '0.0.0.0'; + $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data); dispatch($job); parent::report($e); @@ -262,7 +260,7 @@ class Handler extends ExceptionHandler private function shouldntReportLocal(Throwable $e): bool { - return null !== Arr::first($this->dontReport, static fn($type): bool => $e instanceof $type); + return null !== Arr::first($this->dontReport, static fn ($type): bool => $e instanceof $type); } /** @@ -279,13 +277,14 @@ class Handler extends ExceptionHandler return redirect($redirect ?? $previous) ->withInput(Arr::except($request->input(), $this->dontFlash)) - ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)); + ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)) + ; } /** * Only return the redirectTo property from the exception if it is a valid URL. Return NULL otherwise. */ - private function getRedirectUrl(LaravelValidationException $exception): null|string + private function getRedirectUrl(LaravelValidationException $exception): ?string { if (null === $exception->redirectTo) { return null; diff --git a/app/Exceptions/IntervalException.php b/app/Exceptions/IntervalException.php index 305aec2061..68664388a9 100644 --- a/app/Exceptions/IntervalException.php +++ b/app/Exceptions/IntervalException.php @@ -37,19 +37,19 @@ final class IntervalException extends Exception public Periodicity $periodicity = Periodicity::Monthly; /** @var mixed */ - protected $message = 'The periodicity %s is unknown. Choose one of available periodicity: %s'; + protected $message = 'The periodicity %s is unknown. Choose one of available periodicity: %s'; - public function __construct(string $message = '', int $code = 0, null|Throwable $previous = null) + public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); } - public static function unavailable(Periodicity $periodicity, array $intervals, int $code = 0, null|Throwable $previous = null): self + public static function unavailable(Periodicity $periodicity, array $intervals, int $code = 0, ?Throwable $previous = null): self { - $message = sprintf('The periodicity %s is unknown. Choose one of available periodicity: %s', $periodicity->name, implode(', ', $intervals)); + $message = sprintf('The periodicity %s is unknown. Choose one of available periodicity: %s', $periodicity->name, implode(', ', $intervals)); - $exception = new self($message, $code, $previous); - $exception->periodicity = $periodicity; + $exception = new self($message, $code, $previous); + $exception->periodicity = $periodicity; $exception->availableIntervals = $intervals; return $exception; diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index eb7c558baf..5d06a29c61 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -59,12 +59,12 @@ class AccountFactory */ public function __construct() { - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); $this->canHaveOpeningBalance = config('firefly.can_have_opening_balance'); - $this->validAssetFields = config('firefly.valid_asset_fields'); - $this->validCCFields = config('firefly.valid_cc_fields'); - $this->validFields = config('firefly.valid_account_fields'); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); } /** @@ -74,7 +74,7 @@ class AccountFactory { Log::debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); - $type = $this->accountRepository->getAccountTypeByType($accountType); + $type = $this->accountRepository->getAccountTypeByType($accountType); if (!$type instanceof AccountType) { throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType)); } @@ -84,7 +84,8 @@ class AccountFactory ->accounts ->where('account_type_id', $type->id) ->where('name', $accountName) - ->first(); + ->first() + ; if (null === $return) { Log::debug('Found nothing. Will create a new one.'); @@ -96,7 +97,7 @@ class AccountFactory 'account_type_name' => null, 'virtual_balance' => '0', 'iban' => null, - 'active' => true + 'active' => true, ]); } @@ -109,17 +110,17 @@ class AccountFactory public function create(array $data): Account { Log::debug('Now in AccountFactory::create()'); - $type = $this->getAccountType($data); + $type = $this->getAccountType($data); $data['iban'] = $this->filterIban($data['iban'] ?? null); // account may exist already: - $return = $this->find($data['name'], $type->type); + $return = $this->find($data['name'], $type->type); if ($return instanceof Account) { return $return; } - $return = $this->createAccount($type, $data); + $return = $this->createAccount($type, $data); event(new StoredAccount($return)); @@ -129,7 +130,7 @@ class AccountFactory /** * @throws FireflyException */ - protected function getAccountType(array $data): null|AccountType + protected function getAccountType(array $data): ?AccountType { $accountTypeId = array_key_exists('account_type_id', $data) ? (int) $data['account_type_id'] : 0; $accountTypeName = $data['account_type_name'] ?? null; @@ -159,7 +160,7 @@ class AccountFactory return $result; } - public function find(string $accountName, string $accountType): null|Account + public function find(string $accountName, string $accountType): ?Account { Log::debug(sprintf('Now in AccountFactory::find("%s", "%s")', $accountName, $accountType)); $type = AccountType::whereType($accountType)->first(); @@ -169,7 +170,8 @@ class AccountFactory ->accounts() ->where('account_type_id', $type->id) ->where('name', $accountName) - ->first(); + ->first() + ; } /** @@ -190,7 +192,7 @@ class AccountFactory 'order' => 25000, 'virtual_balance' => $virtualBalance, 'active' => $active, - 'iban' => $data['iban'] + 'iban' => $data['iban'], ]; // fix virtual balance when it's empty if ('' === (string) $databaseData['virtual_balance']) { @@ -201,11 +203,11 @@ class AccountFactory $databaseData['virtual_balance'] = null; } // create account! - $account = Account::create($databaseData); + $account = Account::create($databaseData); Log::channel('audit')->info(sprintf('Account #%d ("%s") has been created.', $account->id, $account->name)); // update meta data: - $data = $this->cleanMetaDataArray($account, $data); + $data = $this->cleanMetaDataArray($account, $data); $this->storeMetaData($account, $data); // create opening balance (only asset accounts) @@ -225,7 +227,7 @@ class AccountFactory } // create notes - $notes = array_key_exists('notes', $data) ? $data['notes'] : ''; + $notes = array_key_exists('notes', $data) ? $data['notes'] : ''; $this->updateNote($account, $notes); // create location @@ -245,10 +247,10 @@ class AccountFactory */ private function cleanMetaDataArray(Account $account, array $data): array { - $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0; - $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : ''; - $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null; - $currency = $this->getCurrency($currencyId, $currencyCode); + $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0; + $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : ''; + $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null; + $currency = $this->getCurrency($currencyId, $currencyCode); // only asset account may have a role: if (AccountTypeEnum::ASSET->value !== $account->accountType->type) { @@ -259,14 +261,14 @@ class AccountFactory $data['liability_direction'] = null; } $data['account_role'] = $accountRole; - $data['currency_id'] = $currency->id; + $data['currency_id'] = $currency->id; return $data; } private function storeMetaData(Account $account, array $data): void { - $fields = $this->validFields; + $fields = $this->validFields; if (AccountTypeEnum::ASSET->value === $account->accountType->type) { $fields = $this->validAssetFields; } @@ -275,8 +277,8 @@ class AccountFactory } // remove currency_id if necessary. - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); if (!in_array($type, $list, true)) { $pos = array_search('currency_id', $fields, true); if (false !== $pos) { @@ -353,9 +355,9 @@ class AccountFactory */ private function storeOrder(Account $account, array $data): void { - $accountType = $account->accountType->type; - $maxOrder = $this->accountRepository->maxOrder($accountType); - $order = null; + $accountType = $account->accountType->type; + $maxOrder = $this->accountRepository->maxOrder($accountType); + $order = null; if (!array_key_exists('order', $data)) { $order = $maxOrder + 1; } diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php index 345d05fbfb..d2b8d7a80f 100644 --- a/app/Factory/AccountMetaFactory.php +++ b/app/Factory/AccountMetaFactory.php @@ -36,7 +36,7 @@ class AccountMetaFactory /** * Create update or delete meta data. */ - public function crud(Account $account, string $field, string $value): null|AccountMeta + public function crud(Account $account, string $field, string $value): ?AccountMeta { /** @var null|AccountMeta $entry */ $entry = $account->accountMeta()->where('name', $field)->first(); @@ -64,7 +64,7 @@ class AccountMetaFactory return $entry; } - public function create(array $data): null|AccountMeta + public function create(array $data): ?AccountMeta { return AccountMeta::create($data); } diff --git a/app/Factory/AttachmentFactory.php b/app/Factory/AttachmentFactory.php index b8b4cdd3d1..a9095503e8 100644 --- a/app/Factory/AttachmentFactory.php +++ b/app/Factory/AttachmentFactory.php @@ -41,22 +41,22 @@ class AttachmentFactory /** * @throws FireflyException */ - public function create(array $data): null|Attachment + public function create(array $data): ?Attachment { // append if necessary. - $model = str_contains((string) $data['attachable_type'], 'FireflyIII') + $model = str_contains((string) $data['attachable_type'], 'FireflyIII') ? $data['attachable_type'] : sprintf('FireflyIII\Models\%s', $data['attachable_type']); // get journal instead of transaction. if (Transaction::class === $model) { /** @var null|Transaction $transaction */ - $transaction = $this->user->transactions()->find((int) $data['attachable_id']); + $transaction = $this->user->transactions()->find((int) $data['attachable_id']); if (null === $transaction) { throw new FireflyException('Unexpectedly could not find transaction'); } $data['attachable_id'] = $transaction->transaction_journal_id; - $model = TransactionJournal::class; + $model = TransactionJournal::class; } // create attachment: @@ -70,11 +70,11 @@ class AttachmentFactory 'description' => null, 'mime' => '', 'size' => 0, - 'uploaded' => 0 + 'uploaded' => 0, ]); $notes = (string) ($data['notes'] ?? ''); if ('' !== $notes) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($attachment); $note->text = $notes; $note->save(); diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index 0577edd3ed..83fccbe71c 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -47,11 +47,11 @@ class BillFactory /** * @throws FireflyException */ - public function create(array $data): null|Bill + public function create(array $data): ?Bill { Log::debug(sprintf('Now in %s', __METHOD__), $data); - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find( + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find( (int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null) ) ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); @@ -61,10 +61,10 @@ class BillFactory $active = array_key_exists('active', $data) ? $data['active'] : 0; $data['extension_date'] ??= null; - $data['end_date'] ??= null; + $data['end_date'] ??= null; /** @var Bill $bill */ - $bill = Bill::create([ + $bill = Bill::create([ 'name' => $data['name'], 'match' => 'MIGRATED_TO_RULES', 'amount_min' => $data['amount_min'], @@ -81,7 +81,7 @@ class BillFactory 'repeat_freq' => $data['repeat_freq'], 'skip' => $skip, 'automatch' => true, - 'active' => $active + 'active' => $active, ]); } catch (QueryException $e) { Log::error($e->getMessage()); @@ -102,7 +102,7 @@ class BillFactory } } // try also with ID: - $objectGroupId = (int) ($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if ($objectGroup instanceof ObjectGroup) { @@ -114,7 +114,7 @@ class BillFactory return $bill; } - public function find(null|int $billId, null|string $billName): null|Bill + public function find(?int $billId, ?string $billName): ?Bill { $billId = (int) $billId; $billName = (string) $billName; @@ -133,13 +133,14 @@ class BillFactory return $bill; } - public function findByName(string $name): null|Bill + public function findByName(string $name): ?Bill { /** @var null|Bill */ return $this->user ->bills() ->whereLike('name', sprintf('%%%s%%', $name)) - ->first(); + ->first() + ; } public function setUser(User $user): void diff --git a/app/Factory/BudgetFactory.php b/app/Factory/BudgetFactory.php index 731e5e8bbf..fa4ceab6d8 100644 --- a/app/Factory/BudgetFactory.php +++ b/app/Factory/BudgetFactory.php @@ -33,7 +33,7 @@ class BudgetFactory { private User $user; - public function find(null|int $budgetId, null|string $budgetName): null|Budget + public function find(?int $budgetId, ?string $budgetName): ?Budget { $budgetId = (int) $budgetId; $budgetName = (string) $budgetName; @@ -61,13 +61,14 @@ class BudgetFactory return null; } - public function findByName(string $name): null|Budget + public function findByName(string $name): ?Budget { /** @var null|Budget */ return $this->user ->budgets() ->where('name', $name) - ->first(); + ->first() + ; } public function setUser(User $user): void diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php index fbdbd45952..a5ddb51b9d 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -39,7 +39,7 @@ class CategoryFactory /** * @throws FireflyException */ - public function findOrCreate(null|int $categoryId, null|string $categoryName): null|Category + public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category { $categoryId = (int) $categoryId; $categoryName = (string) $categoryName; @@ -77,13 +77,14 @@ class CategoryFactory return null; } - public function findByName(string $name): null|Category + public function findByName(string $name): ?Category { /** @var null|Category */ return $this->user ->categories() ->where('name', $name) - ->first(); + ->first() + ; } public function setUser(User $user): void diff --git a/app/Factory/PiggyBankEventFactory.php b/app/Factory/PiggyBankEventFactory.php index 689afa9af0..e4635fb93c 100644 --- a/app/Factory/PiggyBankEventFactory.php +++ b/app/Factory/PiggyBankEventFactory.php @@ -35,7 +35,7 @@ use Illuminate\Support\Facades\Log; */ class PiggyBankEventFactory { - public function create(TransactionJournal $journal, null|PiggyBank $piggyBank): void + public function create(TransactionJournal $journal, ?PiggyBank $piggyBank): void { Log::debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type)); if (!$piggyBank instanceof PiggyBank) { @@ -48,7 +48,7 @@ class PiggyBankEventFactory $piggyRepos = app(PiggyBankRepositoryInterface::class); $piggyRepos->setUser($journal->user); - $amount = $piggyRepos->getExactAmount($piggyBank, $journal); + $amount = $piggyRepos->getExactAmount($piggyBank, $journal); if (0 === bccomp($amount, '0')) { Log::debug('Amount is zero, will not create event.'); diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index 5d46ac14eb..62ac992de6 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -54,8 +54,8 @@ class PiggyBankFactory public function __construct() { - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->currencyRepository = app(CurrencyRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->piggyBankRepository = app(PiggyBankRepositoryInterface::class); } @@ -72,7 +72,7 @@ class PiggyBankFactory */ public function store(array $data): PiggyBank { - $piggyBankData = $data; + $piggyBankData = $data; // unset some fields unset( @@ -89,11 +89,11 @@ class PiggyBankFactory $piggyBankData['target_amount'] = '0'; } - $piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e'); - $piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e'); - $piggyBankData['account_id'] = null; + $piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e'); + $piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e'); + $piggyBankData['account_id'] = null; $piggyBankData['transaction_currency_id'] = $this->getCurrency($data)->id; - $piggyBankData['order'] = 131337; + $piggyBankData['order'] = 131337; try { /** @var PiggyBank $piggyBank */ @@ -103,11 +103,11 @@ class PiggyBankFactory throw new FireflyException('400005: Could not store new piggy bank.', 0, $e); } - $piggyBank = $this->setOrder($piggyBank, $data); + $piggyBank = $this->setOrder($piggyBank, $data); $this->linkToAccountIds($piggyBank, $data['accounts']); $this->piggyBankRepository->updateNote($piggyBank, $data['notes']); - $objectGroupTitle = $data['object_group_title'] ?? ''; + $objectGroupTitle = $data['object_group_title'] ?? ''; if ('' !== $objectGroupTitle) { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); if ($objectGroup instanceof ObjectGroup) { @@ -115,7 +115,7 @@ class PiggyBankFactory } } // try also with ID - $objectGroupId = (int) ($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if ($objectGroup instanceof ObjectGroup) { @@ -123,7 +123,7 @@ class PiggyBankFactory } } Log::debug('Touch piggy bank'); - $piggyBank->encrypted = false; + $piggyBank->encrypted = false; $piggyBank->save(); $piggyBank->touch(); @@ -146,7 +146,7 @@ class PiggyBankFactory return $currency; } - public function find(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank + public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank { $piggyBankId = (int) $piggyBankId; $piggyBankName = (string) $piggyBankName; @@ -159,7 +159,8 @@ class PiggyBankFactory ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.id', $piggyBankId) - ->first(['piggy_banks.*']); + ->first(['piggy_banks.*']) + ; if (null !== $piggyBank) { return $piggyBank; } @@ -177,19 +178,20 @@ class PiggyBankFactory return null; } - public function findByName(string $name): null|PiggyBank + public function findByName(string $name): ?PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.name', $name) - ->first(['piggy_banks.*']); + ->first(['piggy_banks.*']) + ; } private function setOrder(PiggyBank $piggyBank, array $data): PiggyBank { $this->resetOrder(); - $order = $this->getMaxOrder() + 1; + $order = $this->getMaxOrder() + 1; if (array_key_exists('order', $data)) { $order = $data['order']; } @@ -207,7 +209,8 @@ class PiggyBankFactory ->where('accounts.user_id', $this->user->id) ->with(['objectGroups']) ->orderBy('piggy_banks.order', 'ASC') - ->get(['piggy_banks.*']); + ->get(['piggy_banks.*']) + ; $current = 1; foreach ($set as $piggyBank) { if ($piggyBank->order !== $current) { @@ -254,8 +257,8 @@ class PiggyBankFactory Log::debug(sprintf('Working on account #%d', $account->id)); if (array_key_exists('current_amount', $info) && null !== $info['current_amount']) { // an amount is set, first check out if there is a difference with the previous amount. - $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; - $diff = bcsub($info['current_amount'], $previous); + $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; + $diff = bcsub($info['current_amount'], $previous); // create event for difference. if (0 !== bccomp($diff, '0')) { @@ -270,8 +273,8 @@ class PiggyBankFactory } if (array_key_exists('current_amount', $info) && null === $info['current_amount']) { // no amount is set, first check out if there is a difference with the previous amount. - $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; - $diff = bcsub('0', $previous); + $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; + $diff = bcsub('0', $previous); // create event for difference. if (0 !== bccomp($diff, '0')) { diff --git a/app/Factory/RecurrenceFactory.php b/app/Factory/RecurrenceFactory.php index c18476462a..5efb5cebbd 100644 --- a/app/Factory/RecurrenceFactory.php +++ b/app/Factory/RecurrenceFactory.php @@ -100,7 +100,7 @@ class RecurrenceFactory } $repeatUntilString = $repeatUntil?->format('Y-m-d'); - $recurrence = new Recurrence([ + $recurrence = new Recurrence([ 'user_id' => $this->user->id, 'user_group_id' => $this->user->user_group_id, 'transaction_type_id' => $type->id, @@ -112,7 +112,7 @@ class RecurrenceFactory 'latest_date' => null, 'repetitions' => $repetitions, 'apply_rules' => $applyRules, - 'active' => $active + 'active' => $active, ]); $recurrence->save(); diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php index 18c8c329f7..5e2c44de64 100644 --- a/app/Factory/TagFactory.php +++ b/app/Factory/TagFactory.php @@ -38,16 +38,17 @@ class TagFactory private User $user; private UserGroup $userGroup; - public function findOrCreate(string $tag): null|Tag + public function findOrCreate(string $tag): ?Tag { - $tag = trim($tag); + $tag = trim($tag); Log::debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag)); /** @var null|Tag $dbTag */ - $dbTag = $this->user + $dbTag = $this->user ->tags() ->where('tag', $tag) - ->first(); + ->first() + ; if (null !== $dbTag) { Log::debug(sprintf('Tag exists (#%d), return it.', $dbTag->id)); @@ -59,7 +60,7 @@ class TagFactory 'description' => null, 'latitude' => null, 'longitude' => null, - 'zoom_level' => null + 'zoom_level' => null, ]); if (!$newTag instanceof Tag) { Log::error(sprintf('TagFactory::findOrCreate("%s") but tag is unexpectedly NULL!', $tag)); @@ -71,12 +72,12 @@ class TagFactory return $newTag; } - public function create(array $data): null|Tag + public function create(array $data): ?Tag { $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level']; $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; // intentional float $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude']; // intentional float - $array = [ + $array = [ 'user_id' => $this->user->id, 'user_group_id' => $this->userGroup->id, 'tag' => trim((string) $data['tag']), @@ -85,16 +86,16 @@ class TagFactory 'description' => $data['description'], 'latitude' => null, 'longitude' => null, - 'zoomLevel' => null + 'zoomLevel' => null, ]; /** @var null|Tag $tag */ - $tag = Tag::create($array); + $tag = Tag::create($array); if (!in_array(null, [$tag, $latitude, $longitude], true)) { // create location object. - $location = new Location(); - $location->latitude = $latitude; - $location->longitude = $longitude; + $location = new Location(); + $location->latitude = $latitude; + $location->longitude = $longitude; $location->zoom_level = $zoomLevel; $location->locatable()->associate($tag); $location->save(); @@ -105,7 +106,7 @@ class TagFactory public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } diff --git a/app/Factory/TransactionCurrencyFactory.php b/app/Factory/TransactionCurrencyFactory.php index 4aa98da308..013a43db95 100644 --- a/app/Factory/TransactionCurrencyFactory.php +++ b/app/Factory/TransactionCurrencyFactory.php @@ -40,13 +40,13 @@ class TransactionCurrencyFactory */ public function create(array $data): TransactionCurrency { - $data['code'] = e($data['code']); - $data['symbol'] = e($data['symbol']); - $data['name'] = e($data['name']); + $data['code'] = e($data['code']); + $data['symbol'] = e($data['symbol']); + $data['name'] = e($data['name']); $data['decimal_places'] = (int) $data['decimal_places']; // if the code already exists (deleted) // force delete it and then create the transaction: - $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); + $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); if (1 === $count) { $old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first(); $old->forceDelete(); @@ -60,7 +60,7 @@ class TransactionCurrencyFactory 'code' => $data['code'], 'symbol' => $data['symbol'], 'decimal_places' => $data['decimal_places'], - 'enabled' => false + 'enabled' => false, ]); } catch (QueryException $e) { $result = null; @@ -73,7 +73,7 @@ class TransactionCurrencyFactory return $result; } - public function find(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency + public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency { $currencyCode = e($currencyCode); $currencyId = (int) $currencyId; diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php index 900d7a1b12..2ea36c7a84 100644 --- a/app/Factory/TransactionFactory.php +++ b/app/Factory/TransactionFactory.php @@ -42,18 +42,18 @@ use Illuminate\Support\Facades\Validator; class TransactionFactory { private Account $account; - private array $accountInformation = []; + private array $accountInformation = []; private TransactionCurrency $currency; - private null|TransactionCurrency $foreignCurrency = null; + private ?TransactionCurrency $foreignCurrency = null; private TransactionJournal $journal; - private bool $reconciled = false; + private bool $reconciled = false; /** * Create transaction with negative amount (for source accounts). * * @throws FireflyException */ - public function createNegative(string $amount, null|string $foreignAmount): Transaction + public function createNegative(string $amount, ?string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -68,7 +68,7 @@ class TransactionFactory /** * @throws FireflyException */ - private function create(string $amount, null|string $foreignAmount): Transaction + private function create(string $amount, ?string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -82,7 +82,7 @@ class TransactionFactory 'amount' => $amount, 'foreign_amount' => null, 'foreign_currency_id' => null, - 'identifier' => 0 + 'identifier' => 0, ]; try { @@ -111,7 +111,7 @@ class TransactionFactory // do foreign currency thing: add foreign currency info to $one and $two if necessary. if ($this->foreignCurrency instanceof TransactionCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id) { $result->foreign_currency_id = $this->foreignCurrency->id; - $result->foreign_amount = $foreignAmount; + $result->foreign_amount = $foreignAmount; } $result->save(); @@ -144,7 +144,7 @@ class TransactionFactory // validate info: $validator = Validator::make(['iban' => $this->accountInformation['iban']], ['iban' => [ 'required', - new UniqueIban($this->account, $this->account->accountType->type) + new UniqueIban($this->account, $this->account->accountType->type), ]]); if ($validator->fails()) { Log::debug('Invalid or non-unique IBAN, will not update.'); @@ -153,7 +153,7 @@ class TransactionFactory } Log::debug('Will update account with IBAN information.'); - $service = app(AccountUpdateService::class); + $service = app(AccountUpdateService::class); $service->update($this->account, ['iban' => $this->accountInformation['iban']]); } @@ -162,7 +162,7 @@ class TransactionFactory * * @throws FireflyException */ - public function createPositive(string $amount, null|string $foreignAmount): Transaction + public function createPositive(string $amount, ?string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -192,7 +192,7 @@ class TransactionFactory /** * @param null|TransactionCurrency $foreignCurrency |null */ - public function setForeignCurrency(null|TransactionCurrency $foreignCurrency): void + public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void { $this->foreignCurrency = $foreignCurrency; } diff --git a/app/Factory/TransactionGroupFactory.php b/app/Factory/TransactionGroupFactory.php index a9c0e96cf7..1fd87b8b06 100644 --- a/app/Factory/TransactionGroupFactory.php +++ b/app/Factory/TransactionGroupFactory.php @@ -68,8 +68,8 @@ class TransactionGroupFactory throw new DuplicateTransactionException($e->getMessage(), 0, $e); } - $title = $data['group_title'] ?? null; - $title = '' === $title ? null : $title; + $title = $data['group_title'] ?? null; + $title = '' === $title ? null : $title; if (null !== $title) { $title = substr((string) $title, 0, 1000); @@ -78,7 +78,7 @@ class TransactionGroupFactory throw new FireflyException('Created zero transaction journals.'); } - $group = new TransactionGroup(); + $group = new TransactionGroup(); $group->user()->associate($this->user); $group->userGroup()->associate($this->userGroup); $group->title = $title; @@ -94,7 +94,7 @@ class TransactionGroupFactory */ public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index d9d3cf17ec..53923e6a92 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -87,17 +87,17 @@ class TransactionJournalFactory */ public function __construct() { - $this->fields = config('firefly.journal_meta_fields'); + $this->fields = config('firefly.journal_meta_fields'); $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->typeRepository = app(TransactionTypeRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->typeRepository = app(TransactionTypeRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->piggyRepository = app(PiggyBankRepositoryInterface::class); - $this->piggyEventFactory = app(PiggyBankEventFactory::class); - $this->tagFactory = app(TagFactory::class); - $this->accountValidator = app(AccountValidator::class); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->piggyRepository = app(PiggyBankRepositoryInterface::class); + $this->piggyEventFactory = app(PiggyBankEventFactory::class); + $this->tagFactory = app(TagFactory::class); + $this->accountValidator = app(AccountValidator::class); + $this->accountRepository = app(AccountRepositoryInterface::class); } /** @@ -110,7 +110,7 @@ class TransactionJournalFactory { Log::debug('Now in TransactionJournalFactory::create()'); // convert to special object. - $dataObject = new NullArrayObject($data); + $dataObject = new NullArrayObject($data); Log::debug('Start of TransactionJournalFactory::create()'); $collection = new Collection(); @@ -161,7 +161,7 @@ class TransactionJournalFactory * * @SuppressWarnings("PHPMD.ExcessiveMethodLength") */ - private function createJournal(NullArrayObject $row): null|TransactionJournal + private function createJournal(NullArrayObject $row): ?TransactionJournal { Log::debug('Now in TransactionJournalFactory::createJournal()'); $row['import_hash_v2'] = $this->hashArray($row); @@ -169,18 +169,18 @@ class TransactionJournalFactory $this->errorIfDuplicate($row['import_hash_v2']); // Some basic fields - $type = $this->typeRepository->findTransactionType(null, $row['type']); - $carbon = $row['date'] ?? today(config('app.timezone')); - $order = $row['order'] ?? 0; + $type = $this->typeRepository->findTransactionType(null, $row['type']); + $carbon = $row['date'] ?? today(config('app.timezone')); + $order = $row['order'] ?? 0; Log::debug('Find currency or return default.'); - $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); + $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); Log::debug('Find foreign currency or return NULL.'); - $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); - $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); - $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null; - $description = (string) $row['description']; + $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); + $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); + $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null; + $description = (string) $row['description']; // Manipulate basic fields $carbon->setTimezone(config('app.timezone')); @@ -202,27 +202,27 @@ class TransactionJournalFactory } /** create or get source and destination accounts */ - $sourceInfo = [ + $sourceInfo = [ 'id' => $row['source_id'], 'name' => $row['source_name'], 'iban' => $row['source_iban'], 'number' => $row['source_number'], 'bic' => $row['source_bic'], - 'currency_id' => $currency->id + 'currency_id' => $currency->id, ]; - $destInfo = [ + $destInfo = [ 'id' => $row['destination_id'], 'name' => $row['destination_name'], 'iban' => $row['destination_iban'], 'number' => $row['destination_number'], 'bic' => $row['destination_bic'], - 'currency_id' => $currency->id + 'currency_id' => $currency->id, ]; Log::debug('Source info:', $sourceInfo); Log::debug('Destination info:', $destInfo); - $destinationAccount = null; - $sourceAccount = null; + $destinationAccount = null; + $sourceAccount = null; if (TransactionTypeEnum::DEPOSIT->value === $type->type) { Log::debug('Transaction type is deposit, start with destination first.'); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); @@ -247,10 +247,10 @@ class TransactionJournalFactory [$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount); } - $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); - $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); - $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); - $description = $this->getDescription($description); + $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); + $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); + $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); + $description = $this->getDescription($description); Log::debug(sprintf( 'Currency is #%d "%s", foreign currency is #%d "%s"', @@ -262,7 +262,7 @@ class TransactionJournalFactory Log::debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName())); /** Create a basic journal. */ - $journal = TransactionJournal::create([ + $journal = TransactionJournal::create([ 'user_id' => $this->user->id, 'user_group_id' => $this->userGroup->id, 'transaction_type_id' => $type->id, @@ -273,12 +273,12 @@ class TransactionJournalFactory 'date_tz' => $carbon->format('e'), 'order' => $order, 'tag_count' => 0, - 'completed' => 0 + 'completed' => 0, ]); Log::debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description)); /** Create two transactions. */ - $transactionFactory = app(TransactionFactory::class); + $transactionFactory = app(TransactionFactory::class); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($sourceAccount); $transactionFactory->setCurrency($currency); @@ -296,7 +296,7 @@ class TransactionJournalFactory } /** @var TransactionFactory $transactionFactory */ - $transactionFactory = app(TransactionFactory::class); + $transactionFactory = app(TransactionFactory::class); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($destinationAccount); $transactionFactory->setAccountInformation($destInfo); @@ -308,8 +308,8 @@ class TransactionJournalFactory // Firefly III will save the foreign currency information in such a way that both // asset accounts can look at the "amount" and "transaction_currency_id" column and // see the currency they expect to see. - $amount = (string) $row['amount']; - $foreignAmount = (string) $row['foreign_amount']; + $amount = (string) $row['amount']; + $foreignAmount = (string) $row['foreign_amount']; if ( $foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id !== $currency->id @@ -331,7 +331,7 @@ class TransactionJournalFactory throw new FireflyException($e->getMessage(), 0, $e); } - $journal->completed = true; + $journal->completed = true; $journal->save(); $this->storeBudget($journal, $row); $this->storeCategory($journal, $row); @@ -356,7 +356,7 @@ class TransactionJournalFactory Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage())); $json = microtime(); } - $hash = hash('sha256', $json); + $hash = hash('sha256', $json); Log::debug(sprintf('The hash is: %s', $hash), $dataRow); return $hash; @@ -384,7 +384,8 @@ class TransactionJournalFactory ->where('transaction_journals.user_id', $this->user->id) ->where('data', json_encode($hash, JSON_THROW_ON_ERROR)) ->with(['transactionJournal', 'transactionJournal.transactionGroup']) - ->first(['journal_meta.*']); + ->first(['journal_meta.*']) + ; if (null !== $result) { Log::warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash)); $journal = $result->transactionJournal()->withTrashed()->first(); @@ -401,18 +402,18 @@ class TransactionJournalFactory private function validateAccounts(NullArrayObject $data): void { Log::debug(sprintf('Now in %s', __METHOD__)); - $transactionType = $data['type'] ?? 'invalid'; + $transactionType = $data['type'] ?? 'invalid'; $this->accountValidator->setUser($this->user); $this->accountValidator->setTransactionType($transactionType); // validate source account. - $array = [ + $array = [ 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null, 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null, 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null, - 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null + 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null, ]; - $validSource = $this->accountValidator->validateSource($array); + $validSource = $this->accountValidator->validateSource($array); // do something with result: if (false === $validSource) { @@ -421,11 +422,11 @@ class TransactionJournalFactory Log::debug('Source seems valid.'); // validate destination account - $array = [ + $array = [ 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null, 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null, 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null, - 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null + 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null, ]; $validDestination = $this->accountValidator->validateDestination($array); @@ -440,7 +441,7 @@ class TransactionJournalFactory */ public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; $this->currencyRepository->setUser($this->user); $this->tagFactory->setUser($user); @@ -451,7 +452,7 @@ class TransactionJournalFactory $this->accountRepository->setUser($this->user); } - private function reconciliationSanityCheck(null|Account $sourceAccount, null|Account $destinationAccount): array + private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array { Log::debug(sprintf('Now in %s', __METHOD__)); if ($sourceAccount instanceof Account && $destinationAccount instanceof Account) { @@ -482,7 +483,7 @@ class TransactionJournalFactory /** * @throws FireflyException */ - private function getCurrencyByAccount(string $type, null|TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency + private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency { Log::debug('Now in getCurrencyByAccount()'); @@ -495,12 +496,12 @@ class TransactionJournalFactory } return match ($type) { - default => $this->getCurrency($currency, $source), + default => $this->getCurrency($currency, $source), TransactionTypeEnum::DEPOSIT->value => $this->getCurrency($currency, $destination) }; } - private function getCurrency(null|TransactionCurrency $currency, Account $account): TransactionCurrency + private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency { Log::debug(sprintf('Now in getCurrency(#%d, "%s")', $currency?->id, $account->name)); @@ -510,7 +511,7 @@ class TransactionJournalFactory // return user's default: return Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $result = $preference ?? $currency; + $result = $preference ?? $currency; Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); return $result; @@ -519,7 +520,7 @@ class TransactionJournalFactory /** * Set foreign currency to NULL if it's the same as the normal currency: */ - private function compareCurrencies(null|TransactionCurrency $currency, null|TransactionCurrency $foreignCurrency): null|TransactionCurrency + private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency { Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code)); if (!$currency instanceof TransactionCurrency) { @@ -535,7 +536,7 @@ class TransactionJournalFactory /** * @throws FireflyException */ - private function getForeignByAccount(string $type, null|TransactionCurrency $foreignCurrency, Account $destination): null|TransactionCurrency + private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency { Log::debug(sprintf('Now in getForeignByAccount("%s", #%d, "%s")', $type, $foreignCurrency?->id, $destination->name)); if (TransactionTypeEnum::TRANSFER->value === $type) { @@ -600,7 +601,7 @@ class TransactionJournalFactory protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void { - $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')]; + $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')]; if ($data[$field] instanceof Carbon) { $data[$field]->setTimezone(config('app.timezone')); Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName())); @@ -617,9 +618,9 @@ class TransactionJournalFactory private function storeLocation(TransactionJournal $journal, NullArrayObject $data): void { if (!in_array(null, [$data['longitude'], $data['latitude'], $data['zoom_level']], true)) { - $location = new Location(); - $location->longitude = $data['longitude']; - $location->latitude = $data['latitude']; + $location = new Location(); + $location->longitude = $data['longitude']; + $location->latitude = $data['latitude']; $location->zoom_level = $data['zoom_level']; $location->locatable()->associate($journal); $location->save(); diff --git a/app/Factory/TransactionJournalMetaFactory.php b/app/Factory/TransactionJournalMetaFactory.php index 4f3573ea06..31e9fe4888 100644 --- a/app/Factory/TransactionJournalMetaFactory.php +++ b/app/Factory/TransactionJournalMetaFactory.php @@ -33,13 +33,13 @@ use Illuminate\Support\Facades\Log; */ class TransactionJournalMetaFactory { - public function updateOrCreate(array $data): null|TransactionJournalMeta + public function updateOrCreate(array $data): ?TransactionJournalMeta { // Log::debug('In updateOrCreate()'); - $value = $data['data']; + $value = $data['data']; /** @var null|TransactionJournalMeta $entry */ - $entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first(); + $entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first(); if (null === $value && null !== $entry) { // Log::debug('Value is empty, delete meta value.'); $entry->delete(); @@ -65,7 +65,7 @@ class TransactionJournalMetaFactory if (null === $entry) { // Log::debug('Will create new object.'); Log::debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name'])); - $entry = new TransactionJournalMeta(); + $entry = new TransactionJournalMeta(); $entry->transactionJournal()->associate($data['journal']); $entry->name = $data['name']; } diff --git a/app/Factory/TransactionTypeFactory.php b/app/Factory/TransactionTypeFactory.php index df0367f809..b7bde85c90 100644 --- a/app/Factory/TransactionTypeFactory.php +++ b/app/Factory/TransactionTypeFactory.php @@ -31,7 +31,7 @@ use FireflyIII\Models\TransactionType; */ class TransactionTypeFactory { - public function find(string $type): null|TransactionType + public function find(string $type): ?TransactionType { return TransactionType::whereType(ucfirst($type))->first(); } diff --git a/app/Factory/UserGroupFactory.php b/app/Factory/UserGroupFactory.php index ec93b97b6d..d392b69832 100644 --- a/app/Factory/UserGroupFactory.php +++ b/app/Factory/UserGroupFactory.php @@ -40,20 +40,20 @@ class UserGroupFactory */ public function create(array $data): UserGroup { - $userGroup = new UserGroup(); - $userGroup->title = $data['title']; + $userGroup = new UserGroup(); + $userGroup->title = $data['title']; $userGroup->save(); // grab the OWNER role: - $role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first(); + $role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first(); if (null === $role) { throw new FireflyException('Role "owner" does not exist.'); } // make user member: - $groupMembership = new GroupMembership(); + $groupMembership = new GroupMembership(); $groupMembership->user_group_id = $userGroup->id; - $groupMembership->user_id = $data['user']->id; - $groupMembership->user_role_id = $role->id; + $groupMembership->user_id = $data['user']->id; + $groupMembership->user_role_id = $role->id; $groupMembership->save(); return $userGroup; diff --git a/app/Generator/Chart/Basic/ChartJsGenerator.php b/app/Generator/Chart/Basic/ChartJsGenerator.php index b167072e5d..a236daf151 100644 --- a/app/Generator/Chart/Basic/ChartJsGenerator.php +++ b/app/Generator/Chart/Basic/ChartJsGenerator.php @@ -40,22 +40,22 @@ class ChartJsGenerator implements GeneratorInterface { $chartData = ['datasets' => [0 => []], 'labels' => []]; - $amounts = array_column($data, 'amount'); - $next = next($amounts); - $sortFlag = SORT_ASC; + $amounts = array_column($data, 'amount'); + $next = next($amounts); + $sortFlag = SORT_ASC; if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { $sortFlag = SORT_DESC; } array_multisort($amounts, $sortFlag, $data); unset($next, $sortFlag, $amounts); - $index = 0; + $index = 0; foreach ($data as $key => $valueArray) { // make larger than 0 - $chartData['datasets'][0]['data'][] = Steam::positive((string) $valueArray['amount']); + $chartData['datasets'][0]['data'][] = Steam::positive((string) $valueArray['amount']); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol']; - $chartData['labels'][] = $key; + $chartData['labels'][] = $key; ++$index; } @@ -95,21 +95,21 @@ class ChartJsGenerator implements GeneratorInterface public function multiSet(array $data): array { reset($data); - $first = current($data); + $first = current($data); if (!is_array($first)) { return []; } - $labels = is_array($first['entries']) ? array_keys($first['entries']) : []; + $labels = is_array($first['entries']) ? array_keys($first['entries']) : []; $chartData = [ - 'count' => count($data), - 'labels' => $labels, // take ALL labels from the first set. - 'datasets' => [] + 'count' => count($data), + 'labels' => $labels, // take ALL labels from the first set. + 'datasets' => [], ]; unset($first, $labels); foreach ($data as $set) { - $currentSet = ['label' => $set['label'] ?? '(no label)', 'type' => $set['type'] ?? 'line', 'data' => array_values($set['entries'])]; + $currentSet = ['label' => $set['label'] ?? '(no label)', 'type' => $set['type'] ?? 'line', 'data' => array_values($set['entries'])]; if (array_key_exists('yAxisID', $set)) { $currentSet['yAxisID'] = $set['yAxisID']; } @@ -140,20 +140,20 @@ class ChartJsGenerator implements GeneratorInterface // sort by value, keep keys. // different sort when values are positive and when they're negative. asort($data); - $next = next($data); + $next = next($data); if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { // next is positive, sort other way around. arsort($data); } unset($next); - $index = 0; + $index = 0; foreach ($data as $key => $value) { // make larger than 0 - $chartData['datasets'][0]['data'][] = Steam::positive((string) $value); + $chartData['datasets'][0]['data'][] = Steam::positive((string) $value); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); - $chartData['labels'][] = $key; + $chartData['labels'][] = $key; ++$index; } @@ -168,9 +168,9 @@ class ChartJsGenerator implements GeneratorInterface public function singleSet(string $setLabel, array $data): array { return [ - 'count' => 1, - 'labels' => array_keys($data), // take ALL labels from the first set. - 'datasets' => [['label' => $setLabel, 'data' => array_values($data)]] + 'count' => 1, + 'labels' => array_keys($data), // take ALL labels from the first set. + 'datasets' => [['label' => $setLabel, 'data' => array_values($data)]], ]; } } diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index 105c89fbc3..b186742802 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -57,12 +57,13 @@ class MonthReportGenerator implements ReportGeneratorInterface 'accountIds' => $accountIds, 'reportType' => $reportType, 'doubleIds' => $doubleIds, - 'preferredPeriod' => $preferredPeriod + 'preferredPeriod' => $preferredPeriod, ]) ->with('start', $this->start) ->with('end', $this->end) ->with('doubles', $this->expense) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index 1e1c166b02..76cad49a34 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -53,8 +53,8 @@ class MonthReportGenerator implements ReportGeneratorInterface */ public function generate(): string { - $auditData = []; - $dayBefore = clone $this->start; + $auditData = []; + $dayBefore = clone $this->start; // set date to subday + end-of-day for account balance. so it is at $date 23:59:59 $dayBefore->subDay()->endOfDay(); @@ -62,7 +62,7 @@ class MonthReportGenerator implements ReportGeneratorInterface /** @var Account $account */ foreach ($this->accounts as $account) { // balance the day before: - $id = $account->id; + $id = $account->id; $auditData[$id] = $this->getAuditReport($account, $dayBefore); } @@ -97,7 +97,7 @@ class MonthReportGenerator implements ReportGeneratorInterface 'process_date', 'due_date', 'payment_date', - 'invoice_date' + 'invoice_date', ]; try { @@ -106,12 +106,13 @@ class MonthReportGenerator implements ReportGeneratorInterface 'accountIds' => $accountIds, 'auditData' => $auditData, 'hideable' => $hideable, - 'defaultShow' => $defaultShow + 'defaultShow' => $defaultShow, ]) ->with('start', $this->start) ->with('end', $this->end) ->with('accounts', $this->accounts) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -139,7 +140,7 @@ class MonthReportGenerator implements ReportGeneratorInterface $journalRepository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setRange($this->start, $this->end) @@ -147,22 +148,23 @@ class MonthReportGenerator implements ReportGeneratorInterface ->withBudgetInformation() ->withCategoryInformation() ->withBillInformation() - ->withNotes(); - $journals = $collector->getExtractedJournals(); - $journals = array_reverse($journals, true); + ->withNotes() + ; + $journals = $collector->getExtractedJournals(); + $journals = array_reverse($journals, true); Log::debug(sprintf('getAuditReport: Call accountsBalancesOptimized with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace with accountsBalancesOptimized. // $dayBeforeBalance = Steam::finalAccountBalance($account, $date); - $dayBeforeBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; + $dayBeforeBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; - $startBalance = $dayBeforeBalance['balance']; - $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); - $currency = $accountRepository->getAccountCurrency($account) ?? $primaryCurrency; + $startBalance = $dayBeforeBalance['balance']; + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); + $currency = $accountRepository->getAccountCurrency($account) ?? $primaryCurrency; foreach ($journals as $index => $journal) { $journals[$index]['balance_before'] = $startBalance; - $transactionAmount = $journal['amount']; + $transactionAmount = $journal['amount']; // make sure amount is in the right "direction". if ($account->id === $journal['destination_account_id']) { @@ -176,32 +178,32 @@ class MonthReportGenerator implements ReportGeneratorInterface } } - $newBalance = bcadd((string) $startBalance, (string) $transactionAmount); - $journals[$index]['balance_after'] = $newBalance; - $startBalance = $newBalance; + $newBalance = bcadd((string) $startBalance, (string) $transactionAmount); + $journals[$index]['balance_after'] = $newBalance; + $startBalance = $newBalance; // add meta dates for each journal. - $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); - $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); - $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); - $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); - $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); - $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); + $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); + $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); + $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); + $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); + $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); + $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); } - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); // call is correct. Log::debug(sprintf('getAuditReport end: Call finalAccountBalance with date/time "%s"', $this->end->toIso8601String())); // 2025-10-08 replace with accountsBalancesOptimized: return [ - 'journals' => $journals, - 'currency' => $currency, - 'exists' => 0 !== count($journals), - 'end' => $this->end->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), + 'journals' => $journals, + 'currency' => $currency, + 'exists' => 0 !== count($journals), + 'end' => $this->end->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), // 'endBalance' => Steam::finalAccountBalance($account, $this->end)['balance'], 'endBalance' => Steam::accountsBalancesOptimized(new Collection()->push($account), $this->end)[$account->id]['balance'], 'dayBefore' => $date->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), - 'dayBeforeBalance' => $dayBeforeBalance + 'dayBeforeBalance' => $dayBeforeBalance, ]; } diff --git a/app/Generator/Report/Budget/MonthReportGenerator.php b/app/Generator/Report/Budget/MonthReportGenerator.php index 5d8ea8f433..865a07ad32 100644 --- a/app/Generator/Report/Budget/MonthReportGenerator.php +++ b/app/Generator/Report/Budget/MonthReportGenerator.php @@ -60,7 +60,8 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('end', $this->end) ->with('budgets', $this->budgets) ->with('accounts', $this->accounts) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -128,16 +129,17 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($this->accounts) ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->withAccountInformation() ->withBudgetInformation() - ->setBudgets($this->budgets); + ->setBudgets($this->budgets) + ; - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); $this->expenses = $journals; return $journals; diff --git a/app/Generator/Report/Category/MonthReportGenerator.php b/app/Generator/Report/Category/MonthReportGenerator.php index 3f1bd84a6b..d4079bbd47 100644 --- a/app/Generator/Report/Category/MonthReportGenerator.php +++ b/app/Generator/Report/Category/MonthReportGenerator.php @@ -63,7 +63,8 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('end', $this->end) ->with('categories', $this->categories) ->with('accounts', $this->accounts) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.category.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -129,15 +130,16 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($this->accounts) ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($this->categories) - ->withAccountInformation(); + ->withAccountInformation() + ; - $transactions = $collector->getExtractedJournals(); + $transactions = $collector->getExtractedJournals(); $this->expenses = $transactions; return $transactions; @@ -173,14 +175,15 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($this->accounts) ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($this->categories) - ->withAccountInformation(); + ->withAccountInformation() + ; $transactions = $collector->getExtractedJournals(); $this->income = $transactions; diff --git a/app/Generator/Report/ReportGeneratorFactory.php b/app/Generator/Report/ReportGeneratorFactory.php index f0a05a9df6..9d74f758ba 100644 --- a/app/Generator/Report/ReportGeneratorFactory.php +++ b/app/Generator/Report/ReportGeneratorFactory.php @@ -49,7 +49,7 @@ class ReportGeneratorFactory $period = 'MultiYear'; } - $class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period); + $class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period); if (class_exists($class)) { /** @var ReportGeneratorInterface $obj */ $obj = app($class); diff --git a/app/Generator/Report/Standard/MonthReportGenerator.php b/app/Generator/Report/Standard/MonthReportGenerator.php index 4475ba23da..f1d3d30d42 100644 --- a/app/Generator/Report/Standard/MonthReportGenerator.php +++ b/app/Generator/Report/Standard/MonthReportGenerator.php @@ -36,13 +36,13 @@ use Throwable; class MonthReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved in the report. */ - private null|Collection $accounts = null; + private ?Collection $accounts = null; /** @var Carbon The end date. */ - private null|Carbon $end = null; + private ?Carbon $end = null; /** @var Carbon The start date. */ - private null|Carbon $start = null; + private ?Carbon $start = null; /** * Generates the report. @@ -58,7 +58,8 @@ class MonthReportGenerator implements ReportGeneratorInterface return view('reports.default.month', ['accountIds' => $accountIds, 'reportType' => $reportType]) ->with('start', $this->start) ->with('end', $this->end) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.default.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Standard/MultiYearReportGenerator.php b/app/Generator/Report/Standard/MultiYearReportGenerator.php index 13be7c51e0..acd6d70f80 100644 --- a/app/Generator/Report/Standard/MultiYearReportGenerator.php +++ b/app/Generator/Report/Standard/MultiYearReportGenerator.php @@ -36,13 +36,13 @@ use Throwable; class MultiYearReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved. */ - private null|Collection $accounts = null; + private ?Collection $accounts = null; /** @var Carbon The end date. */ - private null|Carbon $end = null; + private ?Carbon $end = null; /** @var Carbon The start date. */ - private null|Carbon $start = null; + private ?Carbon $start = null; /** * Generates the report. @@ -59,7 +59,8 @@ class MultiYearReportGenerator implements ReportGeneratorInterface return view('reports.default.multi-year', ['accountIds' => $accountIds, 'reportType' => $reportType]) ->with('start', $this->start) ->with('end', $this->end) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.default.multi-year: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Standard/YearReportGenerator.php b/app/Generator/Report/Standard/YearReportGenerator.php index 2cea39525f..2605cc06b8 100644 --- a/app/Generator/Report/Standard/YearReportGenerator.php +++ b/app/Generator/Report/Standard/YearReportGenerator.php @@ -36,13 +36,13 @@ use Throwable; class YearReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved. */ - private null|Collection $accounts = null; + private ?Collection $accounts = null; /** @var Carbon The end date. */ - private null|Carbon $end = null; + private ?Carbon $end = null; /** @var Carbon The start date. */ - private null|Carbon $start = null; + private ?Carbon $start = null; /** * Generates the report. @@ -59,7 +59,8 @@ class YearReportGenerator implements ReportGeneratorInterface $result = view('reports.default.year', ['accountIds' => $accountIds, 'reportType' => $reportType]) ->with('start', $this->start) ->with('end', $this->end) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Tag/MonthReportGenerator.php b/app/Generator/Report/Tag/MonthReportGenerator.php index de9310775f..d1af280e97 100644 --- a/app/Generator/Report/Tag/MonthReportGenerator.php +++ b/app/Generator/Report/Tag/MonthReportGenerator.php @@ -46,7 +46,7 @@ class MonthReportGenerator implements ReportGeneratorInterface */ public function __construct() { - $this->tags = new Collection(); + $this->tags = new Collection(); $this->accounts = new Collection(); } @@ -68,7 +68,8 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('end', $this->end) ->with('tags', $this->tags) ->with('accounts', $this->accounts) - ->render(); + ->render() + ; } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Webhook/StandardMessageGenerator.php b/app/Generator/Webhook/StandardMessageGenerator.php index ecbe711fa3..3e5d3e4fb9 100644 --- a/app/Generator/Webhook/StandardMessageGenerator.php +++ b/app/Generator/Webhook/StandardMessageGenerator.php @@ -63,7 +63,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface public function __construct() { - $this->objects = new Collection(); + $this->objects = new Collection(); $this->webhooks = new Collection(); } @@ -92,7 +92,8 @@ class StandardMessageGenerator implements MessageGeneratorInterface ->leftJoin('webhook_triggers', 'webhook_webhook_trigger.webhook_trigger_id', 'webhook_triggers.id') ->where('active', true) ->whereIn('webhook_triggers.title', [$this->trigger->name, WebhookTrigger::ANY->name]) - ->get(['webhooks.*']); + ->get(['webhooks.*']) + ; } /** @@ -127,23 +128,23 @@ class StandardMessageGenerator implements MessageGeneratorInterface */ private function generateMessage(Webhook $webhook, Model $model): void { - $class = $model::class; + $class = $model::class; // Line is ignored because all of Firefly III's Models have an id property. Log::debug(sprintf('Now in generateMessage(#%d, %s#%d)', $webhook->id, $class, $model->id)); - $uuid = Uuid::uuid4(); + $uuid = Uuid::uuid4(); /** @var WebhookResponseModel $response */ - $response = $webhook->webhookResponses()->first(); + $response = $webhook->webhookResponses()->first(); $this->getTriggerTitles($webhook->webhookTriggers()->get()); - $basicMessage = [ + $basicMessage = [ 'uuid' => $uuid->toString(), 'user_id' => 0, 'user_group_id' => 0, 'trigger' => $this->trigger->name, 'response' => $response->title, // guess that the database is correct. - 'url' => $webhook->url, - 'version' => sprintf('v%d', $this->getVersion()), - 'content' => [] + 'url' => $webhook->url, + 'version' => sprintf('v%d', $this->getVersion()), + 'content' => [], ]; switch ($class) { @@ -155,22 +156,22 @@ class StandardMessageGenerator implements MessageGeneratorInterface case Budget::class: /** @var Budget $model */ - $basicMessage['user_id'] = $model->user_id; + $basicMessage['user_id'] = $model->user_id; $basicMessage['user_group_id'] = $model->user_group_id; - $relevantResponse = WebhookResponse::BUDGET->name; + $relevantResponse = WebhookResponse::BUDGET->name; break; case BudgetLimit::class: - $basicMessage['user_id'] = $model->budget->user_id; + $basicMessage['user_id'] = $model->budget->user_id; $basicMessage['user_group_id'] = $model->budget->user_group_id; - $relevantResponse = WebhookResponse::BUDGET->name; + $relevantResponse = WebhookResponse::BUDGET->name; break; case TransactionGroup::class: /** @var TransactionGroup $model */ - $basicMessage['user_id'] = $model->user_id; + $basicMessage['user_id'] = $model->user_id; $basicMessage['user_group_id'] = $model->user_group_id; break; @@ -190,26 +191,26 @@ class StandardMessageGenerator implements MessageGeneratorInterface case WebhookResponse::BUDGET->name: $basicMessage['content'] = []; if ($model instanceof Budget) { - $enrichment = new BudgetEnrichment(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($model->user); /** @var Budget $model */ - $model = $enrichment->enrichSingle($model); - $transformer = new BudgetTransformer(); + $model = $enrichment->enrichSingle($model); + $transformer = new BudgetTransformer(); $basicMessage['content'] = $transformer->transform($model); } if ($model instanceof BudgetLimit) { - $user = $model->budget->user; - $enrichment = new BudgetLimitEnrichment(); + $user = $model->budget->user; + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($user); - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('start', $model->start_date); $parameters->set('end', $model->end_date); /** @var BudgetLimit $model */ - $model = $enrichment->enrichSingle($model); - $transformer = new BudgetLimitTransformer(); + $model = $enrichment->enrichSingle($model); + $transformer = new BudgetLimitTransformer(); $transformer->setParameters($parameters); $basicMessage['content'] = $transformer->transform($model); } @@ -223,7 +224,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface case WebhookResponse::TRANSACTIONS->name: /** @var TransactionGroup $model */ - $transformer = new TransactionGroupTransformer(); + $transformer = new TransactionGroupTransformer(); try { $basicMessage['content'] = $transformer->transformObject($model); @@ -242,13 +243,13 @@ class StandardMessageGenerator implements MessageGeneratorInterface case WebhookResponse::ACCOUNTS->name: /** @var TransactionGroup $model */ - $accounts = $this->collectAccounts($model); - $enrichment = new AccountEnrichment(); + $accounts = $this->collectAccounts($model); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($model->user); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); foreach ($accounts as $account) { - $transformer = new AccountTransformer(); + $transformer = new AccountTransformer(); $transformer->setParameters(new ParameterBag()); $basicMessage['content'][] = $transformer->transform($account); } @@ -278,11 +279,11 @@ class StandardMessageGenerator implements MessageGeneratorInterface private function storeMessage(Webhook $webhook, array $message): void { - $webhookMessage = new WebhookMessage(); + $webhookMessage = new WebhookMessage(); $webhookMessage->webhook()->associate($webhook); - $webhookMessage->sent = false; + $webhookMessage->sent = false; $webhookMessage->errored = false; - $webhookMessage->uuid = $message['uuid']; + $webhookMessage->uuid = $message['uuid']; $webhookMessage->message = $message; $webhookMessage->save(); Log::debug(sprintf('Stored new webhook message #%d', $webhookMessage->id)); diff --git a/app/Handlers/Events/AdminEventHandler.php b/app/Handlers/Events/AdminEventHandler.php index 66abc16d6a..12835737a8 100644 --- a/app/Handlers/Events/AdminEventHandler.php +++ b/app/Handlers/Events/AdminEventHandler.php @@ -62,7 +62,5 @@ class AdminEventHandler } } - /** - * Send new version message to admin. - */ + // Send new version message to admin. } diff --git a/app/Handlers/Events/AuditEventHandler.php b/app/Handlers/Events/AuditEventHandler.php index 9e618631d6..21e8ac56ed 100644 --- a/app/Handlers/Events/AuditEventHandler.php +++ b/app/Handlers/Events/AuditEventHandler.php @@ -36,12 +36,12 @@ class AuditEventHandler { public function storeAuditEvent(TriggeredAuditLog $event): void { - $array = [ + $array = [ 'auditable' => $event->auditable, 'changer' => $event->changer, 'action' => $event->field, 'before' => $event->before, - 'after' => $event->after + 'after' => $event->after, ]; if ($event->before === $event->after) { @@ -56,7 +56,7 @@ class AuditEventHandler } if ($event->before instanceof Carbon && $event->after instanceof Carbon) { $array['before'] = $event->before->toIso8601String(); - $array['after'] = $event->after->toIso8601String(); + $array['after'] = $event->after->toIso8601String(); Log::debug(sprintf('Converted "before" to "%s".', $event->before)); Log::debug(sprintf('Converted "after" to "%s".', $event->after)); } diff --git a/app/Handlers/Events/AutomationHandler.php b/app/Handlers/Events/AutomationHandler.php index 788d463a90..f441d22c89 100644 --- a/app/Handlers/Events/AutomationHandler.php +++ b/app/Handlers/Events/AutomationHandler.php @@ -50,11 +50,11 @@ class AutomationHandler Log::debug('In reportJournals.'); /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $repository->find($event->userId); + $repository = app(UserRepositoryInterface::class); + $user = $repository->find($event->userId); /** @var bool $sendReport */ - $sendReport = Preferences::getForUser($user, 'notification_transaction_creation', false)->data; + $sendReport = Preferences::getForUser($user, 'notification_transaction_creation', false)->data; if (false === $sendReport) { Log::debug('Not sending report, because config says so.'); diff --git a/app/Handlers/Events/DestroyedGroupEventHandler.php b/app/Handlers/Events/DestroyedGroupEventHandler.php index 49af9c93bb..18b4144709 100644 --- a/app/Handlers/Events/DestroyedGroupEventHandler.php +++ b/app/Handlers/Events/DestroyedGroupEventHandler.php @@ -47,8 +47,8 @@ class DestroyedGroupEventHandler private function triggerWebhooks(DestroyedTransactionGroup $destroyedGroupEvent): void { Log::debug('DestroyedTransactionGroup:triggerWebhooks'); - $group = $destroyedGroupEvent->transactionGroup; - $user = $group->user; + $group = $destroyedGroupEvent->transactionGroup; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/PreferencesEventHandler.php b/app/Handlers/Events/PreferencesEventHandler.php index 23e2cbfc5d..47ab58adcd 100644 --- a/app/Handlers/Events/PreferencesEventHandler.php +++ b/app/Handlers/Events/PreferencesEventHandler.php @@ -47,7 +47,7 @@ class PreferencesEventHandler // !!! this array is also in the migration 'accounts' => ['native_virtual_balance'], 'available_budgets' => ['native_amount'], - 'bills' => ['native_amount_min', 'native_amount_max'] + 'bills' => ['native_amount_min', 'native_amount_max'], ]; foreach ($tables as $table => $columns) { foreach ($columns as $column) { @@ -103,7 +103,7 @@ class PreferencesEventHandler { $repository = app(BudgetRepositoryInterface::class); $repository->setUserGroup($userGroup); - $set = $repository->getBudgets(); + $set = $repository->getBudgets(); Log::debug(sprintf('Resetting %d budget(s).', $set->count())); @@ -136,7 +136,8 @@ class PreferencesEventHandler ->where(static function (Builder $q): void { $q->whereNotNull('native_amount')->orWhereNotNull('native_foreign_amount'); }) - ->update(['native_amount' => null, 'native_foreign_amount' => null]); + ->update(['native_amount' => null, 'native_foreign_amount' => null]) + ; Log::debug(sprintf('Reset %d transactions.', $success)); } } diff --git a/app/Handlers/Events/StoredAccountEventHandler.php b/app/Handlers/Events/StoredAccountEventHandler.php index bb81b22cec..574148def2 100644 --- a/app/Handlers/Events/StoredAccountEventHandler.php +++ b/app/Handlers/Events/StoredAccountEventHandler.php @@ -37,7 +37,7 @@ class StoredAccountEventHandler $account = $event->account; /** @var CreditRecalculateService $object */ - $object = app(CreditRecalculateService::class); + $object = app(CreditRecalculateService::class); $object->setAccount($account); $object->recalculate(); } diff --git a/app/Handlers/Events/StoredGroupEventHandler.php b/app/Handlers/Events/StoredGroupEventHandler.php index 677e4748d6..014dc63ae6 100644 --- a/app/Handlers/Events/StoredGroupEventHandler.php +++ b/app/Handlers/Events/StoredGroupEventHandler.php @@ -62,7 +62,7 @@ class StoredGroupEventHandler /** * This method grabs all the users rules and processes them. */ - private function processRules(StoredTransactionGroup $storedGroupEvent, null|RuleGroup $ruleGroup): void + private function processRules(StoredTransactionGroup $storedGroupEvent, ?RuleGroup $ruleGroup): void { if (false === $storedGroupEvent->applyRules) { Log::info(sprintf('Will not run rules on group #%d', $storedGroupEvent->transactionGroup->id)); @@ -71,14 +71,14 @@ class StoredGroupEventHandler } Log::debug('Now in StoredGroupEventHandler::processRules()'); - $journals = $storedGroupEvent->transactionGroup->transactionJournals; - $array = []; + $journals = $storedGroupEvent->transactionGroup->transactionJournals; + $array = []; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $array[] = $journal->id; } - $journalIds = implode(',', $array); + $journalIds = implode(',', $array); Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds)); // collect rules: @@ -97,7 +97,7 @@ class StoredGroupEventHandler } // create and fire rule engine. - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($storedGroupEvent->transactionGroup->user); $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->setRuleGroups($groups); @@ -106,7 +106,7 @@ class StoredGroupEventHandler private function recalculateCredit(StoredTransactionGroup $event): void { - $group = $event->transactionGroup; + $group = $event->transactionGroup; /** @var CreditRecalculateService $object */ $object = app(CreditRecalculateService::class); @@ -122,10 +122,10 @@ class StoredGroupEventHandler /** @var TransactionJournal $journal */ foreach ($event->transactionGroup->transactionJournals as $journal) { /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', '0')->first(); + $source = $journal->transactions()->where('amount', '<', '0')->first(); /** @var null|Transaction $dest */ - $dest = $journal->transactions()->where('amount', '>', '0')->first(); + $dest = $journal->transactions()->where('amount', '>', '0')->first(); if (null !== $source) { $repository->deleteStatisticsForModel($source->account, $journal->date); @@ -160,14 +160,14 @@ class StoredGroupEventHandler private function triggerWebhooks(StoredTransactionGroup $storedGroupEvent): void { Log::debug(__METHOD__); - $group = $storedGroupEvent->transactionGroup; + $group = $storedGroupEvent->transactionGroup; if (false === $storedGroupEvent->fireWebhooks) { Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); return; } - $user = $group->user; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/UpdatedAccountEventHandler.php b/app/Handlers/Events/UpdatedAccountEventHandler.php index e949c02e6b..59c137e817 100644 --- a/app/Handlers/Events/UpdatedAccountEventHandler.php +++ b/app/Handlers/Events/UpdatedAccountEventHandler.php @@ -37,7 +37,7 @@ class UpdatedAccountEventHandler $account = $event->account; /** @var CreditRecalculateService $object */ - $object = app(CreditRecalculateService::class); + $object = app(CreditRecalculateService::class); $object->setAccount($account); $object->recalculate(); } diff --git a/app/Handlers/Events/UpdatedGroupEventHandler.php b/app/Handlers/Events/UpdatedGroupEventHandler.php index f1c1eaf031..d9e7b3c33a 100644 --- a/app/Handlers/Events/UpdatedGroupEventHandler.php +++ b/app/Handlers/Events/UpdatedGroupEventHandler.php @@ -67,8 +67,8 @@ class UpdatedGroupEventHandler /** @var TransactionJournal $journal */ foreach ($event->transactionGroup->transactionJournals as $journal) { - $source = $journal->transactions()->where('amount', '<', '0')->first(); - $dest = $journal->transactions()->where('amount', '>', '0')->first(); + $source = $journal->transactions()->where('amount', '<', '0')->first(); + $dest = $journal->transactions()->where('amount', '>', '0')->first(); if (null !== $source) { $repository->deleteStatisticsForModel($source->account, $journal->date); } @@ -103,20 +103,21 @@ class UpdatedGroupEventHandler */ public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void { - $group = $updatedGroupEvent->transactionGroup; + $group = $updatedGroupEvent->transactionGroup; if (1 === $group->transactionJournals->count()) { return; } // first journal: /** @var null|TransactionJournal $first */ - $first = $group + $first = $group ->transactionJournals() ->orderBy('transaction_journals.date', 'DESC') ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->first(); + ->first() + ; if (null === $first) { Log::warning(sprintf('Group #%d has no transaction journals.', $group->id)); @@ -124,15 +125,15 @@ class UpdatedGroupEventHandler return; } - $all = $group->transactionJournals()->get()->pluck('id')->toArray(); + $all = $group->transactionJournals()->get()->pluck('id')->toArray(); /** @var Account $sourceAccount */ $sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account; /** @var Account $destAccount */ - $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; + $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; - $type = $first->transactionType->type; + $type = $first->transactionType->type; if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) { // set all source transactions to source account: Transaction::whereIn('transaction_journal_id', $all)->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id]); @@ -154,24 +155,24 @@ class UpdatedGroupEventHandler return; } - $journals = $updatedGroupEvent->transactionGroup->transactionJournals; - $array = []; + $journals = $updatedGroupEvent->transactionGroup->transactionJournals; + $array = []; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $array[] = $journal->id; } - $journalIds = implode(',', $array); + $journalIds = implode(',', $array); Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds)); // collect rules: $ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user); - $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); + $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); // file rule engine. - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user); $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->setRuleGroups($groups); @@ -180,7 +181,7 @@ class UpdatedGroupEventHandler private function recalculateCredit(UpdatedTransactionGroup $event): void { - $group = $event->transactionGroup; + $group = $event->transactionGroup; /** @var CreditRecalculateService $object */ $object = app(CreditRecalculateService::class); @@ -191,13 +192,13 @@ class UpdatedGroupEventHandler private function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void { Log::debug(__METHOD__); - $group = $updatedGroupEvent->transactionGroup; + $group = $updatedGroupEvent->transactionGroup; if (false === $updatedGroupEvent->fireWebhooks) { Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); return; } - $user = $group->user; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 42821d354f..4345df507a 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -52,8 +52,8 @@ class UserEventHandler $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = $event->user; - $count = $repository->count(); + $user = $event->user; + $count = $repository->count(); // only act when there is 1 user in the system and he has no admin rights. if (1 === $count && !$repository->hasRole($user, 'owner')) { @@ -80,7 +80,7 @@ class UserEventHandler $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = $event->user; + $user = $event->user; if ($repository->hasRole($user, 'demo')) { // set user back to English. Preferences::setForUser($user, 'language', 'en_US'); diff --git a/app/Handlers/Events/VersionCheckEventHandler.php b/app/Handlers/Events/VersionCheckEventHandler.php index 51d47812da..824a98c676 100644 --- a/app/Handlers/Events/VersionCheckEventHandler.php +++ b/app/Handlers/Events/VersionCheckEventHandler.php @@ -55,8 +55,8 @@ class VersionCheckEventHandler Log::debug('Now in checkForUpdates()'); // should not check for updates: - $permission = FireflyConfig::get('permission_update_check', -1); - $value = (int) $permission->data; + $permission = FireflyConfig::get('permission_update_check', -1); + $value = (int) $permission->data; if (1 !== $value) { Log::debug('Update check is not enabled.'); $this->warnToCheckForUpdates($event); @@ -65,8 +65,8 @@ class VersionCheckEventHandler } /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $event->user; + $repository = app(UserRepositoryInterface::class); + $user = $event->user; if (!$repository->hasRole($user, 'owner')) { Log::debug('User is not admin, done.'); @@ -85,7 +85,7 @@ class VersionCheckEventHandler } // last check time was more than a week ago. Log::debug('Have not checked for a new version in a week!'); - $release = $this->getLatestRelease(); + $release = $this->getLatestRelease(); session()->flash($release['level'], $release['message']); FireflyConfig::set('last_update_check', Carbon::now()->getTimestamp()); @@ -99,8 +99,8 @@ class VersionCheckEventHandler protected function warnToCheckForUpdates(RequestedVersionCheckStatus $event): void { /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $event->user; + $repository = app(UserRepositoryInterface::class); + $user = $event->user; if (!$repository->hasRole($user, 'owner')) { Log::debug('User is not admin, done.'); diff --git a/app/Handlers/Events/WebhookEventHandler.php b/app/Handlers/Events/WebhookEventHandler.php index f8b45b2d05..29fab920b3 100644 --- a/app/Handlers/Events/WebhookEventHandler.php +++ b/app/Handlers/Events/WebhookEventHandler.php @@ -49,8 +49,9 @@ class WebhookEventHandler // kick off the job! $messages = WebhookMessage::where('webhook_messages.sent', false) ->get(['webhook_messages.*']) - ->filter(static fn(WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) - ->splice(0, 5); + ->filter(static fn (WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) + ->splice(0, 5) + ; Log::debug(sprintf('Found %d webhook message(s) ready to be send.', $messages->count())); /** @var WebhookMessage $message */ diff --git a/app/Handlers/Observer/AccountObserver.php b/app/Handlers/Observer/AccountObserver.php index 4e57308f22..25f5492ba4 100644 --- a/app/Handlers/Observer/AccountObserver.php +++ b/app/Handlers/Observer/AccountObserver.php @@ -61,13 +61,13 @@ class AccountObserver && '' !== (string) $account->virtual_balance && 0 !== bccomp($account->virtual_balance, '0') ) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($account->user->userGroup); $converter->setIgnoreSettings(true); $account->native_virtual_balance = $converter->convert($currency, $userCurrency, today(), $account->virtual_balance); } if ('' === (string) $account->virtual_balance || 0 === bccomp($account->virtual_balance, '0')) { - $account->virtual_balance = null; + $account->virtual_balance = null; $account->native_virtual_balance = null; } $account->saveQuietly(); @@ -95,11 +95,13 @@ class AccountObserver $journalIds = Transaction::where('account_id', $account->id) ->get(['transactions.transaction_journal_id']) ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $groupIds = TransactionJournal::whereIn('id', $journalIds) ->get(['transaction_journals.transaction_group_id']) ->pluck('transaction_group_id') - ->toArray(); // @phpstan-ignore-line + ->toArray() // @phpstan-ignore-line + ; if (count($journalIds) > 0) { Transaction::whereIn('transaction_journal_id', $journalIds)->delete(); diff --git a/app/Handlers/Observer/AutoBudgetObserver.php b/app/Handlers/Observer/AutoBudgetObserver.php index deb565eeb0..fd838dcd68 100644 --- a/app/Handlers/Observer/AutoBudgetObserver.php +++ b/app/Handlers/Observer/AutoBudgetObserver.php @@ -42,10 +42,10 @@ class AutoBudgetObserver if (!Amount::convertToPrimary($autoBudget->budget->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($autoBudget->budget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($autoBudget->budget->user->userGroup); $autoBudget->native_amount = null; if ($autoBudget->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($autoBudget->budget->user->userGroup); $converter->setIgnoreSettings(true); $autoBudget->native_amount = $converter->convert($autoBudget->transactionCurrency, $userCurrency, today(), $autoBudget->amount); diff --git a/app/Handlers/Observer/AvailableBudgetObserver.php b/app/Handlers/Observer/AvailableBudgetObserver.php index 9d60fff3de..f9eb735b2f 100644 --- a/app/Handlers/Observer/AvailableBudgetObserver.php +++ b/app/Handlers/Observer/AvailableBudgetObserver.php @@ -44,10 +44,10 @@ class AvailableBudgetObserver return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($availableBudget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($availableBudget->user->userGroup); $availableBudget->native_amount = null; if ($availableBudget->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($availableBudget->user->userGroup); $converter->setIgnoreSettings(true); $availableBudget->native_amount = $converter->convert($availableBudget->transactionCurrency, $userCurrency, today(), $availableBudget->amount); diff --git a/app/Handlers/Observer/BillObserver.php b/app/Handlers/Observer/BillObserver.php index 8b28bc32ea..ea9c8bf4e0 100644 --- a/app/Handlers/Observer/BillObserver.php +++ b/app/Handlers/Observer/BillObserver.php @@ -46,11 +46,11 @@ class BillObserver if (!Amount::convertToPrimary($bill->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); $bill->native_amount_min = null; $bill->native_amount_max = null; if ($bill->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($bill->user->userGroup); $converter->setIgnoreSettings(true); $bill->native_amount_min = $converter->convert($bill->transactionCurrency, $userCurrency, today(), $bill->amount_min); diff --git a/app/Handlers/Observer/BudgetLimitObserver.php b/app/Handlers/Observer/BudgetLimitObserver.php index cfe5f47130..6c85bc0fc1 100644 --- a/app/Handlers/Observer/BudgetLimitObserver.php +++ b/app/Handlers/Observer/BudgetLimitObserver.php @@ -49,7 +49,7 @@ class BudgetLimitObserver $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_bl_store')) { - $user = $budgetLimit->budget->user; + $user = $budgetLimit->budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -70,10 +70,10 @@ class BudgetLimitObserver return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($budgetLimit->budget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($budgetLimit->budget->user->userGroup); $budgetLimit->native_amount = null; if ($budgetLimit->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($budgetLimit->budget->user->userGroup); $converter->setIgnoreSettings(true); $budgetLimit->native_amount = $converter->convert($budgetLimit->transactionCurrency, $userCurrency, today(), $budgetLimit->amount); @@ -92,7 +92,7 @@ class BudgetLimitObserver $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_bl_update')) { - $user = $budgetLimit->budget->user; + $user = $budgetLimit->budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Observer/BudgetObserver.php b/app/Handlers/Observer/BudgetObserver.php index f1772bf0c0..2a78e1f4be 100644 --- a/app/Handlers/Observer/BudgetObserver.php +++ b/app/Handlers/Observer/BudgetObserver.php @@ -51,7 +51,7 @@ class BudgetObserver if (true === $singleton->getPreference('fire_webhooks_budget_create')) { // fire event. - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -72,7 +72,7 @@ class BudgetObserver $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_budget_update')) { - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -89,10 +89,10 @@ class BudgetObserver { Log::debug('Observe "deleting" of a budget.'); - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ - $engine = app(MessageGeneratorInterface::class); + $engine = app(MessageGeneratorInterface::class); $engine->setUser($user); $engine->setObjects(new Collection()->push($budget)); $engine->setTrigger(WebhookTrigger::DESTROY_BUDGET); @@ -100,7 +100,7 @@ class BudgetObserver Log::debug(sprintf('send event RequestedSendWebhookMessages from %s', __METHOD__)); event(new RequestedSendWebhookMessages()); - $repository = app(AttachmentRepositoryInterface::class); + $repository = app(AttachmentRepositoryInterface::class); $repository->setUser($budget->user); /** @var Attachment $attachment */ @@ -112,7 +112,7 @@ class BudgetObserver /** @var BudgetLimit $budgetLimit */ foreach ($budgetLimits as $budgetLimit) { // this loop exists so several events are fired. - $copy = clone $budgetLimit; + $copy = clone $budgetLimit; $copy->id = 0; $this->updateAvailableBudget($copy); $budgetLimit->deleteQuietly(); // delete is quietly when in a loop. diff --git a/app/Handlers/Observer/PiggyBankEventObserver.php b/app/Handlers/Observer/PiggyBankEventObserver.php index 4295fdc676..0aab702717 100644 --- a/app/Handlers/Observer/PiggyBankEventObserver.php +++ b/app/Handlers/Observer/PiggyBankEventObserver.php @@ -39,7 +39,7 @@ class PiggyBankEventObserver private function updatePrimaryCurrencyAmount(PiggyBankEvent $event): void { - $user = $event->piggyBank->accounts()->first()?->user; + $user = $event->piggyBank->accounts()->first()?->user; if (null === $user) { Log::warning('Piggy bank seems to have no accounts. Break.'); @@ -48,10 +48,10 @@ class PiggyBankEventObserver if (!Amount::convertToPrimary($user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); $event->native_amount = null; if ($event->piggyBank->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($event->piggyBank->accounts()->first()->user->userGroup); $converter->setIgnoreSettings(true); $event->native_amount = $converter->convert($event->piggyBank->transactionCurrency, $userCurrency, today(), $event->amount); diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php index 9a3159ceda..b5d14fd8ed 100644 --- a/app/Handlers/Observer/PiggyBankObserver.php +++ b/app/Handlers/Observer/PiggyBankObserver.php @@ -44,16 +44,16 @@ class PiggyBankObserver private function updatePrimaryCurrencyAmount(PiggyBank $piggyBank): void { - $group = $piggyBank->accounts()->first()?->user->userGroup; + $group = $piggyBank->accounts()->first()?->user->userGroup; if (null === $group) { Log::debug(sprintf('No account(s) yet for piggy bank #%d.', $piggyBank->id)); return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($group); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($group); $piggyBank->native_target_amount = null; if ($piggyBank->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $converter->setUserGroup($group); $piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount); diff --git a/app/Handlers/Observer/TransactionObserver.php b/app/Handlers/Observer/TransactionObserver.php index 4bf674defb..97f81bf08b 100644 --- a/app/Handlers/Observer/TransactionObserver.php +++ b/app/Handlers/Observer/TransactionObserver.php @@ -61,8 +61,8 @@ class TransactionObserver if (!Amount::convertToPrimary($transaction->transactionJournal->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); - $transaction->native_amount = null; + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); + $transaction->native_amount = null; $transaction->native_foreign_amount = null; // first normal amount if ( @@ -73,7 +73,7 @@ class TransactionObserver && $transaction->foreign_currency_id !== $userCurrency->id ) ) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($transaction->transactionJournal->user->userGroup); $converter->setIgnoreSettings(true); $transaction->native_amount = $converter->convert( @@ -85,7 +85,7 @@ class TransactionObserver } // then foreign amount if ($transaction->foreignCurrency?->id !== $userCurrency->id && null !== $transaction->foreign_amount && null !== $transaction->foreignCurrency) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($transaction->transactionJournal->user->userGroup); $converter->setIgnoreSettings(true); $transaction->native_foreign_amount = $converter->convert( @@ -100,7 +100,7 @@ class TransactionObserver Log::debug(sprintf('Transaction #%d primary currency amounts are updated.', $transaction->id)); } - public function deleting(null|Transaction $transaction): void + public function deleting(?Transaction $transaction): void { Log::debug('Observe "deleting" of a transaction.'); $transaction?->transactionJournal?->delete(); diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index beeecdb684..1e84e2b457 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -66,11 +66,11 @@ class AttachmentHelper implements AttachmentHelperInterface public function __construct() { $this->maxUploadSize = (int) config('firefly.maxUploadSize'); - $this->allowedMimes = (array) config('firefly.allowedMimes'); - $this->errors = new MessageBag(); - $this->messages = new MessageBag(); - $this->attachments = new Collection(); - $this->uploadDisk = Storage::disk('upload'); + $this->allowedMimes = (array) config('firefly.allowedMimes'); + $this->errors = new MessageBag(); + $this->messages = new MessageBag(); + $this->attachments = new Collection(); + $this->uploadDisk = Storage::disk('upload'); } /** @@ -143,7 +143,7 @@ class AttachmentHelper implements AttachmentHelperInterface return false; } - $path = stream_get_meta_data($resource)['uri']; + $path = stream_get_meta_data($resource)['uri']; Log::debug(sprintf('Path is %s', $path)); try { @@ -162,8 +162,8 @@ class AttachmentHelper implements AttachmentHelperInterface return false; } - $mime = (string) finfo_file($finfo, $path); - $allowedMime = config('firefly.allowedMimes'); + $mime = (string) finfo_file($finfo, $path); + $allowedMime = config('firefly.allowedMimes'); if (!in_array($mime, $allowedMime, true)) { Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime)); fclose($resource); @@ -172,15 +172,15 @@ class AttachmentHelper implements AttachmentHelperInterface } Log::debug(sprintf('Found mime "%s" in file "%s"', $mime, $path)); // is allowed? Save the file, without encryption. - $parts = explode('/', $attachment->fileName()); - $file = $parts[count($parts) - 1]; + $parts = explode('/', $attachment->fileName()); + $file = $parts[count($parts) - 1]; Log::debug(sprintf('Write file to disk in file named "%s"', $file)); $this->uploadDisk->put($file, $content); // update attachment. - $attachment->md5 = md5_file($path); - $attachment->mime = $mime; - $attachment->size = strlen($content); + $attachment->md5 = md5_file($path); + $attachment->mime = $mime; + $attachment->size = strlen($content); $attachment->uploaded = true; $attachment->save(); @@ -194,7 +194,7 @@ class AttachmentHelper implements AttachmentHelperInterface * * @throws FireflyException */ - public function saveAttachmentsForModel(object $model, null|array $files): bool + public function saveAttachmentsForModel(object $model, ?array $files): bool { if (!$model instanceof Model) { return false; @@ -224,30 +224,30 @@ class AttachmentHelper implements AttachmentHelperInterface * * @throws StringsException */ - protected function processFile(UploadedFile $file, Model $model): null|Attachment + protected function processFile(UploadedFile $file, Model $model): ?Attachment { Log::debug('Now in processFile()'); $validation = $this->validateUpload($file, $model); $attachment = null; if ($validation) { - $user = $model->user; + $user = $model->user; // ignore lines about polymorphic calls. if ($model instanceof PiggyBank) { $user = $model->account->user; } - $attachment = new Attachment(); // create Attachment object. + $attachment = new Attachment(); // create Attachment object. $attachment->user()->associate($user); $attachment->attachable()->associate($model); - $attachment->md5 = md5_file($file->getRealPath()); + $attachment->md5 = md5_file($file->getRealPath()); $attachment->filename = $file->getClientOriginalName(); - $attachment->mime = $file->getMimeType(); - $attachment->size = $file->getSize(); + $attachment->mime = $file->getMimeType(); + $attachment->size = $file->getSize(); $attachment->uploaded = false; $attachment->save(); Log::debug('Created attachment:', $attachment->toArray()); - $fileObject = $file->openFile(); + $fileObject = $file->openFile(); $fileObject->rewind(); if (0 === $file->getSize()) { @@ -256,7 +256,7 @@ class AttachmentHelper implements AttachmentHelperInterface return null; } - $content = (string) $fileObject->fread($file->getSize()); + $content = (string) $fileObject->fread($file->getSize()); Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize())); // store it without encryption. @@ -265,8 +265,8 @@ class AttachmentHelper implements AttachmentHelperInterface $attachment->save(); $this->attachments->push($attachment); - $name = e($file->getClientOriginalName()); // add message: - $msg = (string) trans('validation.file_attached', ['name' => $name]); + $name = e($file->getClientOriginalName()); // add message: + $msg = (string) trans('validation.file_attached', ['name' => $name]); $this->messages->add('attachments', $msg); } @@ -306,14 +306,14 @@ class AttachmentHelper implements AttachmentHelperInterface protected function validMime(UploadedFile $file): bool { Log::debug('Now in validMime()'); - $mime = e($file->getMimeType()); - $name = e($file->getClientOriginalName()); + $mime = e($file->getMimeType()); + $name = e($file->getClientOriginalName()); Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime)); Log::debug('Valid mimes are', $this->allowedMimes); $result = true; if (!in_array($mime, $this->allowedMimes, true)) { - $msg = (string) trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); + $msg = (string) trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); $this->errors->add('attachments', $msg); Log::error($msg); @@ -332,7 +332,7 @@ class AttachmentHelper implements AttachmentHelperInterface $name = e($file->getClientOriginalName()); $result = true; if ($size > $this->maxUploadSize) { - $msg = (string) trans('validation.file_too_large', ['name' => $name]); + $msg = (string) trans('validation.file_too_large', ['name' => $name]); $this->errors->add('attachments', $msg); Log::error($msg); @@ -347,10 +347,10 @@ class AttachmentHelper implements AttachmentHelperInterface */ protected function hasFile(UploadedFile $file, Model $model): bool { - $md5 = md5_file($file->getRealPath()); - $name = $file->getClientOriginalName(); - $class = $model::class; - $count = 0; + $md5 = md5_file($file->getRealPath()); + $name = $file->getClientOriginalName(); + $class = $model::class; + $count = 0; // ignore lines about polymorphic calls. if ($model instanceof PiggyBank) { $count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); @@ -360,7 +360,7 @@ class AttachmentHelper implements AttachmentHelperInterface } $result = false; if ($count > 0) { - $msg = (string) trans('validation.file_already_attached', ['name' => $name]); + $msg = (string) trans('validation.file_already_attached', ['name' => $name]); $this->errors->add('attachments', $msg); Log::error($msg); $result = true; diff --git a/app/Helpers/Attachments/AttachmentHelperInterface.php b/app/Helpers/Attachments/AttachmentHelperInterface.php index 2434f75ef1..4640d5deb8 100644 --- a/app/Helpers/Attachments/AttachmentHelperInterface.php +++ b/app/Helpers/Attachments/AttachmentHelperInterface.php @@ -65,5 +65,5 @@ interface AttachmentHelperInterface /** * Save attachments that got uploaded. */ - public function saveAttachmentsForModel(object $model, null|array $files): bool; + public function saveAttachmentsForModel(object $model, ?array $files): bool; } diff --git a/app/Helpers/Collector/Extensions/AccountCollection.php b/app/Helpers/Collector/Extensions/AccountCollection.php index 4a02c20357..8a57ff8ca8 100644 --- a/app/Helpers/Collector/Extensions/AccountCollection.php +++ b/app/Helpers/Collector/Extensions/AccountCollection.php @@ -47,7 +47,7 @@ trait AccountCollection * * @return bool */ - $filter = static function (array $object) use ($direction, $operator, $value): bool { + $filter = static function (array $object) use ($direction, $operator, $value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { $key = sprintf('%s_account_id', $direction); @@ -58,7 +58,7 @@ trait AccountCollection // in theory, this could lead to finding other users accounts. /** @var null|Account $account */ - $account = Account::find($accountId); + $account = Account::find($accountId); if (null === $account) { continue; } @@ -67,14 +67,14 @@ trait AccountCollection // the balance must be found BEFORE the transaction date. // so inclusive = false Log::debug(sprintf('accountBalanceIs: Call accountsBalancesOptimized with date/time "%s"', $transaction['date']->toIso8601String())); - $balance = Steam::accountsBalancesOptimized( + $balance = Steam::accountsBalancesOptimized( new Collection()->push($account), $transaction['date'], convertToPrimary: null, inclusive: false )[$account->id]; // $balance = Steam::finalAccountBalance($account, $date); - $result = bccomp((string) $balance['balance'], $value); + $result = bccomp((string) $balance['balance'], $value); Log::debug(sprintf('"%s" vs "%s" is %d', $balance['balance'], $value, $result)); switch ($operator) { @@ -293,18 +293,18 @@ trait AccountCollection $this->query->leftJoin('account_types as source_account_type', 'source_account_type.id', '=', 'source_account.account_type_id'); // add source account fields: - $this->fields[] = 'source_account.name as source_account_name'; - $this->fields[] = 'source_account.iban as source_account_iban'; - $this->fields[] = 'source_account_type.type as source_account_type'; + $this->fields[] = 'source_account.name as source_account_name'; + $this->fields[] = 'source_account.iban as source_account_iban'; + $this->fields[] = 'source_account_type.type as source_account_type'; // same for dest $this->query->leftJoin('accounts as dest_account', 'dest_account.id', '=', 'destination.account_id'); $this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id'); // and add fields: - $this->fields[] = 'dest_account.name as destination_account_name'; - $this->fields[] = 'dest_account.iban as destination_account_iban'; - $this->fields[] = 'dest_account_type.type as destination_account_type'; + $this->fields[] = 'dest_account.name as destination_account_name'; + $this->fields[] = 'dest_account.iban as destination_account_iban'; + $this->fields[] = 'dest_account_type.type as destination_account_type'; $this->hasAccountInfo = true; } diff --git a/app/Helpers/Collector/Extensions/AttachmentCollection.php b/app/Helpers/Collector/Extensions/AttachmentCollection.php index b512cd9a9c..09ebe86911 100644 --- a/app/Helpers/Collector/Extensions/AttachmentCollection.php +++ b/app/Helpers/Collector/Extensions/AttachmentCollection.php @@ -45,13 +45,13 @@ trait AttachmentCollection * * @return bool */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - str_contains(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = str_contains(strtolower((string) $attachment['filename']), strtolower($name)) || str_contains(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -94,7 +94,8 @@ trait AttachmentCollection // $q1->where('attachments.uploaded', true); // $q1->whereNull('attachments.deleted_at'); $q1->orWhereNull('attachments.attachable_type'); - }); + }) + ; } } @@ -122,13 +123,13 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - !str_contains(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = !str_contains(strtolower((string) $attachment['filename']), strtolower($name)) && !str_contains(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -155,13 +156,13 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - !str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = !str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) && !str_ends_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -188,13 +189,13 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - !str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = !str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) && !str_starts_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -213,13 +214,13 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) || str_ends_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -238,7 +239,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -261,7 +262,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -284,13 +285,13 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = - str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) + $result + = str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) || str_starts_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; @@ -309,7 +310,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -333,7 +334,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -357,7 +358,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -381,7 +382,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -405,7 +406,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -429,7 +430,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -453,7 +454,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -477,7 +478,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ diff --git a/app/Helpers/Collector/Extensions/CollectorProperties.php b/app/Helpers/Collector/Extensions/CollectorProperties.php index 8f7745e4d5..f6ccb5780e 100644 --- a/app/Helpers/Collector/Extensions/CollectorProperties.php +++ b/app/Helpers/Collector/Extensions/CollectorProperties.php @@ -38,7 +38,7 @@ trait CollectorProperties /** @var array */ public array $sorting; private array $booleanFields; - private null|int $endRow; + private ?int $endRow; private bool $expandGroupSearch; private array $fields; private bool $hasAccountInfo; @@ -50,11 +50,11 @@ trait CollectorProperties private bool $hasJoinedTagTables; private bool $hasNotesInformation; private array $integerFields; - private null|int $limit; - private null|int $page; + private ?int $limit; + private ?int $page; private array $postFilters; private HasMany $query; - private null|int $startRow; + private ?int $startRow; private array $stringFields; /* * This array is used to collect ALL tags the user may search for (using 'setTags'). @@ -63,6 +63,6 @@ trait CollectorProperties */ private array $tags; private int $total; - private null|User $user; - private null|UserGroup $userGroup; + private ?User $user; + private ?UserGroup $userGroup; } diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php index 0a7005b91e..99aea4872b 100644 --- a/app/Helpers/Collector/Extensions/MetaCollection.php +++ b/app/Helpers/Collector/Extensions/MetaCollection.php @@ -63,8 +63,8 @@ trait MetaCollection // join bill table $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id'); // add fields - $this->fields[] = 'bills.id as bill_id'; - $this->fields[] = 'bills.name as bill_name'; + $this->fields[] = 'bills.id as bill_id'; + $this->fields[] = 'bills.name as bill_name'; $this->hasBillInformation = true; } @@ -97,8 +97,8 @@ trait MetaCollection // join cat table $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id'); // add fields - $this->fields[] = 'budgets.id as budget_id'; - $this->fields[] = 'budgets.name as budget_name'; + $this->fields[] = 'budgets.id as budget_id'; + $this->fields[] = 'budgets.name as budget_name'; $this->hasBudgetInformation = true; } @@ -142,8 +142,8 @@ trait MetaCollection // join cat table $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id'); // add fields - $this->fields[] = 'categories.id as category_id'; - $this->fields[] = 'categories.name as category_name'; + $this->fields[] = 'categories.id as category_id'; + $this->fields[] = 'categories.name as category_name'; $this->hasCatInformation = true; } @@ -183,8 +183,8 @@ trait MetaCollection if (false === $this->hasJoinedMetaTables) { $this->hasJoinedMetaTables = true; $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - $this->fields[] = 'journal_meta.name as meta_name'; - $this->fields[] = 'journal_meta.data as meta_data'; + $this->fields[] = 'journal_meta.name as meta_name'; + $this->fields[] = 'journal_meta.data as meta_data'; } } @@ -497,7 +497,7 @@ trait MetaCollection $join->whereNull('notes.deleted_at'); }); // add fields - $this->fields[] = 'notes.text as notes'; + $this->fields[] = 'notes.text as notes'; $this->hasNotesInformation = true; } @@ -582,16 +582,16 @@ trait MetaCollection $this->query->whereNotNull('tag_transaction_journal.tag_id'); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool|array { - $includedJournals = []; - $return = $object; + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool|array { + $includedJournals = []; + $return = $object; unset($return['transactions']); $return['transactions'] = []; Log::debug(sprintf('Now in setAllTags(%s) filter', implode(', ', $list))); - $expectedTagCount = count($list); - $foundTagCount = 0; + $expectedTagCount = count($list); + $foundTagCount = 0; foreach ($object['transactions'] as $transaction) { $transactionTagCount = count($transaction['tags']); Log::debug(sprintf('Transaction #%d has %d tag(s)', $transaction['transaction_journal_id'], $transactionTagCount)); @@ -608,7 +608,7 @@ trait MetaCollection $journalId = $transaction['transaction_journal_id']; // #8377 prevent adding a transaction twice when multiple tag searches find this transaction if (!in_array($journalId, $includedJournals, true)) { - $includedJournals[] = $journalId; + $includedJournals[] = $journalId; $return['transactions'][] = $transaction; } } @@ -617,7 +617,7 @@ trait MetaCollection Log::debug(sprintf('Found %d tags, need at least %d.', $foundTagCount, $expectedTagCount)); // found at least the expected tags. - $result = $foundTagCount >= $expectedTagCount; + $result = $foundTagCount >= $expectedTagCount; if ($result) { return $return; } @@ -776,9 +776,9 @@ trait MetaCollection $this->query->whereIn('tag_transaction_journal.tag_id', $tags->pluck('id')->toArray()); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool { + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool { Log::debug(sprintf('Now in setTags(%s) filter', implode(', ', $list))); foreach ($object['transactions'] as $transaction) { $total = count($transaction['tags']); @@ -816,9 +816,9 @@ trait MetaCollection $this->withTagInformation(); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool { + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool { Log::debug(sprintf('Now in setWithoutSpecificTags(%s) filter', implode(', ', $list))); foreach ($object['transactions'] as $transaction) { Log::debug(sprintf('Transaction has %d tag(s)', count($transaction['tags']))); diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php index 3e8180a742..e6f3b3857b 100644 --- a/app/Helpers/Collector/Extensions/TimeCollection.php +++ b/app/Helpers/Collector/Extensions/TimeCollection.php @@ -65,12 +65,12 @@ trait TimeCollection if ($end < $start) { [$start, $end] = [$end, $start]; } - $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. + $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end->endOfDay(); $start->startOfDay(); $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $start, $end): bool { + $filter = static function (array $object) use ($field, $start, $end): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { if ($transaction[$field]->lt($start)) { @@ -125,7 +125,7 @@ trait TimeCollection public function metaDayAfter(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->day >= (int) $day; @@ -142,7 +142,7 @@ trait TimeCollection public function metaDayBefore(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->day <= (int) $day; @@ -159,7 +159,7 @@ trait TimeCollection public function metaDayIs(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $day === $transaction[$field]->day; @@ -176,7 +176,7 @@ trait TimeCollection public function metaDayIsNot(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $day !== $transaction[$field]->day; @@ -193,7 +193,7 @@ trait TimeCollection public function metaMonthAfter(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->month >= (int) $month; @@ -210,7 +210,7 @@ trait TimeCollection public function metaMonthBefore(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->month <= (int) $month; @@ -227,7 +227,7 @@ trait TimeCollection public function metaMonthIs(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $month === $transaction[$field]->month; @@ -244,7 +244,7 @@ trait TimeCollection public function metaMonthIsNot(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $month !== $transaction[$field]->month; @@ -261,7 +261,7 @@ trait TimeCollection public function metaYearAfter(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->year >= (int) $year; @@ -278,7 +278,7 @@ trait TimeCollection public function metaYearBefore(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->year <= (int) $year; @@ -295,7 +295,7 @@ trait TimeCollection public function metaYearIs(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $year === (string) $transaction[$field]->year; @@ -312,7 +312,7 @@ trait TimeCollection public function metaYearIsNot(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $year !== (string) $transaction[$field]->year; @@ -490,7 +490,7 @@ trait TimeCollection { $this->withMetaDate($field); $date->startOfDay(); - $filter = static function (array $object) use ($field, $date): bool { + $filter = static function (array $object) use ($field, $date): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->gte($date); @@ -507,7 +507,7 @@ trait TimeCollection public function setMetaBefore(Carbon $date, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $date): bool { + $filter = static function (array $object) use ($field, $date): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->lte($date); @@ -526,12 +526,12 @@ trait TimeCollection if ($end < $start) { [$start, $end] = [$end, $start]; } - $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. + $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end->endOfDay(); $start->startOfDay(); $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $start, $end): bool { + $filter = static function (array $object) use ($field, $start, $end): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->gte($start) && $transaction[$field]->lte($end); @@ -576,7 +576,7 @@ trait TimeCollection * * Can either or both be NULL */ - public function setRange(null|Carbon $start, null|Carbon $end): GroupCollectorInterface + public function setRange(?Carbon $start, ?Carbon $end): GroupCollectorInterface { if ($start instanceof Carbon && $end instanceof Carbon && $end < $start) { [$start, $end] = [$end, $start]; diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index f6ef351d7b..921f8acd1a 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -68,27 +68,27 @@ class GroupCollector implements GroupCollectorInterface */ public function __construct() { - $this->sorting = []; - $this->postFilters = []; - $this->tags = []; - $this->user = null; - $this->userGroup = null; - $this->limit = null; - $this->page = null; - $this->startRow = null; - $this->endRow = null; + $this->sorting = []; + $this->postFilters = []; + $this->tags = []; + $this->user = null; + $this->userGroup = null; + $this->limit = null; + $this->page = null; + $this->startRow = null; + $this->endRow = null; - $this->hasAccountInfo = false; - $this->hasCatInformation = false; + $this->hasAccountInfo = false; + $this->hasCatInformation = false; $this->hasBudgetInformation = false; - $this->hasBillInformation = false; - $this->hasNotesInformation = false; - $this->hasJoinedTagTables = false; - $this->hasJoinedAttTables = false; - $this->expandGroupSearch = false; - $this->hasJoinedMetaTables = false; - $this->booleanFields = ['source_balance_dirty', 'destination_balance_dirty']; - $this->integerFields = [ + $this->hasBillInformation = false; + $this->hasNotesInformation = false; + $this->hasJoinedTagTables = false; + $this->hasJoinedAttTables = false; + $this->expandGroupSearch = false; + $this->hasJoinedMetaTables = false; + $this->booleanFields = ['source_balance_dirty', 'destination_balance_dirty']; + $this->integerFields = [ 'transaction_group_id', 'user_id', 'user_group_id', @@ -104,11 +104,11 @@ class GroupCollector implements GroupCollectorInterface 'destination_transaction_id', 'destination_account_id', 'category_id', - 'budget_id' + 'budget_id', ]; - $this->stringFields = ['amount', 'foreign_amount', 'pc_amount', 'pc_foreign_amount', 'source_balance_after', 'destination_balance_after']; - $this->total = 0; - $this->fields = [ + $this->stringFields = ['amount', 'foreign_amount', 'pc_amount', 'pc_foreign_amount', 'source_balance_after', 'destination_balance_after']; + $this->total = 0; + $this->fields = [ // group 'transaction_groups.id as transaction_group_id', 'transaction_groups.user_id as user_id', @@ -158,7 +158,7 @@ class GroupCollector implements GroupCollectorInterface // destination account info (always present) 'destination.account_id as destination_account_id', 'destination.balance_after as destination_balance_after', - 'destination.balance_dirty as destination_balance_dirty' + 'destination.balance_dirty as destination_balance_dirty', ]; } @@ -276,7 +276,7 @@ class GroupCollector implements GroupCollectorInterface if (is_int($param)) { $replace = (string) $param; } - $pos = strpos($query, '?'); + $pos = strpos($query, '?'); if (false !== $pos) { $query = substr_replace($query, $replace, $pos, 1); } @@ -388,7 +388,7 @@ class GroupCollector implements GroupCollectorInterface $this->query->whereNotIn('transaction_types.type', [ TransactionTypeEnum::LIABILITY_CREDIT->value, TransactionTypeEnum::OPENING_BALANCE->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ]); return $this; @@ -419,9 +419,9 @@ class GroupCollector implements GroupCollectorInterface foreach ($selection as $group) { $count = count($group['transactions']); foreach ($group['transactions'] as $journalId => $journal) { - $journal['group_title'] = $group['title']; + $journal['group_title'] = $group['title']; $journal['journals_in_group'] = $count; - $return[$journalId] = $journal; + $return[$journalId] = $journal; } } @@ -439,15 +439,15 @@ class GroupCollector implements GroupCollectorInterface // add to query: $this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds); } - $result = $this->query->get($this->fields); + $result = $this->query->get($this->fields); // now to parse this into an array. - $collection = $this->parseArray($result); + $collection = $this->parseArray($result); // filter the array using all available post filters: - $collection = $this->postFilterCollection($collection); + $collection = $this->postFilterCollection($collection); // sort the collection, if sort instructions are present. - $collection = $this->sortCollection($collection); + $collection = $this->sortCollection($collection); // count it and continue: $this->total = $collection->count(); @@ -471,7 +471,8 @@ class GroupCollector implements GroupCollectorInterface return $this->query ->get(['transaction_journals.transaction_group_id']) ->pluck('transaction_group_id') - ->toArray(); + ->toArray() + ; } /** @@ -483,15 +484,15 @@ class GroupCollector implements GroupCollectorInterface /** @var TransactionJournal $augumentedJournal */ foreach ($collection as $augumentedJournal) { - $groupId = (int) $augumentedJournal->transaction_group_id; + $groupId = (int) $augumentedJournal->transaction_group_id; if (!array_key_exists($groupId, $groups)) { // make new array - $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); - $groupArray = [ - 'id' => (int) $augumentedJournal->transaction_group_id, - 'user_id' => $augumentedJournal->user_id, - 'user_group_id' => $augumentedJournal->user_group_id, + $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); + $groupArray = [ + 'id' => (int) $augumentedJournal->transaction_group_id, + 'user_id' => $augumentedJournal->user_id, + 'user_group_id' => $augumentedJournal->user_group_id, // Field transaction_group_title was added by the query. 'title' => $augumentedJournal->transaction_group_title, 'created_at' => new Carbon($augumentedJournal->group_created_at, config('app.timezone')), @@ -499,12 +500,12 @@ class GroupCollector implements GroupCollectorInterface 'transaction_type' => $parsedGroup['transaction_type_type'], 'count' => 1, 'sums' => [], - 'transactions' => [] + 'transactions' => [], ]; // Field transaction_journal_id was added by the query. - $journalId = (int) $augumentedJournal->transaction_journal_id; + $journalId = (int) $augumentedJournal->transaction_journal_id; $groupArray['transactions'][$journalId] = $parsedGroup; - $groups[$groupId] = $groupArray; + $groups[$groupId] = $groupArray; continue; } @@ -534,18 +535,18 @@ class GroupCollector implements GroupCollectorInterface */ private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array { - $result = $augumentedJournal->toArray(); - $result['tags'] = []; - $result['attachments'] = []; + $result = $augumentedJournal->toArray(); + $result['tags'] = []; + $result['attachments'] = []; $result['interest_date'] = null; - $result['payment_date'] = null; - $result['invoice_date'] = null; - $result['book_date'] = null; - $result['due_date'] = null; - $result['process_date'] = null; + $result['payment_date'] = null; + $result['invoice_date'] = null; + $result['book_date'] = null; + $result['due_date'] = null; + $result['process_date'] = null; try { - $result['date'] = new Carbon($result['date'], 'UTC'); + $result['date'] = new Carbon($result['date'], 'UTC'); $result['created_at'] = new Carbon($result['created_at'], 'UTC'); $result['updated_at'] = new Carbon($result['updated_at'], 'UTC'); @@ -560,7 +561,7 @@ class GroupCollector implements GroupCollectorInterface } // try to process meta date value (if present) - $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; + $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) { $name = $result['meta_name']; if (array_key_exists('meta_data', $result) && '' !== (string) $result['meta_data']) { @@ -569,18 +570,18 @@ class GroupCollector implements GroupCollectorInterface } // convert values to integers: - $result = $this->convertToInteger($result); + $result = $this->convertToInteger($result); // convert to boolean - $result = $this->convertToBoolean($result); + $result = $this->convertToBoolean($result); // convert back to strings because SQLite is dumb like that. - $result = $this->convertToStrings($result); + $result = $this->convertToStrings($result); - $result['reconciled'] = 1 === (int) $result['reconciled']; + $result['reconciled'] = 1 === (int) $result['reconciled']; if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. - $tagId = (int) $augumentedJournal['tag_id']; - $tagDate = null; + $tagId = (int) $augumentedJournal['tag_id']; + $tagDate = null; try { $tagDate = Carbon::parse($augumentedJournal['tag_date']); @@ -592,7 +593,7 @@ class GroupCollector implements GroupCollectorInterface 'id' => (int) $result['tag_id'], 'name' => $result['tag_name'], 'date' => $tagDate, - 'description' => $result['tag_description'] + 'description' => $result['tag_description'], ]; } @@ -605,7 +606,7 @@ class GroupCollector implements GroupCollectorInterface $result['attachments'][$attachmentId] = [ 'id' => $attachmentId, 'filename' => $augumentedJournal['attachment_filename'], - 'title' => $augumentedJournal['attachment_title'] + 'title' => $augumentedJournal['attachment_title'], ]; } } @@ -661,9 +662,9 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well. - $tagId = (int) $newJournal['tag_id']; + $tagId = (int) $newJournal['tag_id']; - $tagDate = null; + $tagDate = null; try { $tagDate = Carbon::parse($newArray['tag_date']); @@ -675,7 +676,7 @@ class GroupCollector implements GroupCollectorInterface 'id' => (int) $newArray['tag_id'], 'name' => $newArray['tag_name'], 'date' => $tagDate, - 'description' => $newArray['tag_description'] + 'description' => $newArray['tag_description'], ]; } @@ -686,7 +687,7 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('attachment_id', $newArray)) { - $attachmentId = (int) $newJournal['attachment_id']; + $attachmentId = (int) $newJournal['attachment_id']; $existingJournal['attachments'][$attachmentId] = ['id' => $attachmentId]; } @@ -703,39 +704,39 @@ class GroupCollector implements GroupCollectorInterface foreach ($groups as $groudId => $group) { /** @var array $transaction */ foreach ($group['transactions'] as $transaction) { - $currencyId = (int) $transaction['currency_id']; + $currencyId = (int) $transaction['currency_id']; if (null === $transaction['amount']) { throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId)); } - $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']); - $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']); - $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']); + $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']); + $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']); + $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']); // set default: if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } - $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); + $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount); if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { - $currencyId = (int) $transaction['foreign_currency_id']; + $currencyId = (int) $transaction['foreign_currency_id']; // set default: if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } - $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount); + $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount); $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $pcForeignAmount); } } @@ -762,7 +763,7 @@ class GroupCollector implements GroupCollectorInterface */ foreach ($this->postFilters as $function) { Log::debug('Applying filter...'); - $nextCollection = new Collection(); + $nextCollection = new Collection(); // loop everything in the current collection // and save it (or not) in the new collection. @@ -826,7 +827,7 @@ class GroupCollector implements GroupCollectorInterface */ public function getPaginatedGroups(): LengthAwarePaginator { - $set = $this->getGroups(); + $set = $this->getGroups(); if (0 === $this->limit) { $this->setLimit(50); } @@ -941,7 +942,7 @@ class GroupCollector implements GroupCollectorInterface */ public function setPage(int $page): GroupCollectorInterface { - $page = 0 === $page ? 1 : $page; + $page = 0 === $page ? 1 : $page; $this->page = $page; // Log::debug(sprintf('GroupCollector: page is now %d', $page)); @@ -1057,7 +1058,8 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC'); + ->orderBy('source.amount', 'DESC') + ; } /** @@ -1102,7 +1104,8 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC'); + ->orderBy('source.amount', 'DESC') + ; } /** @@ -1118,7 +1121,8 @@ class GroupCollector implements GroupCollectorInterface // include budget ID + name (if any) ->withBudgetInformation() // include bill ID + name (if any) - ->withBillInformation(); + ->withBillInformation() + ; return $this; } diff --git a/app/Helpers/Fiscal/FiscalHelper.php b/app/Helpers/Fiscal/FiscalHelper.php index 1de4a90bae..b8b5910f2f 100644 --- a/app/Helpers/Fiscal/FiscalHelper.php +++ b/app/Helpers/Fiscal/FiscalHelper.php @@ -79,7 +79,7 @@ class FiscalHelper implements FiscalHelperInterface $prefStartStr = '01-01'; } $prefStartStr = (string) $prefStartStr; - [$mth, $day] = explode('-', $prefStartStr); + [$mth, $day] = explode('-', $prefStartStr); $startDate->day((int) $day)->month((int) $mth); // if start date is after passed date, sub 1 year. diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php index 1d9b6cf784..6b45698eff 100644 --- a/app/Helpers/Report/NetWorth.php +++ b/app/Helpers/Report/NetWorth.php @@ -69,31 +69,31 @@ class NetWorth implements NetWorthInterface return $cache->get(); } Log::debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d H:i:s'))); - $primary = Amount::getPrimaryCurrency(); - $netWorth = []; + $primary = Amount::getPrimaryCurrency(); + $netWorth = []; Log::debug(sprintf('NetWorth: accountsBalancesOptimized("%s")', $date->format('Y-m-d H:i:s'))); - $balances = Steam::accountsBalancesOptimized($accounts, $date, null, $convertToPrimary); + $balances = Steam::accountsBalancesOptimized($accounts, $date, null, $convertToPrimary); /** @var Account $account */ foreach ($accounts as $account) { // Log::debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name)); - $currency = $this->accountRepository->getAccountCurrency($account) ?? $primary; - $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $currency = $usePrimary ? $primary : $currency; - $currencyCode = $currency->code; - $balance = '0'; - $primaryBalance = '0'; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $primary; + $usePrimary = $convertToPrimary && $primary->id !== $currency->id; + $currency = $usePrimary ? $primary : $currency; + $currencyCode = $currency->code; + $balance = '0'; + $primaryBalance = '0'; if (array_key_exists($account->id, $balances)) { $balance = $balances[$account->id]['balance'] ?? '0'; $primaryBalance = $balances[$account->id]['pc_balance'] ?? '0'; } // Log::debug(sprintf('Balance is %s, primary balance is %s', $balance, $primaryBalance)); // always subtract virtual balance again. - $balance = '' !== (string) $account->virtual_balance ? bcsub($balance, (string) $account->virtual_balance) : $balance; - $primaryBalance = '' !== (string) $account->native_virtual_balance + $balance = '' !== (string) $account->virtual_balance ? bcsub($balance, (string) $account->virtual_balance) : $balance; + $primaryBalance = '' !== (string) $account->native_virtual_balance ? bcsub($primaryBalance, (string) $account->native_virtual_balance) : $primaryBalance; - $amountToUse = $usePrimary ? $primaryBalance : $balance; + $amountToUse = $usePrimary ? $primaryBalance : $balance; // Log::debug(sprintf('Will use %s %s', $currencyCode, $amountToUse)); $netWorth[$currencyCode] ??= [ @@ -102,7 +102,7 @@ class NetWorth implements NetWorthInterface 'currency_code' => $currency->code, 'currency_name' => $currency->name, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; $netWorth[$currencyCode]['balance'] = bcadd((string) $amountToUse, $netWorth[$currencyCode]['balance']); diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php index 6b7ec233dd..5ae3e7c431 100644 --- a/app/Helpers/Report/PopupReport.php +++ b/app/Helpers/Report/PopupReport.php @@ -51,7 +51,8 @@ class PopupReport implements PopupReportInterface ->withBudgetInformation() ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate']) - ->setBudget($budget); + ->setBudget($budget) + ; return $collector->getExtractedJournals(); } @@ -71,14 +72,15 @@ class PopupReport implements PopupReportInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->withAccountInformation() ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate']) - ->withoutBudget(); + ->withoutBudget() + ; if (null !== $currency) { $collector->setCurrency($currency); @@ -102,13 +104,14 @@ class PopupReport implements PopupReportInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($attributes['accounts']) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setRange($attributes['startDate'], $attributes['endDate']); + ->setRange($attributes['startDate'], $attributes['endDate']) + ; if (null !== $currency) { $collector->setCurrency($currency); @@ -126,7 +129,7 @@ class PopupReport implements PopupReportInterface /** * Collect journals by a category. */ - public function byCategory(null|Category $category, array $attributes): array + public function byCategory(?Category $category, array $attributes): array { // filter by currency, if set. $currencyId = $attributes['currencyId'] ?? null; @@ -138,7 +141,7 @@ class PopupReport implements PopupReportInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($attributes['accounts']) @@ -147,7 +150,8 @@ class PopupReport implements PopupReportInterface ->withBudgetInformation() ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate']) - ->withAccountInformation(); + ->withAccountInformation() + ; if ($category instanceof Category) { $collector->setCategory($category); @@ -169,8 +173,8 @@ class PopupReport implements PopupReportInterface public function byExpenses(Account $account, array $attributes): array { // filter by currency, if set. - $currencyId = $attributes['currencyId'] ?? null; - $currency = null; + $currencyId = $attributes['currencyId'] ?? null; + $currency = null; if (null !== $currencyId) { /** @var CurrencyRepositoryInterface $repos */ $repos = app(CurrencyRepositoryInterface::class); @@ -178,17 +182,17 @@ class PopupReport implements PopupReportInterface } /** @var JournalRepositoryInterface $repository */ - $repository = app(JournalRepositoryInterface::class); + $repository = app(JournalRepositoryInterface::class); $repository->setUser($account->user); $accountRepository = app(AccountRepositoryInterface::class); $accountRepository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); // the source account must be in the set. - $set = $attributes['accounts'] ?? new Collection(); + $set = $attributes['accounts'] ?? new Collection(); $collector ->setDestinationAccounts(new Collection()->push($account)) @@ -197,7 +201,8 @@ class PopupReport implements PopupReportInterface ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]); + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) + ; if (null !== $currency) { $collector->setCurrency($currency); @@ -216,7 +221,7 @@ class PopupReport implements PopupReportInterface $repository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setSourceAccounts(new Collection()->push($account)) ->setDestinationAccounts($attributes['accounts']) @@ -225,7 +230,8 @@ class PopupReport implements PopupReportInterface ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } diff --git a/app/Helpers/Report/PopupReportInterface.php b/app/Helpers/Report/PopupReportInterface.php index dcaac9375e..3a03cdb049 100644 --- a/app/Helpers/Report/PopupReportInterface.php +++ b/app/Helpers/Report/PopupReportInterface.php @@ -50,7 +50,7 @@ interface PopupReportInterface /** * Group by category. */ - public function byCategory(null|Category $category, array $attributes): array; + public function byCategory(?Category $category, array $attributes): array; /** * Do something with expense. Sorry, I am not very inspirational here. diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 3655736cbe..7a97047adc 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -60,10 +60,10 @@ class ReportHelper implements ReportHelperInterface /** @var Bill $bill */ foreach ($bills as $bill) { - $expectedDates = $repository->getPayDatesInRange($bill, $start, $end); - $billId = $bill->id; - $currency = $bill->transactionCurrency; - $current = [ + $expectedDates = $repository->getPayDatesInRange($bill, $start, $end); + $billId = $bill->id; + $currency = $bill->transactionCurrency; + $current = [ 'id' => $bill->id, 'name' => $bill->name, 'active' => $bill->active, @@ -75,16 +75,16 @@ class ReportHelper implements ReportHelperInterface 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, 'expected_dates' => $expectedDates->toArray(), - 'paid_moments' => [] + 'paid_moments' => [], ]; /** @var Carbon $expectedStart */ foreach ($expectedDates as $expectedStart) { - $expectedEnd = Navigation::endOfX($expectedStart, $bill->repeat_freq, null); + $expectedEnd = Navigation::endOfX($expectedStart, $bill->repeat_freq, null); // is paid in this period maybe? /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($expectedStart, $expectedEnd)->setBill($bill); $current['paid_moments'][] = $collector->getExtractedJournals(); } @@ -105,33 +105,33 @@ class ReportHelper implements ReportHelperInterface $fiscalHelper = app(FiscalHelperInterface::class); $start = clone $date; $start->startOfMonth(); - $end = today(config('app.timezone')); + $end = today(config('app.timezone')); $end->endOfMonth(); - $months = []; + $months = []; while ($start <= $end) { - $year = $fiscalHelper->endOfFiscalYear($start)->year; // current year + $year = $fiscalHelper->endOfFiscalYear($start)->year; // current year if (!array_key_exists($year, $months)) { $months[$year] = [ 'fiscal_start' => $fiscalHelper->startOfFiscalYear($start)->format('Y-m-d'), 'fiscal_end' => $fiscalHelper->endOfFiscalYear($start)->format('Y-m-d'), 'start' => Carbon::createFromDate($year, 1, 1)->format('Y-m-d'), 'end' => Carbon::createFromDate($year, 12, 31)->format('Y-m-d'), - 'months' => [] + 'months' => [], ]; } - $currentEnd = clone $start; + $currentEnd = clone $start; $currentEnd->endOfMonth(); $months[$year]['months'][] = [ 'formatted' => $start->isoFormat((string) trans('config.month_js')), 'start' => $start->format('Y-m-d'), 'end' => $currentEnd->format('Y-m-d'), 'month' => $start->month, - 'year' => $year + 'year' => $year, ]; - $start = clone $currentEnd; // to make the hop to the next month properly + $start = clone $currentEnd; // to make the hop to the next month properly $start->addDay(); } diff --git a/app/Helpers/Webhook/Sha3SignatureGenerator.php b/app/Helpers/Webhook/Sha3SignatureGenerator.php index 26ba341ddd..66eb434876 100644 --- a/app/Helpers/Webhook/Sha3SignatureGenerator.php +++ b/app/Helpers/Webhook/Sha3SignatureGenerator.php @@ -48,7 +48,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface if (null === $message->webhook) { throw new FireflyException('Part of a deleted webhook.'); } - $json = ''; + $json = ''; try { $json = json_encode($message->message, JSON_THROW_ON_ERROR); diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php index 42e96b08fd..6b47c8ec9f 100644 --- a/app/Http/Controllers/Account/CreateController.php +++ b/app/Http/Controllers/Account/CreateController.php @@ -62,7 +62,7 @@ class CreateController extends Controller app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); return $next($request); @@ -85,12 +85,12 @@ class CreateController extends Controller 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), - 'has_location' => $hasOldInput && 'true' === old('location_has_location') + 'has_location' => $hasOldInput && 'true' === old('location_has_location'), ]]; $liabilityDirections = ['debit' => trans('firefly.liability_direction_debit'), 'credit' => trans('firefly.liability_direction_credit')]; // interest calculation periods: - $interestPeriods = []; + $interestPeriods = []; foreach (config('firefly.interest_periods') as $period) { $interestPeriods[$period] = trans(sprintf('firefly.interest_calc_%s', $period)); } @@ -98,10 +98,10 @@ class CreateController extends Controller // pre fill some data $request->session()->flash('preFilled', [ 'currency_id' => $this->primaryCurrency->id, - 'include_net_worth' => !$hasOldInput || (bool) $request->old('include_net_worth') + 'include_net_worth' => !$hasOldInput || (bool) $request->old('include_net_worth'), ]); // issue #8321 - $showNetWorth = true; + $showNetWorth = true; if ('liabilities' !== $objectType && 'asset' !== $objectType) { $showNetWorth = false; } @@ -122,7 +122,7 @@ class CreateController extends Controller 'interestPeriods' => $interestPeriods, 'subTitle' => $subTitle, 'roles' => $roles, - 'liabilityTypes' => $liabilityTypes + 'liabilityTypes' => $liabilityTypes, ]); } @@ -136,8 +136,8 @@ class CreateController extends Controller */ public function store(AccountFormRequest $request) { - $data = $request->getAccountData(); - $account = $this->repository->store($data); + $data = $request->getAccountData(); + $account = $this->repository->store($data); $request->session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name])); Preferences::mark(); @@ -155,7 +155,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($account, $files); } @@ -169,7 +169,7 @@ class CreateController extends Controller } // redirect to previous URL. - $redirect = redirect($this->getPreviousUrl('accounts.create.url')); + $redirect = redirect($this->getPreviousUrl('accounts.create.url')); if (1 === (int) $request->get('create_another')) { // set value so create routine will not overwrite URL: $request->session()->put('accounts.create.fromStore', true); diff --git a/app/Http/Controllers/Account/EditController.php b/app/Http/Controllers/Account/EditController.php index 38e8add2c3..a2bc58c6b0 100644 --- a/app/Http/Controllers/Account/EditController.php +++ b/app/Http/Controllers/Account/EditController.php @@ -62,7 +62,7 @@ class EditController extends Controller app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); return $next($request); @@ -85,28 +85,28 @@ class EditController extends Controller return $this->redirectAccountToAccount($account); } - $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; - $subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); - $roles = $this->getRoles(); - $liabilityTypes = $this->getLiabilityTypes(); - $location = $repository->getLocation($account); - $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); - $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); - $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); - $canEditCurrency = 0 === $account->piggyBanks()->count(); - $hasLocation = $location instanceof Location; - $locations = ['location' => [ + $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; + $subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); + $roles = $this->getRoles(); + $liabilityTypes = $this->getLiabilityTypes(); + $location = $repository->getLocation($account); + $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); + $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); + $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); + $canEditCurrency = 0 === $account->piggyBanks()->count(); + $hasLocation = $location instanceof Location; + $locations = ['location' => [ 'latitude' => old('location_latitude') ?? $latitude, 'longitude' => old('location_longitude') ?? $longitude, 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, - 'has_location' => $hasLocation || 'true' === old('location_has_location') + 'has_location' => $hasLocation || 'true' === old('location_has_location'), ]]; - $liabilityDirections = ['debit' => trans('firefly.liability_direction_debit'), 'credit' => trans('firefly.liability_direction_credit')]; + $liabilityDirections = ['debit' => trans('firefly.liability_direction_debit'), 'credit' => trans('firefly.liability_direction_credit')]; // interest calculation periods: - $interestPeriods = []; + $interestPeriods = []; foreach (config('firefly.interest_periods') as $period) { $interestPeriods[$period] = trans(sprintf('firefly.interest_calc_%s', $period)); } @@ -121,23 +121,23 @@ class EditController extends Controller if ('0' === $openingBalanceAmount) { $openingBalanceAmount = ''; } - $openingBalanceDate = $repository->getOpeningBalanceDate($account); - $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; + $openingBalanceDate = $repository->getOpeningBalanceDate($account); + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; // include this account in net-worth charts? - $includeNetWorth = $repository->getMetaValue($account, 'include_net_worth'); - $includeNetWorth = null === $includeNetWorth ? true : '1' === $includeNetWorth; + $includeNetWorth = $repository->getMetaValue($account, 'include_net_worth'); + $includeNetWorth = null === $includeNetWorth ? true : '1' === $includeNetWorth; // issue #8321 - $showNetWorth = true; + $showNetWorth = true; if ('liabilities' !== $objectType && 'asset' !== $objectType) { $showNetWorth = false; } // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $virtualBalance = $account->virtual_balance ?? '0'; - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $virtualBalance = $account->virtual_balance ?? '0'; + $preFilled = [ 'account_number' => $repository->getMetaValue($account, 'account_number'), 'account_role' => $repository->getMetaValue($account, 'account_role'), 'cc_type' => $repository->getMetaValue($account, 'cc_type'), @@ -153,7 +153,7 @@ class EditController extends Controller 'interest' => $repository->getMetaValue($account, 'interest'), 'interest_period' => $repository->getMetaValue($account, 'interest_period'), 'notes' => $this->repository->getNoteText($account), - 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active + 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active, ]; if ('' === $openingBalanceAmount) { $preFilled['opening_balance'] = ''; @@ -174,7 +174,7 @@ class EditController extends Controller 'roles' => $roles, 'preFilled' => $preFilled, 'liabilityTypes' => $liabilityTypes, - 'interestPeriods' => $interestPeriods + 'interestPeriods' => $interestPeriods, ]); } @@ -189,14 +189,14 @@ class EditController extends Controller return $this->redirectAccountToAccount($account); } - $data = $request->getAccountData(); + $data = $request->getAccountData(); $this->repository->update($account, $data); Log::channel('audit')->info(sprintf('Updated account #%d.', $account->id), $data); $request->session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name])); // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($account, $files); } diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php index 501241b359..c529d61377 100644 --- a/app/Http/Controllers/Account/IndexController.php +++ b/app/Http/Controllers/Account/IndexController.php @@ -73,44 +73,44 @@ class IndexController extends Controller */ public function inactive(Request $request, string $objectType): Factory|\Illuminate\Contracts\View\View { - $inactivePage = true; - $subTitle = (string) trans(sprintf('firefly.%s_accounts_inactive', $objectType)); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); - $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); - $collection = $this->repository->getInactiveAccountsByType($types); - $total = $collection->count(); - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $accounts = $collection->slice(($page - 1) * $pageSize, $pageSize); + $inactivePage = true; + $subTitle = (string) trans(sprintf('firefly.%s_accounts_inactive', $objectType)); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); + $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); + $collection = $this->repository->getInactiveAccountsByType($types); + $total = $collection->count(); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $accounts = $collection->slice(($page - 1) * $pageSize, $pageSize); unset($collection); /** @var Carbon $start */ - $start = clone session('start', today(config('app.timezone'))->startOfMonth()); + $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); Log::debug(sprintf('inactive start: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary); - $activities = Steam::getLastActivities($ids); + $activities = Steam::getLastActivities($ids); $accounts->each(function (Account $account) use ($activities, $startBalances, $endBalances): void { - $currency = $this->repository->getAccountCurrency($account); - $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->differences = $this->subtract($account->startBalances, $account->endBalances); - $account->interest = Steam::bcround($this->repository->getMetaValue($account, 'interest'), 4); - $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); + $currency = $this->repository->getAccountCurrency($account); + $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->differences = $this->subtract($account->startBalances, $account->endBalances); + $account->interest = Steam::bcround($this->repository->getMetaValue($account, 'interest'), 4); + $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); - $account->current_debt = '0'; - $account->currency = $currency ?? $this->primaryCurrency; - $account->iban = implode(' ', str_split((string) $account->iban, 4)); + $account->current_debt = '0'; + $account->currency = $currency ?? $this->primaryCurrency; + $account->iban = implode(' ', str_split((string) $account->iban, 4)); }); // make paginator: - $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); + $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); $accounts->setPath(route('accounts.inactive.index', [$objectType])); return view('accounts.index', [ @@ -119,7 +119,7 @@ class IndexController extends Controller 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle, 'page' => $page, - 'accounts' => $accounts + 'accounts' => $accounts, ]); } @@ -144,62 +144,62 @@ class IndexController extends Controller public function index(Request $request, string $objectType): Factory|\Illuminate\Contracts\View\View { Log::debug(sprintf('Now at %s', __METHOD__)); - $subTitle = (string) trans(sprintf('firefly.%s_accounts', $objectType)); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); - $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); + $subTitle = (string) trans(sprintf('firefly.%s_accounts', $objectType)); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); + $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); $this->repository->resetAccountOrder(); - $collection = $this->repository->getActiveAccountsByType($types); - $total = $collection->count(); - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $accounts = $collection->slice(($page - 1) * $pageSize, $pageSize); - $inactiveCount = $this->repository->getInactiveAccountsByType($types)->count(); + $collection = $this->repository->getActiveAccountsByType($types); + $total = $collection->count(); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $accounts = $collection->slice(($page - 1) * $pageSize, $pageSize); + $inactiveCount = $this->repository->getInactiveAccountsByType($types)->count(); Log::debug(sprintf('Count of collection: %d, count of accounts: %d', $total, $accounts->count())); unset($collection); /** @var Carbon $start */ - $start = clone session('start', today(config('app.timezone'))->startOfMonth()); + $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $now = now(); + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); Log::debug(sprintf('index: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $now, $this->primaryCurrency, $this->convertToPrimary); - $activities = Steam::getLastActivities($ids); + $activities = Steam::getLastActivities($ids); $accounts->each(function (Account $account) use ($activities, $startBalances, $endBalances): void { - $interest = (string) $this->repository->getMetaValue($account, 'interest'); - $interest = '' === $interest ? '0' : $interest; - $currency = $this->repository->getAccountCurrency($account); + $interest = (string) $this->repository->getMetaValue($account, 'interest'); + $interest = '' === $interest ? '0' : $interest; + $currency = $this->repository->getAccountCurrency($account); - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->differences = $this->subtract($account->startBalances, $account->endBalances); - $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); - $account->interest = Steam::bcround($interest, 4); - $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); - $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); - $account->location = $this->repository->getLocation($account); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->differences = $this->subtract($account->startBalances, $account->endBalances); + $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); + $account->interest = Steam::bcround($interest, 4); + $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); + $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); + $account->location = $this->repository->getLocation($account); $account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction'); - $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; - $account->currency = $currency ?? $this->primaryCurrency; - $account->iban = implode(' ', str_split((string) $account->iban, 4)); + $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; + $account->currency = $currency ?? $this->primaryCurrency; + $account->iban = implode(' ', str_split((string) $account->iban, 4)); }); // make paginator: Log::debug(sprintf('Count of accounts before LAP: %d', $accounts->count())); /** @var LengthAwarePaginator $accounts */ - $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); + $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); $accounts->setPath(route('accounts.index', [$objectType])); Log::debug(sprintf('Count of accounts after LAP (1): %d', $accounts->count())); @@ -211,7 +211,7 @@ class IndexController extends Controller 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle, 'page' => $page, - 'accounts' => $accounts + 'accounts' => $accounts, ]); } } diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php index 762e24c12d..a3ab1c94fd 100644 --- a/app/Http/Controllers/Account/ReconcileController.php +++ b/app/Http/Controllers/Account/ReconcileController.php @@ -64,7 +64,7 @@ class ReconcileController extends Controller $this->middleware(function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-credit-card'); app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class); return $next($request); @@ -80,8 +80,8 @@ class ReconcileController extends Controller * */ public function reconcile( Account $account, - null|Carbon $start = null, - null|Carbon $end = null + ?Carbon $start = null, + ?Carbon $end = null ): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); @@ -91,10 +91,10 @@ class ReconcileController extends Controller return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))])); } - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // no start or end: - $range = Navigation::getViewRange(false); + $range = Navigation::getViewRange(false); // get start and end @@ -103,7 +103,7 @@ class ReconcileController extends Controller $start = clone session('start', Navigation::startOfPeriod(new Carbon(), $range)); /** @var Carbon $end */ - $end = clone session('end', Navigation::endOfPeriod(new Carbon(), $range)); + $end = clone session('end', Navigation::endOfPeriod(new Carbon(), $range)); } if (null === $end) { /** @var Carbon $end */ @@ -127,17 +127,17 @@ class ReconcileController extends Controller // 2025-10-08 replace with accountsBalancesOptimized // no longer need to do subday->endofday on $start, set inclusive = false for the same effect. - $startBalance = Steam::bcround( + $startBalance = Steam::bcround( Steam::accountsBalancesOptimized(new Collection()->push($account), $start, convertToPrimary: null, inclusive: false)[$account->id]['balance'], $currency->decimal_places ); - $endBalance = Steam::bcround( + $endBalance = Steam::bcround( Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]['balance'], $currency->decimal_places ); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); - $subTitle = (string) trans('firefly.reconcile_account', ['account' => $account->name]); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); + $subTitle = (string) trans('firefly.reconcile_account', ['account' => $account->name]); // various links $transactionsUrl = route('accounts.reconcile.transactions', [$account->id, '%start%', '%end%']); @@ -157,7 +157,7 @@ class ReconcileController extends Controller 'endBalance' => $endBalance, 'transactionsUrl' => $transactionsUrl, 'overviewUrl' => $overviewUrl, - 'indexUrl' => $indexUrl + 'indexUrl' => $indexUrl, ]); } @@ -173,7 +173,7 @@ class ReconcileController extends Controller } Log::debug('In ReconcileController::submit()'); - $data = $request->getAll(); + $data = $request->getAll(); /** @var string $journalId */ foreach ($data['journals'] as $journalId) { @@ -228,11 +228,11 @@ class ReconcileController extends Controller } // title: - $description = trans('firefly.reconciliation_transaction_title', [ + $description = trans('firefly.reconciliation_transaction_title', [ 'from' => $start->isoFormat($this->monthAndDayFormat), - 'to' => $end->isoFormat($this->monthAndDayFormat) + 'to' => $end->isoFormat($this->monthAndDayFormat), ]); - $submission = [ + $submission = [ 'user' => auth()->user(), 'user_group' => auth()->user()->userGroup, 'group_title' => null, @@ -249,15 +249,15 @@ class ReconcileController extends Controller 'description' => $description, 'source_id' => $source->id, 'destination_id' => $destination->id, - 'reconciled' => true - ]] + 'reconciled' => true, + ]], ]; /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $factory->setUser($user); try { diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php index 2c746880db..be68e9280c 100644 --- a/app/Http/Controllers/Account/ShowController.php +++ b/app/Http/Controllers/Account/ShowController.php @@ -86,13 +86,13 @@ class ShowController extends Controller public function show( Request $request, Account $account, - null|Carbon $start = null, - null|Carbon $end = null + ?Carbon $start = null, + ?Carbon $end = null ): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { if (0 === $account->id) { throw new NotFoundHttpException(); } - $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); + $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); @@ -126,16 +126,16 @@ class ShowController extends Controller $firstTransaction = $this->repository->oldestJournalDate($account) ?? $start; // go back max 3 years. - $threeYearsAgo = clone $start; + $threeYearsAgo = clone $start; $threeYearsAgo->startOfYear()->subYears(3); if ($firstTransaction->lt($threeYearsAgo)) { $firstTransaction = clone $threeYearsAgo; } Log::debug('Start period overview'); - $timer = Timer::getInstance(); + $timer = Timer::getInstance(); $timer->start('period-overview'); - $periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end); + $periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end); Log::debug('End period overview'); $timer->stop('period-overview'); @@ -148,30 +148,31 @@ class ShowController extends Controller $timer->start('collection'); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setLimit($pageSize) ->setPage($page) ->withAttachmentInformation() ->withAPIInformation() - ->setRange($start, $end); + ->setRange($start, $end) + ; // this search will not include transaction groups where this asset account (or liability) // is just part of ONE of the journals. To force this: $collector->setExpandGroupSearch(true); - $groups = $collector->getPaginatedGroups(); + $groups = $collector->getPaginatedGroups(); Log::debug('End collect transactions'); $timer->stop('collection'); $groups->setPath(route('accounts.show', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')])); - $showAll = false; - $now = now(); + $showAll = false; + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. - $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; + $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; // $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $now), $account, $this->convertToPrimary, $accountCurrency); return view('accounts.show', [ @@ -189,7 +190,7 @@ class ShowController extends Controller 'end' => $end, 'chartUrl' => $chartUrl, 'location' => $location, - 'balances' => $balances + 'balances' => $balances, ]); } @@ -206,15 +207,15 @@ class ShowController extends Controller if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); } - $location = $this->repository->getLocation($account); - $isLiability = $this->repository->isLiability($account); - $attachments = $this->repository->getAttachments($account); - $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); - $end = today(config('app.timezone')); - $today = today(config('app.timezone')); + $location = $this->repository->getLocation($account); + $isLiability = $this->repository->isLiability($account); + $attachments = $this->repository->getAttachments($account); + $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); + $end = today(config('app.timezone')); + $today = today(config('app.timezone')); $this->repository->getAccountCurrency($account); $start = $this->repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth(); - $subTitleIcon = config('firefly.subIconsByIdentifier.' . $account->accountType->type); + $subTitleIcon = config('firefly.subIconsByIdentifier.'.$account->accountType->type); $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; @@ -224,21 +225,21 @@ class ShowController extends Controller $end->endOfDay(); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts(new Collection()->push($account))->setLimit($pageSize)->setPage($page)->withAccountInformation()->withCategoryInformation(); // this search will not include transaction groups where this asset account (or liability) // is just part of ONE of the journals. To force this: $collector->setExpandGroupSearch(true); - $groups = $collector->getPaginatedGroups(); + $groups = $collector->getPaginatedGroups(); $groups->setPath(route('accounts.show.all', [$account->id])); - $chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); - $showAll = true; + $chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $showAll = true; // correct Log::debug(sprintf('showAll: Call accountsBalancesOptimized with date/time "%s"', $end->toIso8601String())); - $now = now(); + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } @@ -246,7 +247,7 @@ class ShowController extends Controller // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balances = Steam::finalAccountBalance($account, $end); // $balances = Steam::filterAccountBalance($balances, $account, $this->convertToPrimary, $accountCurrency); - $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; + $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; return view('accounts.show', [ 'account' => $account, @@ -264,7 +265,7 @@ class ShowController extends Controller 'subTitle' => $subTitle, 'start' => $start, 'end' => $end, - 'balances' => $balances + 'balances' => $balances, ]); } } diff --git a/app/Http/Controllers/Admin/ConfigurationController.php b/app/Http/Controllers/Admin/ConfigurationController.php index fa9e26ab81..1381b4fd87 100644 --- a/app/Http/Controllers/Admin/ConfigurationController.php +++ b/app/Http/Controllers/Admin/ConfigurationController.php @@ -61,16 +61,16 @@ class ConfigurationController extends Controller */ public function index(): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.instance_configuration'); - $subTitleIcon = 'fa-wrench'; + $subTitle = (string) trans('firefly.instance_configuration'); + $subTitleIcon = 'fa-wrench'; Log::channel('audit')->info('User visits admin config index.'); // all available configuration and their default value in case // they don't exist yet. - $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; - $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; - $siteOwner = config('firefly.site_owner'); + $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; + $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; + $siteOwner = config('firefly.site_owner'); $enableExchangeRates = FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $useRunningBalance = FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data; @@ -90,7 +90,7 @@ class ConfigurationController extends Controller 'enableExternalMap' => $enableExternalMap, 'enableExternalRates' => $enableExternalRates, 'allowWebhooks' => $allowWebhooks, - 'validUrlProtocols' => $validUrlProtocols + 'validUrlProtocols' => $validUrlProtocols, ]); } diff --git a/app/Http/Controllers/Admin/LinkController.php b/app/Http/Controllers/Admin/LinkController.php index 18dd62b881..e80c824032 100644 --- a/app/Http/Controllers/Admin/LinkController.php +++ b/app/Http/Controllers/Admin/LinkController.php @@ -98,7 +98,7 @@ class LinkController extends Controller $otherTypes = $this->repository->get(); $count = $this->repository->countJournals($linkType); $moveTo = []; - $moveTo[0] = (string) trans('firefly.do_not_save_connection'); + $moveTo[0] = (string) trans('firefly.do_not_save_connection'); /** @var LinkType $otherType */ foreach ($otherTypes as $otherType) { @@ -191,7 +191,7 @@ class LinkController extends Controller 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkType' => $linkType, - 'links' => $links + 'links' => $links, ]); } @@ -205,7 +205,7 @@ class LinkController extends Controller $data = [ 'name' => $request->convertString('name'), 'inward' => $request->convertString('inward'), - 'outward' => $request->convertString('outward') + 'outward' => $request->convertString('outward'), ]; $linkType = $this->repository->store($data); @@ -237,7 +237,7 @@ class LinkController extends Controller return redirect(route('settings.links.index')); } - $data = ['name' => $request->convertString('name'), 'inward' => $request->convertString('inward'), 'outward' => $request->convertString('outward')]; + $data = ['name' => $request->convertString('name'), 'inward' => $request->convertString('inward'), 'outward' => $request->convertString('outward')]; $this->repository->update($linkType, $data); Log::channel('audit')->info(sprintf('User update link type #%d.', $linkType->id), $data); diff --git a/app/Http/Controllers/Admin/NotificationController.php b/app/Http/Controllers/Admin/NotificationController.php index 0a8e3cd3dd..4f99aeeb61 100644 --- a/app/Http/Controllers/Admin/NotificationController.php +++ b/app/Http/Controllers/Admin/NotificationController.php @@ -39,25 +39,25 @@ class NotificationController extends Controller public function index(): View { Log::channel('audit')->info('User visits notifications index.'); - $title = (string) trans('firefly.system_settings'); - $mainTitleIcon = 'fa-hand-spock-o'; - $subTitle = (string) trans('firefly.title_owner_notifications'); - $subTitleIcon = 'envelope-o'; + $title = (string) trans('firefly.system_settings'); + $mainTitleIcon = 'fa-hand-spock-o'; + $subTitle = (string) trans('firefly.title_owner_notifications'); + $subTitleIcon = 'envelope-o'; // notification settings: - $slackUrl = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; - $pushoverAppToken = FireflyConfig::getEncrypted('pushover_app_token', '')->data; - $pushoverUserToken = FireflyConfig::getEncrypted('pushover_user_token', '')->data; - $ntfyServer = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $ntfyTopic = FireflyConfig::getEncrypted('ntfy_topic', '')->data; - $ntfyAuth = FireflyConfig::get('ntfy_auth', false)->data; - $ntfyUser = FireflyConfig::getEncrypted('ntfy_user', '')->data; - $ntfyPass = FireflyConfig::getEncrypted('ntfy_pass', '')->data; - $channels = config('notifications.channels'); - $forcedAvailability = []; + $slackUrl = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; + $pushoverAppToken = FireflyConfig::getEncrypted('pushover_app_token', '')->data; + $pushoverUserToken = FireflyConfig::getEncrypted('pushover_user_token', '')->data; + $ntfyServer = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; + $ntfyTopic = FireflyConfig::getEncrypted('ntfy_topic', '')->data; + $ntfyAuth = FireflyConfig::get('ntfy_auth', false)->data; + $ntfyUser = FireflyConfig::getEncrypted('ntfy_user', '')->data; + $ntfyPass = FireflyConfig::getEncrypted('ntfy_pass', '')->data; + $channels = config('notifications.channels'); + $forcedAvailability = []; // admin notification settings: - $notifications = []; + $notifications = []; foreach (config('notifications.notifications.owner') as $key => $info) { if (true === $info['enabled']) { $notifications[$key] = FireflyConfig::get(sprintf('notification_%s', $key), true)->data; @@ -68,9 +68,9 @@ class NotificationController extends Controller foreach ($channels as $channel => $info) { $forcedAvailability[$channel] = true; } - $forcedAvailability['ntfy'] = '' !== $ntfyTopic; + $forcedAvailability['ntfy'] = '' !== $ntfyTopic; $forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken; - $forcedAvailability['slack'] = '' !== $slackUrl; + $forcedAvailability['slack'] = '' !== $slackUrl; return view('settings.notifications.index', [ 'title' => $title, @@ -87,13 +87,13 @@ class NotificationController extends Controller 'ntfyTopic' => $ntfyTopic, 'ntfyAuth' => $ntfyAuth, 'ntfyUser' => $ntfyUser, - 'ntfyPass' => $ntfyPass + 'ntfyPass' => $ntfyPass, ]); } public function postIndex(NotificationRequest $request): RedirectResponse { - $all = $request->getAll(); + $all = $request->getAll(); foreach (config('notifications.notifications.owner') as $key => $info) { if (array_key_exists($key, $all)) { diff --git a/app/Http/Controllers/Admin/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php index ed13dec31d..4bdf1b2851 100644 --- a/app/Http/Controllers/Admin/UpdateController.php +++ b/app/Http/Controllers/Admin/UpdateController.php @@ -72,13 +72,13 @@ class UpdateController extends Controller $options = [ -1 => (string) trans('firefly.updates_ask_me_later'), 0 => (string) trans('firefly.updates_do_not_check'), - 1 => (string) trans('firefly.updates_enable_check') + 1 => (string) trans('firefly.updates_enable_check'), ]; - $channelOptions = [ + $channelOptions = [ 'stable' => (string) trans('firefly.update_channel_stable'), 'beta' => (string) trans('firefly.update_channel_beta'), - 'alpha' => (string) trans('firefly.update_channel_alpha') + 'alpha' => (string) trans('firefly.update_channel_alpha'), ]; return view('settings.update.index', [ @@ -87,7 +87,7 @@ class UpdateController extends Controller 'selected' => $selected, 'options' => $options, 'channelSelected' => $channelSelected, - 'channelOptions' => $channelOptions + 'channelOptions' => $channelOptions, ]); } diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index 8f76787414..4cff16fa8c 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -135,15 +135,15 @@ class UserController extends Controller } session()->forget('users.edit.fromUpdate'); - $subTitle = (string) trans('firefly.edit_user', ['email' => $user->email]); - $subTitleIcon = 'fa-user-o'; - $currentUser = auth()->user(); - $isAdmin = $this->repository->hasRole($user, 'owner'); - $codes = [ + $subTitle = (string) trans('firefly.edit_user', ['email' => $user->email]); + $subTitleIcon = 'fa-user-o'; + $currentUser = auth()->user(); + $isAdmin = $this->repository->hasRole($user, 'owner'); + $codes = [ '' => (string) trans('firefly.no_block_code'), 'bounced' => (string) trans('firefly.block_code_bounced'), 'expired' => (string) trans('firefly.block_code_expired'), - 'email_changed' => (string) trans('firefly.block_code_email_changed') + 'email_changed' => (string) trans('firefly.block_code_email_changed'), ]; return view('settings.users.edit', [ @@ -153,7 +153,7 @@ class UserController extends Controller 'subTitleIcon' => $subTitleIcon, 'codes' => $codes, 'currentUser' => $currentUser, - 'isAdmin' => $isAdmin + 'isAdmin' => $isAdmin, ]); } @@ -178,12 +178,12 @@ class UserController extends Controller $allowInvites = true; } - $invitedUsers = $this->repository->getInvitedUsers(); + $invitedUsers = $this->repository->getInvitedUsers(); // add meta stuff. $users->each(function (User $user): void { $user->isAdmin = $this->repository->hasRole($user, 'owner'); - $user->has2FA = null !== $user->mfa_secret; + $user->has2FA = null !== $user->mfa_secret; }); return view('settings.users.index', [ @@ -191,7 +191,7 @@ class UserController extends Controller 'subTitleIcon' => $subTitleIcon, 'users' => $users, 'allowInvites' => $allowInvites, - 'invitedUsers' => $invitedUsers + 'invitedUsers' => $invitedUsers, ]); } @@ -226,7 +226,7 @@ class UserController extends Controller 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'information' => $information, - 'user' => $user + 'user' => $user, ]); } @@ -238,7 +238,7 @@ class UserController extends Controller public function update(UserFormRequest $request, User $user) { Log::debug('Actually here'); - $data = $request->getUserData(); + $data = $request->getUserData(); // var_dump($data); diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php index c8bf40120b..50c63a76ca 100644 --- a/app/Http/Controllers/AttachmentController.php +++ b/app/Http/Controllers/AttachmentController.php @@ -99,21 +99,22 @@ class AttachmentController extends Controller public function download(Attachment $attachment) { if ($this->repository->exists($attachment)) { - $content = $this->repository->getContent($attachment); - $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); + $content = $this->repository->getContent($attachment); + $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); /** @var LaravelResponse $response */ $response = response($content); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename=' . $quoted) + ->header('Content-Disposition', 'attachment; filename='.$quoted) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen($content)); + ->header('Content-Length', (string) strlen($content)) + ; return $response; } @@ -137,7 +138,7 @@ class AttachmentController extends Controller $this->rememberPreviousUrl('attachments.edit.url'); } $request->session()->forget('attachments.edit.fromUpdate'); - $preFilled = ['notes' => $this->repository->getNoteText($attachment)]; + $preFilled = ['notes' => $this->repository->getNoteText($attachment)]; $request->session()->flash('preFilled', $preFilled); return view('attachments.edit', ['attachment' => $attachment, 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); @@ -165,7 +166,7 @@ class AttachmentController extends Controller */ public function update(AttachmentFormRequest $request, Attachment $attachment): RedirectResponse { - $data = $request->getAttachmentData(); + $data = $request->getAttachmentData(); $this->repository->update($attachment, $data); $request->session()->flash('success', (string) trans('firefly.attachment_updated', ['name' => $attachment->filename])); @@ -193,7 +194,7 @@ class AttachmentController extends Controller $content = $this->repository->getContent($attachment); // prevent XSS by adding a new secure header. - $csp = [ + $csp = [ "default-src 'none'", "object-src 'none'", "script-src 'none'", @@ -202,13 +203,13 @@ class AttachmentController extends Controller "font-src 'none'", "connect-src 'none'", "img-src 'self'", - "manifest-src 'none'" + "manifest-src 'none'", ]; return response()->make($content, 200, [ 'Content-Security-Policy' => implode('; ', $csp), 'Content-Type' => $attachment->mime, - 'Content-Disposition' => 'inline; filename="' . $attachment->filename . '"' + 'Content-Disposition' => 'inline; filename="'.$attachment->filename.'"', ]); } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 0c13d3e9df..1b11a93b1e 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -84,7 +84,7 @@ class ForgotPasswordController extends Controller // verify if the user is not a demo user. If so, we give him back an error. /** @var null|User $user */ - $user = User::where('email', $request->get('email'))->first(); + $user = User::where('email', $request->get('email'))->first(); if (null !== $user && $repository->hasRole($user, 'demo')) { return back()->withErrors(['email' => (string) trans('firefly.cannot_reset_demo_user')]); @@ -93,7 +93,7 @@ class ForgotPasswordController extends Controller // We will send the password reset link to this user. Once we have attempted // to send the link, we will examine the response then see the message we // need to show to the user. Finally, we'll send out a proper response. - $result = $this->broker()->sendResetLink($request->only('email')); + $result = $this->broker()->sendResetLink($request->only('email')); if ('passwords.throttled' === $result) { Log::error(sprintf('Cowardly refuse to send a password reset message to user #%d because the reset button has been throttled.', $user->id)); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 1d78148505..9f681b5fac 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -70,7 +70,7 @@ class LoginController extends Controller protected string $redirectTo = RouteServiceProvider::HOME; private UserRepositoryInterface $repository; - private string $username = 'email'; + private string $username = 'email'; /** * Create a new controller instance. @@ -101,7 +101,8 @@ class LoginController extends Controller // TODO here be warning. return redirect(route('login')) ->withErrors([$this->username => trans('auth.failed')]) - ->onlyInput($this->username); + ->onlyInput($this->username) + ; } Log::debug('Login data is present.'); @@ -169,7 +170,7 @@ class LoginController extends Controller */ protected function sendFailedLoginResponse(Request $request): void { - $exception = ValidationException::withMessages([$this->username() => [trans('auth.failed')]]); + $exception = ValidationException::withMessages([$this->username() => [trans('auth.failed')]]); $exception->redirectTo = route('login'); throw $exception; @@ -180,8 +181,8 @@ class LoginController extends Controller */ public function logout(Request $request): Redirector|RedirectResponse|Response { - $authGuard = config('firefly.authentication_guard'); - $logoutUrl = config('firefly.custom_logout_url'); + $authGuard = config('firefly.authentication_guard'); + $logoutUrl = config('firefly.custom_logout_url'); if ('remote_user_guard' === $authGuard && '' !== $logoutUrl) { return redirect($logoutUrl); } @@ -217,9 +218,9 @@ class LoginController extends Controller { Log::channel('audit')->info('Show login form (1.1).'); - $count = DB::table('users')->count(); - $guard = config('auth.defaults.guard'); - $title = (string) trans('firefly.login_page_title'); + $count = DB::table('users')->count(); + $guard = config('auth.defaults.guard'); + $title = (string) trans('firefly.login_page_title'); if (0 === $count && 'web' === $guard) { return redirect(route('register')); @@ -239,15 +240,15 @@ class LoginController extends Controller $allowReset = false; } - $email = $request->old('email'); - $remember = $request->old('remember'); + $email = $request->old('email'); + $remember = $request->old('remember'); - $storeInCookie = config('google2fa.store_in_cookie', false); + $storeInCookie = config('google2fa.store_in_cookie', false); if (false !== $storeInCookie) { $cookieName = config('google2fa.cookie_name', 'google2fa_token'); - Cookie::queue(Cookie::make($cookieName, 'invalid-' . Carbon::now()->getTimestamp())); + Cookie::queue(Cookie::make($cookieName, 'invalid-'.Carbon::now()->getTimestamp())); } - $usernameField = $this->username(); + $usernameField = $this->username(); return view('auth.login', [ 'allowRegistration' => $allowRegistration, @@ -255,7 +256,7 @@ class LoginController extends Controller 'remember' => $remember, 'allowReset' => $allowReset, 'title' => $title, - 'usernameField' => $usernameField + 'usernameField' => $usernameField, ]); } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 949be67c86..0de21cb311 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -95,9 +95,9 @@ class RegisterController extends Controller } $this->validator($request->all())->validate(); - $user = $this->createUser($request->all()); + $user = $this->createUser($request->all()); Log::info(sprintf('Registered new user %s', $user->email)); - $owner = new OwnerNotifiable(); + $owner = new OwnerNotifiable(); event(new NewUserRegistered($owner, $user)); $this->guard()->login($user); @@ -126,8 +126,8 @@ class RegisterController extends Controller } catch (ContainerExceptionInterface|NotFoundExceptionInterface) { $singleUserMode = true; } - $userCount = User::count(); - $guard = config('auth.defaults.guard'); + $userCount = User::count(); + $guard = config('auth.defaults.guard'); if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) { $allowRegistration = false; } @@ -167,7 +167,7 @@ class RegisterController extends Controller return view('errors.error', ['message' => $message]); } - $email = $request->old('email'); + $email = $request->old('email'); return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle, 'inviteCode' => $inviteCode]); } @@ -181,7 +181,7 @@ class RegisterController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function showRegistrationForm(null|Request $request = null): Factory|\Illuminate\Contracts\View\View + public function showRegistrationForm(?Request $request = null): Factory|\Illuminate\Contracts\View\View { $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; $pageTitle = (string) trans('firefly.register_page_title'); @@ -193,7 +193,7 @@ class RegisterController extends Controller return view('errors.error', ['message' => $message]); } - $email = $request?->old('email'); + $email = $request?->old('email'); return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle]); } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 4781c763be..cb412585bf 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -85,7 +85,7 @@ class ResetPasswordController extends Controller return view('errors.error', ['message' => $message]); } - $rules = ['token' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed|min:16|secure_password']; + $rules = ['token' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed|min:16|secure_password']; $this->validate($request, $rules, $this->validationErrorMessages()); @@ -136,7 +136,7 @@ class ResetPasswordController extends Controller 'token' => $token, 'email' => $request->email, 'allowRegistration' => $allowRegistration, - 'pageTitle' => $pageTitle + 'pageTitle' => $pageTitle, ]); } } diff --git a/app/Http/Controllers/Auth/TwoFactorController.php b/app/Http/Controllers/Auth/TwoFactorController.php index ff4e3ee608..f8919f52c6 100644 --- a/app/Http/Controllers/Auth/TwoFactorController.php +++ b/app/Http/Controllers/Auth/TwoFactorController.php @@ -66,8 +66,8 @@ class TwoFactorController extends Controller public function submitMFA(Request $request): Redirector|RedirectResponse { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $mfaCode = (string) $request->get('one_time_password'); + $mfaHistory = Preferences::get('mfa_history', [])->data; + $mfaCode = (string) $request->get('one_time_password'); // is in history? then refuse to use it. if ($this->inMFAHistory($mfaCode, $mfaHistory)) { @@ -82,7 +82,7 @@ class TwoFactorController extends Controller // if not OK, save error. if (!$authenticator->isAuthenticated()) { - $user = auth()->user(); + $user = auth()->user(); $this->addToMFAFailureCounter(); $counter = $this->getMFAFailureCounter(); if (3 === $counter || 10 === $counter) { @@ -182,8 +182,8 @@ class TwoFactorController extends Controller private function addToMFAHistory(string $mfaCode): void { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; + $mfaHistory = Preferences::get('mfa_history', [])->data; + $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; $mfaHistory[] = $entry; Preferences::set('mfa_history', $mfaHistory); @@ -214,7 +214,7 @@ class TwoFactorController extends Controller */ private function removeFromBackupCodes(string $mfaCode): void { - $list = Preferences::get('mfa_recovery', [])->data; + $list = Preferences::get('mfa_recovery', [])->data; if (!is_array($list)) { $list = []; } diff --git a/app/Http/Controllers/Bill/CreateController.php b/app/Http/Controllers/Bill/CreateController.php index ccc59968a7..6bc9b10f08 100644 --- a/app/Http/Controllers/Bill/CreateController.php +++ b/app/Http/Controllers/Bill/CreateController.php @@ -55,7 +55,7 @@ class CreateController extends Controller app('view')->share('title', (string) trans('firefly.bills')); app('view')->share('mainTitleIcon', 'fa-calendar-o'); $this->attachments = app(AttachmentHelperInterface::class); - $this->repository = app(BillRepositoryInterface::class); + $this->repository = app(BillRepositoryInterface::class); return $next($request); }); @@ -66,14 +66,14 @@ class CreateController extends Controller */ public function create(Request $request): Factory|View { - $periods = []; + $periods = []; /** @var array $billPeriods */ $billPeriods = config('firefly.bill_periods'); foreach ($billPeriods as $current) { - $periods[$current] = (string) trans('firefly.repeat_freq_' . $current); + $periods[$current] = (string) trans('firefly.repeat_freq_'.$current); } - $subTitle = (string) trans('firefly.create_new_bill'); + $subTitle = (string) trans('firefly.create_new_bill'); // put previous url in session if not redirect from store (not "create another"). if (true !== session('bills.create.fromStore')) { @@ -89,7 +89,7 @@ class CreateController extends Controller */ public function store(BillStoreRequest $request): RedirectResponse { - $billData = $request->getBillData(); + $billData = $request->getBillData(); $billData['active'] = true; @@ -107,7 +107,7 @@ class CreateController extends Controller Preferences::mark(); /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($bill, $files); } diff --git a/app/Http/Controllers/Bill/EditController.php b/app/Http/Controllers/Bill/EditController.php index 593c3ab3f7..9581b9e568 100644 --- a/app/Http/Controllers/Bill/EditController.php +++ b/app/Http/Controllers/Bill/EditController.php @@ -56,7 +56,7 @@ class EditController extends Controller app('view')->share('title', (string) trans('firefly.bills')); app('view')->share('mainTitleIcon', 'fa-calendar-o'); $this->attachments = app(AttachmentHelperInterface::class); - $this->repository = app(BillRepositoryInterface::class); + $this->repository = app(BillRepositoryInterface::class); return $next($request); }); @@ -67,16 +67,16 @@ class EditController extends Controller */ public function edit(Request $request, Bill $bill): Factory|View { - $periods = []; + $periods = []; /** @var array $billPeriods */ - $billPeriods = config('firefly.bill_periods'); + $billPeriods = config('firefly.bill_periods'); foreach ($billPeriods as $current) { - $periods[$current] = (string) trans('firefly.' . $current); + $periods[$current] = (string) trans('firefly.'.$current); } - $subTitle = (string) trans('firefly.edit_bill', ['name' => $bill->name]); + $subTitle = (string) trans('firefly.edit_bill', ['name' => $bill->name]); // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('bills.edit.fromUpdate')) { @@ -85,18 +85,18 @@ class EditController extends Controller $bill->amount_min = Steam::bcround($bill->amount_min, $bill->transactionCurrency->decimal_places); $bill->amount_max = Steam::bcround($bill->amount_max, $bill->transactionCurrency->decimal_places); - $rules = $this->repository->getRulesForBill($bill); + $rules = $this->repository->getRulesForBill($bill); // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); + $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $preFilled = [ 'bill_end_date' => $bill->end_date, 'extension_date' => $bill->extension_date, 'notes' => $this->repository->getNoteText($bill), 'transaction_currency_id' => $bill->transaction_currency_id, 'active' => $hasOldInput ? (bool) $request->old('active') : $bill->active, - 'object_group' => null !== $bill->objectGroups->first() ? $bill->objectGroups->first()->title : '' + 'object_group' => null !== $bill->objectGroups->first() ? $bill->objectGroups->first()->title : '', ]; $request->session()->flash('preFilled', $preFilled); @@ -119,7 +119,7 @@ class EditController extends Controller Preferences::mark(); /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($bill, $files); } diff --git a/app/Http/Controllers/Bill/IndexController.php b/app/Http/Controllers/Bill/IndexController.php index 20d3027e1a..d642eb482f 100644 --- a/app/Http/Controllers/Bill/IndexController.php +++ b/app/Http/Controllers/Bill/IndexController.php @@ -73,21 +73,21 @@ class IndexController extends Controller $this->cleanupObjectGroups(); $this->repository->correctOrder(); $this->repository->correctTransfers(); - $start = session('start'); - $end = session('end'); - $collection = $this->repository->getBills(); - $total = $collection->count(); + $start = session('start'); + $end = session('end'); + $collection = $this->repository->getBills(); + $total = $collection->count(); - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start->clone()); $enrichment->setEnd($end); - $collection = $enrichment->enrich($collection); + $collection = $enrichment->enrich($collection); $parameters->set('start', $start->clone()); $parameters->set('end', $end); @@ -99,39 +99,39 @@ class IndexController extends Controller $transformer->setParameters($parameters); // loop all bills, convert to array and add rules and stuff. - $rules = $this->repository->getRulesForBills($collection); + $rules = $this->repository->getRulesForBills($collection); // make bill groups: - $bills = [0 => ['object_group_id' => 0, 'object_group_title' => (string) trans('firefly.default_group_title_name'), 'bills' => []]]; // the index is the order, not the ID. + $bills = [0 => ['object_group_id' => 0, 'object_group_title' => (string) trans('firefly.default_group_title_name'), 'bills' => []]]; // the index is the order, not the ID. /** @var Bill $bill */ foreach ($collection as $bill) { - $array = $transformer->transform($bill); - $groupOrder = (int) $array['object_group_order']; + $array = $transformer->transform($bill); + $groupOrder = (int) $array['object_group_order']; // make group array if necessary: $bills[$groupOrder] ??= [ 'object_group_id' => $array['object_group_id'], 'object_group_title' => $array['object_group_title'], - 'bills' => [] + 'bills' => [], ]; - $currency = $bill->transactionCurrency ?? $this->primaryCurrency; - $array['currency_id'] = $currency->id; - $array['currency_name'] = $currency->name; - $array['currency_symbol'] = $currency->symbol; - $array['currency_code'] = $currency->code; + $currency = $bill->transactionCurrency ?? $this->primaryCurrency; + $array['currency_id'] = $currency->id; + $array['currency_name'] = $currency->name; + $array['currency_symbol'] = $currency->symbol; + $array['currency_code'] = $currency->code; $array['currency_decimal_places'] = $currency->decimal_places; - $array['attachments'] = $this->repository->getAttachments($bill); - $array['rules'] = $rules[$bill['id']] ?? []; - $bills[$groupOrder]['bills'][] = $array; + $array['attachments'] = $this->repository->getAttachments($bill); + $array['rules'] = $rules[$bill['id']] ?? []; + $bills[$groupOrder]['bills'][] = $array; } // order by key ksort($bills); // summarise per currency / per group. - $sums = $this->getSums($bills); - $totals = $this->getTotals($sums); - $today = now()->startOfDay(); + $sums = $this->getSums($bills); + $totals = $this->getTotals($sums); + $today = now()->startOfDay(); return view('bills.index', ['bills' => $bills, 'sums' => $sums, 'total' => $total, 'totals' => $totals, 'today' => $today]); } @@ -161,7 +161,7 @@ class IndexController extends Controller } Log::debug(sprintf('Now at subscription #%d.', $bill['id'])); - $currencyId = $bill['currency_id']; + $currencyId = $bill['currency_id']; $sums[$groupOrder][$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_code' => $bill['currency_code'], @@ -171,7 +171,7 @@ class IndexController extends Controller 'avg' => '0', 'total_left_to_pay' => '0', 'period' => $range, - 'per_period' => '0' + 'per_period' => '0', ]; Log::debug(sprintf( 'Start with avg:%s, total_left_to_pay:%s, per_period:%s', @@ -182,8 +182,8 @@ class IndexController extends Controller // only fill in avg when bill is active. if (null !== $bill['next_expected_match']) { - $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); - $avg = bcmul($avg, (string) count($bill['pay_dates'])); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); + $avg = bcmul($avg, (string) count($bill['pay_dates'])); $sums[$groupOrder][$currencyId]['avg'] = bcadd($sums[$groupOrder][$currencyId]['avg'], $avg); Log::debug(sprintf('next expected match is "%s", avg is now %s', $bill['next_expected_match'], $sums[$groupOrder][$currencyId]['avg'])); @@ -192,8 +192,8 @@ class IndexController extends Controller if (count($bill['paid_dates']) < count($bill['pay_dates'])) { $count = count($bill['pay_dates']) - count($bill['paid_dates']); if ($count > 0) { - $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); - $avg = bcmul($avg, (string) $count); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); + $avg = bcmul($avg, (string) $count); $sums[$groupOrder][$currencyId]['total_left_to_pay'] = bcadd($sums[$groupOrder][$currencyId]['total_left_to_pay'], $avg); Log::debug( sprintf( @@ -207,7 +207,7 @@ class IndexController extends Controller } } - $perPeriod = $this->amountPerPeriod($bill, $range); + $perPeriod = $this->amountPerPeriod($bill, $range); Log::debug(sprintf('Add amount %s to per_period', $perPeriod)); // fill in per period regardless: $sums[$groupOrder][$currencyId]['per_period'] = bcadd($sums[$groupOrder][$currencyId]['per_period'], $perPeriod); @@ -219,7 +219,7 @@ class IndexController extends Controller private function amountPerPeriod(array $bill, string $range): string { - $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); Log::debug(sprintf('Amount per period for bill #%d "%s"', $bill['id'], $bill['name'])); Log::debug(sprintf('Average is %s', $avg)); @@ -229,7 +229,7 @@ class IndexController extends Controller Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1))); // per period: - $division = [ + $division = [ '1Y' => '1', '6M' => '2', '3M' => '4', @@ -242,9 +242,9 @@ class IndexController extends Controller 'last7' => '52.16', 'last30' => '12', 'last90' => '4', - 'last365' => '1' + 'last365' => '1', ]; - $perPeriod = bcdiv($yearAmount, $division[$range]); + $perPeriod = bcdiv($yearAmount, $division[$range]); Log::debug(sprintf('Amount per %s is %s (%s / %s)', $range, $perPeriod, $yearAmount, $division[$range])); @@ -275,9 +275,9 @@ class IndexController extends Controller 'currency_decimal_places' => $entry['currency_decimal_places'], 'avg' => '0', 'period' => $entry['period'], - 'per_period' => '0' + 'per_period' => '0', ]; - $totals[$currencyId]['avg'] = bcadd($totals[$currencyId]['avg'], (string) $entry['avg']); + $totals[$currencyId]['avg'] = bcadd($totals[$currencyId]['avg'], (string) $entry['avg']); $totals[$currencyId]['per_period'] = bcadd($totals[$currencyId]['per_period'], (string) $entry['per_period']); } } diff --git a/app/Http/Controllers/Bill/ShowController.php b/app/Http/Controllers/Bill/ShowController.php index 3781b0e7a0..702cf495cb 100644 --- a/app/Http/Controllers/Bill/ShowController.php +++ b/app/Http/Controllers/Bill/ShowController.php @@ -79,13 +79,13 @@ class ShowController extends Controller */ public function rescan(Request $request, Bill $bill): Redirector|RedirectResponse { - $total = 0; + $total = 0; if (false === $bill->active) { $request->session()->flash('warning', (string) trans('firefly.cannot_scan_inactive_bill')); return redirect(route('bills.show', [$bill->id])); } - $set = $this->repository->getRulesForBill($bill); + $set = $this->repository->getRulesForBill($bill); if (0 === $set->count()) { $request->session()->flash('error', (string) trans('firefly.no_rules_for_bill')); @@ -121,60 +121,60 @@ class ShowController extends Controller { $this->repository->correctTransfers(); // add info about rules: - $rules = $this->repository->getRulesForBill($bill); - $subTitle = $bill->name; + $rules = $this->repository->getRulesForBill($bill); + $subTitle = $bill->name; /** @var Carbon $start */ - $start = session('start'); + $start = session('start'); /** @var Carbon $end */ - $end = session('end'); - $year = $start->year; - $page = (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $yearAverage = $this->repository->getYearAverage($bill, $start); - $overallAverage = $this->repository->getOverallAverage($bill); - $manager = new Manager(); + $end = session('end'); + $year = $start->year; + $page = (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $yearAverage = $this->repository->getYearAverage($bill, $start); + $overallAverage = $this->repository->getOverallAverage($bill); + $manager = new Manager(); $manager->setSerializer(new DataArraySerializer()); $manager->parseIncludes(['attachments', 'notes']); // add another period to end, could fix 8163 - $range = Navigation::getViewRange(true); - $end = Navigation::addPeriod($end, $range); + $range = Navigation::getViewRange(true); + $end = Navigation::addPeriod($end, $range); // Make a resource out of the data and - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('start', $start); $parameters->set('end', $end); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); /** @var Bill $bill */ - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ - $transformer = app(BillTransformer::class); + $transformer = app(BillTransformer::class); $transformer->setParameters($parameters); - $resource = new Item($bill, $transformer, 'bill'); - $object = $manager->createData($resource)->toArray(); + $resource = new Item($bill, $transformer, 'bill'); + $object = $manager->createData($resource)->toArray(); $object['data']['currency'] = $bill->transactionCurrency; /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setBill($bill)->setLimit($pageSize)->setPage($page)->withBudgetInformation()->withCategoryInformation()->withAccountInformation(); - $groups = $collector->getPaginatedGroups(); + $groups = $collector->getPaginatedGroups(); $groups->setPath(route('bills.show', [$bill->id])); // transform any attachments as well. - $collection = $this->repository->getAttachments($bill); - $attachments = new Collection(); + $collection = $this->repository->getAttachments($bill); + $attachments = new Collection(); if ($collection->count() > 0) { /** @var AttachmentTransformer $transformer */ @@ -191,7 +191,7 @@ class ShowController extends Controller 'year' => $year, 'object' => $object, 'bill' => $bill, - 'subTitle' => $subTitle + 'subTitle' => $subTitle, ]); } } diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php index fa7c03432e..d3df36ce31 100644 --- a/app/Http/Controllers/Budget/BudgetLimitController.php +++ b/app/Http/Controllers/Budget/BudgetLimitController.php @@ -68,9 +68,9 @@ class BudgetLimitController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); return $next($request); @@ -86,7 +86,7 @@ class BudgetLimitController extends Controller $budgetLimits = $this->blRepository->getBudgetLimits($budget, $start, $end); // remove already budgeted currencies with the same date range - $currencies = $collection->filter(static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end): bool { + $currencies = $collection->filter(static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end): bool { /** @var BudgetLimit $limit */ foreach ($budgetLimits as $limit) { if ($limit->transaction_currency_id === $currency->id && $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { @@ -142,14 +142,14 @@ class BudgetLimitController extends Controller if (!$currency instanceof TransactionCurrency || !$budget instanceof Budget) { throw new FireflyException('No valid currency or budget.'); } - $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); - $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); + $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); + $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); if (!$start instanceof Carbon || !$end instanceof Carbon) { return response()->json(); } - $amount = (string) $request->get('amount'); + $amount = (string) $request->get('amount'); $start->startOfDay(); $end->startOfDay(); @@ -159,7 +159,7 @@ class BudgetLimitController extends Controller Log::debug(sprintf('Start: %s, end: %s', $start->format('Y-m-d'), $end->format('Y-m-d'))); - $limit = $this->blRepository->find($budget, $currency, $start, $end); + $limit = $this->blRepository->find($budget, $currency, $start, $end); // sanity check on amount: if (0 === bccomp($amount, '0')) { @@ -187,23 +187,23 @@ class BudgetLimitController extends Controller 'currency_id' => (int) $request->get('transaction_currency_id'), 'start_date' => $start, 'end_date' => $end, - 'amount' => $amount + 'amount' => $amount, ]); } // parse notes, if any. - $notes = (string) $request->get('notes'); + $notes = (string) $request->get('notes'); $this->blRepository->setNoteText($limit, $notes); if ($request->expectsJson()) { - $array = $limit->toArray(); + $array = $limit->toArray(); // add some extra metadata: - $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); - $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0'; - $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); - $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); - $array['days_left'] = (string) $this->activeDaysLeft($start, $end); + $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); + $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0'; + $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); + $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); + $array['days_left'] = (string) $this->activeDaysLeft($start, $end); // left per day: - $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) + $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd((string) $array['spent'], (string) $array['amount']) : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); @@ -211,7 +211,7 @@ class BudgetLimitController extends Controller $array['left_per_day_formatted'] = Amount::formatAnything($limit->transactionCurrency, $array['left_per_day']); // notes: - $array['notes'] = $this->blRepository->getNoteText($limit); + $array['notes'] = $this->blRepository->getNoteText($limit); return response()->json($array); } @@ -221,7 +221,7 @@ class BudgetLimitController extends Controller public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse|RedirectResponse { - $amount = (string) $request->get('amount'); + $amount = (string) $request->get('amount'); if ('' === $amount) { $amount = '0'; } @@ -233,11 +233,11 @@ class BudgetLimitController extends Controller $budgetId = $budgetLimit->budget_id; $currency = $budgetLimit->transactionCurrency; $this->blRepository->destroyBudgetLimit($budgetLimit); - $array = [ + $array = [ 'budget_id' => $budgetId, 'left_formatted' => Amount::formatAnything($currency, '0'), 'left_per_day_formatted' => Amount::formatAnything($currency, '0'), - 'transaction_currency_id' => $currency->id + 'transaction_currency_id' => $currency->id, ]; return response()->json($array); @@ -246,33 +246,33 @@ class BudgetLimitController extends Controller if (-1 === bccomp($amount, '0')) { $amount = bcmul($amount, '-1'); } - $notes = (string) $request->get('notes'); + $notes = (string) $request->get('notes'); if (strlen($notes) > 32768) { $notes = substr($notes, 0, 32768); } - $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]); + $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]); Preferences::mark(); - $array = $limit->toArray(); + $array = $limit->toArray(); - $spentArr = $this->opsRepository->sumExpenses( + $spentArr = $this->opsRepository->sumExpenses( $limit->start_date, $limit->end_date, null, new Collection()->push($budgetLimit->budget), $budgetLimit->transactionCurrency ); - $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date); - $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0'; - $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); - $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); - $array['days_left'] = (string) $daysLeft; - $array['left_per_day'] = 0 === $daysLeft + $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date); + $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0'; + $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); + $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); + $array['days_left'] = (string) $daysLeft; + $array['left_per_day'] = 0 === $daysLeft ? bcadd((string) $array['spent'], (string) $array['amount']) : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); // left per day formatted. - $array['amount'] = Steam::bcround($limit['amount'], $limit->transactionCurrency->decimal_places); + $array['amount'] = Steam::bcround($limit['amount'], $limit->transactionCurrency->decimal_places); $array['left_per_day_formatted'] = Amount::formatAnything($limit->transactionCurrency, $array['left_per_day']); if ('true' === $request->get('redirect')) { return redirect(route('budgets.index')); diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php index e54e59f807..b8e20e9e6d 100644 --- a/app/Http/Controllers/Budget/CreateController.php +++ b/app/Http/Controllers/Budget/CreateController.php @@ -54,7 +54,7 @@ class CreateController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); return $next($request); @@ -68,14 +68,14 @@ class CreateController extends Controller */ public function create(Request $request): Factory|\Illuminate\Contracts\View\View { - $hasOldInput = null !== $request->old('_token'); + $hasOldInput = null !== $request->old('_token'); // auto budget types $autoBudgetTypes = [ 0 => (string) trans('firefly.auto_budget_none'), AutoBudgetType::AUTO_BUDGET_RESET->value => (string) trans('firefly.auto_budget_reset'), AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => (string) trans('firefly.auto_budget_rollover'), - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted') + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted'), ]; $autoBudgetPeriods = [ 'daily' => (string) trans('firefly.auto_budget_period_daily'), @@ -83,12 +83,12 @@ class CreateController extends Controller 'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'half_year' => (string) trans('firefly.auto_budget_period_half_year'), - 'yearly' => (string) trans('firefly.auto_budget_period_yearly') + 'yearly' => (string) trans('firefly.auto_budget_period_yearly'), ]; - $preFilled = [ + $preFilled = [ 'auto_budget_period' => $hasOldInput ? (bool) $request->old('auto_budget_period') : 'monthly', - 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id + 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, ]; $request->session()->flash('preFilled', $preFilled); @@ -98,7 +98,7 @@ class CreateController extends Controller $this->rememberPreviousUrl('budgets.create.url'); } $request->session()->forget('budgets.create.fromStore'); - $subTitle = (string) trans('firefly.create_new_budget'); + $subTitle = (string) trans('firefly.create_new_budget'); return view('budgets.create', ['subTitle' => $subTitle, 'autoBudgetTypes' => $autoBudgetTypes, 'autoBudgetPeriods' => $autoBudgetPeriods]); } @@ -110,9 +110,9 @@ class CreateController extends Controller */ public function store(BudgetFormStoreRequest $request): RedirectResponse { - $data = $request->getBudgetData(); + $data = $request->getBudgetData(); - $budget = $this->repository->store($data); + $budget = $this->repository->store($data); $this->repository->cleanupBudgets(); $request->session()->flash('success', (string) trans('firefly.stored_new_budget', ['name' => $budget->name])); Preferences::mark(); @@ -121,7 +121,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($budget, $files); } diff --git a/app/Http/Controllers/Budget/EditController.php b/app/Http/Controllers/Budget/EditController.php index 567e132aea..46951e0797 100644 --- a/app/Http/Controllers/Budget/EditController.php +++ b/app/Http/Controllers/Budget/EditController.php @@ -57,7 +57,7 @@ class EditController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); return $next($request); @@ -71,15 +71,15 @@ class EditController extends Controller */ public function edit(Request $request, Budget $budget): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.edit_budget', ['name' => $budget->name]); - $autoBudget = $this->repository->getAutoBudget($budget); + $subTitle = (string) trans('firefly.edit_budget', ['name' => $budget->name]); + $autoBudget = $this->repository->getAutoBudget($budget); // auto budget types $autoBudgetTypes = [ 0 => (string) trans('firefly.auto_budget_none'), AutoBudgetType::AUTO_BUDGET_RESET->value => (string) trans('firefly.auto_budget_reset'), AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => (string) trans('firefly.auto_budget_rollover'), - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted') + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted'), ]; $autoBudgetPeriods = [ 'daily' => (string) trans('firefly.auto_budget_period_daily'), @@ -87,22 +87,22 @@ class EditController extends Controller 'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'half_year' => (string) trans('firefly.auto_budget_period_half_year'), - 'yearly' => (string) trans('firefly.auto_budget_period_yearly') + 'yearly' => (string) trans('firefly.auto_budget_period_yearly'), ]; // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'active' => $hasOldInput ? (bool) $request->old('active') : $budget->active, 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, - 'notes' => $this->repository->getNoteText($budget) + 'notes' => $this->repository->getNoteText($budget), ]; if ($autoBudget instanceof AutoBudget) { - $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; + $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; if (is_array($amount)) { $amount = '0'; } - $amount = (string) $amount; + $amount = (string) $amount; $preFilled['auto_budget_amount'] = Steam::bcround($amount, $autoBudget->transactionCurrency->decimal_places); } @@ -118,7 +118,7 @@ class EditController extends Controller 'subTitle' => $subTitle, 'autoBudgetTypes' => $autoBudgetTypes, 'autoBudgetPeriods' => $autoBudgetPeriods, - 'autoBudget' => $autoBudget + 'autoBudget' => $autoBudget, ]); } @@ -127,7 +127,7 @@ class EditController extends Controller */ public function update(BudgetFormUpdateRequest $request, Budget $budget): RedirectResponse { - $data = $request->getBudgetData(); + $data = $request->getBudgetData(); $this->repository->update($budget, $data); $request->session()->flash('success', (string) trans('firefly.updated_budget', ['name' => $budget->name])); @@ -140,7 +140,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($budget, $files); } diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php index c6884faf81..f6ba24ff40 100644 --- a/app/Http/Controllers/Budget/IndexController.php +++ b/app/Http/Controllers/Budget/IndexController.php @@ -71,11 +71,11 @@ class IndexController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->cleanupBudgets(); return $next($request); @@ -89,14 +89,14 @@ class IndexController extends Controller * * @throws FireflyException * */ - public function index(null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function index(?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View { $this->abRepository->cleanup(); Log::debug(sprintf('Start of IndexController::index("%s", "%s")', $start?->format('Y-m-d'), $end?->format('Y-m-d'))); // collect some basic vars: - $range = Navigation::getViewRange(true); - $isCustomRange = session('is_custom_range', false); + $range = Navigation::getViewRange(true); + $isCustomRange = session('is_custom_range', false); if (false === $isCustomRange) { $start ??= session('start', today(config('app.timezone'))->startOfMonth()); $end ??= Navigation::endOfPeriod($start, $range); @@ -108,23 +108,23 @@ class IndexController extends Controller $end ??= session('end', today(config('app.timezone'))->endOfMonth()); } - $currencies = $this->currencyRepository->get(); - $budgeted = '0'; - $spent = '0'; + $currencies = $this->currencyRepository->get(); + $budgeted = '0'; + $spent = '0'; // new period stuff: - $periodTitle = Navigation::periodShow($start, $range); - $prevLoop = $this->getPreviousPeriods($start, $range); - $nextLoop = $this->getNextPeriods($start, $range); + $periodTitle = Navigation::periodShow($start, $range); + $prevLoop = $this->getPreviousPeriods($start, $range); + $nextLoop = $this->getNextPeriods($start, $range); // get all available budgets: $availableBudgets = $this->getAllAvailableBudgets($start, $end); // get all active budgets: - $budgets = $this->getAllBudgets($start, $end, $currencies, $this->primaryCurrency); + $budgets = $this->getAllBudgets($start, $end, $currencies, $this->primaryCurrency); // echo '
';
         //        var_dump($budgets[0]);exit;
-        $sums = $this->getSums($budgets);
+        $sums             = $this->getSums($budgets);
 
         // get budgeted for default currency:
         if (0 === count($availableBudgets)) {
@@ -135,10 +135,10 @@ class IndexController extends Controller
         }
         // number of days for consistent budgeting.
         $activeDaysPassed = $this->activeDaysPassed($start, $end); // see method description.
-        $activeDaysLeft = $this->activeDaysLeft($start, $end); // see method description.
+        $activeDaysLeft   = $this->activeDaysLeft($start, $end); // see method description.
 
         // get all inactive budgets, and simply list them:
-        $inactive = $this->repository->getInactiveBudgets();
+        $inactive         = $this->repository->getInactiveBudgets();
 
         return view('budgets.index', [
             'availableBudgets' => $availableBudgets,
@@ -154,14 +154,14 @@ class IndexController extends Controller
             'budgets'          => $budgets,
             'start'            => $start,
             'end'              => $end,
-            'sums'             => $sums
+            'sums'             => $sums,
         ]);
     }
 
     private function getAllAvailableBudgets(Carbon $start, Carbon $end): array
     {
         Log::debug(sprintf('Start of getAllAvailableBudgets("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        $converter = new ExchangeRateConverter();
+        $converter        = new ExchangeRateConverter();
         // get all available budgets.
         $ab               = $this->abRepository->get($start, $end);
         $availableBudgets = [];
@@ -169,25 +169,25 @@ class IndexController extends Controller
         // for each, complement with spent amount:
         /** @var AvailableBudget $entry */
         foreach ($ab as $entry) {
-            $array = $entry->toArray();
-            $array['start_date'] = $entry->start_date;
-            $array['end_date'] = $entry->end_date;
+            $array                = $entry->toArray();
+            $array['start_date']  = $entry->start_date;
+            $array['end_date']    = $entry->end_date;
 
             // spent in period:
-            $spentArr = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency);
-            $array['spent'] = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0';
-            $array['pc_spent'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id
+            $spentArr             = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency);
+            $array['spent']       = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0';
+            $array['pc_spent']    = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id
                 ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $array['spent'])
                 : null;
             // budgeted in period:
-            $budgeted = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency);
-            $array['budgeted'] = $budgeted;
+            $budgeted             = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency);
+            $array['budgeted']    = $budgeted;
             $array['pc_budgeted'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id
                 ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $budgeted)
                 : null;
             // this time, because of complex sums, use the currency converter.
 
-            $availableBudgets[] = $array;
+            $availableBudgets[]   = $array;
             unset($spentArr);
         }
 
@@ -205,19 +205,19 @@ class IndexController extends Controller
         /** @var Budget $current */
         foreach ($collection as $current) {
             Log::debug(sprintf('Working on budget #%d ("%s")', $current->id, $current->name));
-            $array = $current->toArray();
-            $array['spent'] = [];
+            $array                = $current->toArray();
+            $array['spent']       = [];
             $array['spent_total'] = [];
-            $array['budgeted'] = [];
+            $array['budgeted']    = [];
             $array['attachments'] = $this->repository->getAttachments($current);
             $array['auto_budget'] = $this->repository->getAutoBudget($current);
-            $budgetLimits = $this->blRepository->getBudgetLimits($current, $start, $end);
+            $budgetLimits         = $this->blRepository->getBudgetLimits($current, $start, $end);
 
             /** @var BudgetLimit $limit */
             foreach ($budgetLimits as $limit) {
                 Log::debug(sprintf('Working on budget limit #%d', $limit->id));
-                $currency = $limit->transactionCurrency ?? $primaryCurrency;
-                $amount   = Steam::bcround($limit->amount, $currency->decimal_places);
+                $currency            = $limit->transactionCurrency ?? $primaryCurrency;
+                $amount              = Steam::bcround($limit->amount, $currency->decimal_places);
                 $array['budgeted'][] = [
                     'id'                      => $limit->id,
                     'amount'                  => $amount,
@@ -229,7 +229,7 @@ class IndexController extends Controller
                     'currency_id'             => $currency->id,
                     'currency_symbol'         => $currency->symbol,
                     'currency_name'           => $currency->name,
-                    'currency_decimal_places' => $currency->decimal_places
+                    'currency_decimal_places' => $currency->decimal_places,
                 ];
                 Log::debug(sprintf('The amount budgeted for budget limit #%d is %s %s', $limit->id, $currency->code, $amount));
             }
@@ -240,13 +240,13 @@ class IndexController extends Controller
             foreach ($currencies as $currency) {
                 $spentArr = $this->opsRepository->sumExpenses($start, $end, null, new Collection()->push($current), $currency);
                 if (array_key_exists($currency->id, $spentArr) && array_key_exists('sum', $spentArr[$currency->id])) {
-                    $array['spent'][$currency->id]['spent'] = $spentArr[$currency->id]['sum'];
-                    $array['spent'][$currency->id]['currency_id'] = $currency->id;
-                    $array['spent'][$currency->id]['currency_symbol'] = $currency->symbol;
+                    $array['spent'][$currency->id]['spent']                   = $spentArr[$currency->id]['sum'];
+                    $array['spent'][$currency->id]['currency_id']             = $currency->id;
+                    $array['spent'][$currency->id]['currency_symbol']         = $currency->symbol;
                     $array['spent'][$currency->id]['currency_decimal_places'] = $currency->decimal_places;
                 }
             }
-            $budgets[] = $array;
+            $budgets[]            = $array;
         }
 
         return $budgets;
@@ -262,33 +262,33 @@ class IndexController extends Controller
 
             /** @var array $spent */
             foreach ($budget['spent'] as $spent) {
-                $currencyId = $spent['currency_id'];
+                $currencyId                           = $spent['currency_id'];
                 $sums['spent'][$currencyId] ??= [
                     'amount'                  => '0',
                     'currency_id'             => $spent['currency_id'],
                     'currency_symbol'         => $spent['currency_symbol'],
-                    'currency_decimal_places' => $spent['currency_decimal_places']
+                    'currency_decimal_places' => $spent['currency_decimal_places'],
                 ];
                 $sums['spent'][$currencyId]['amount'] = bcadd($sums['spent'][$currencyId]['amount'], (string) $spent['spent']);
             }
 
             /** @var array $budgeted */
             foreach ($budget['budgeted'] as $budgeted) {
-                $currencyId = $budgeted['currency_id'];
+                $currencyId                              = $budgeted['currency_id'];
                 $sums['budgeted'][$currencyId] ??= [
                     'amount'                  => '0',
                     'currency_id'             => $budgeted['currency_id'],
                     'currency_symbol'         => $budgeted['currency_symbol'],
-                    'currency_decimal_places' => $budgeted['currency_decimal_places']
+                    'currency_decimal_places' => $budgeted['currency_decimal_places'],
                 ];
                 $sums['budgeted'][$currencyId]['amount'] = bcadd($sums['budgeted'][$currencyId]['amount'], (string) $budgeted['amount']);
 
                 // also calculate how much left from budgeted:
-                $sums['left'][$currencyId] ??= [
+                $sums['left'][$currencyId]     ??= [
                     'amount'                  => '0',
                     'currency_id'             => $budgeted['currency_id'],
                     'currency_symbol'         => $budgeted['currency_symbol'],
-                    'currency_decimal_places' => $budgeted['currency_decimal_places']
+                    'currency_decimal_places' => $budgeted['currency_decimal_places'],
                 ];
             }
         }
@@ -298,8 +298,8 @@ class IndexController extends Controller
          * @var int $currencyId
          */
         foreach (array_keys($sums['budgeted']) as $currencyId) {
-            $spent    = $sums['spent'][$currencyId]['amount'] ?? '0';
-            $budgeted = $sums['budgeted'][$currencyId]['amount'] ?? '0';
+            $spent                               = $sums['spent'][$currencyId]['amount'] ?? '0';
+            $budgeted                            = $sums['budgeted'][$currencyId]['amount'] ?? '0';
             $sums['left'][$currencyId]['amount'] = bcadd($spent, $budgeted);
         }
 
diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php
index 13a65c6c53..bae08b34f3 100644
--- a/app/Http/Controllers/Budget/ShowController.php
+++ b/app/Http/Controllers/Budget/ShowController.php
@@ -65,7 +65,7 @@ class ShowController extends Controller
             app('view')->share('title', (string) trans('firefly.budgets'));
             app('view')->share('mainTitleIcon', 'fa-pie-chart');
             $this->journalRepos = app(JournalRepositoryInterface::class);
-            $this->repository = app(BudgetRepositoryInterface::class);
+            $this->repository   = app(BudgetRepositoryInterface::class);
 
             return $next($request);
         });
@@ -80,16 +80,16 @@ class ShowController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function noBudget(Request $request, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function noBudget(Request $request, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         $start ??= session('start');
         $end   ??= session('end');
 
         /** @var Carbon $start */
         /** @var Carbon $end */
-        $subTitle = trans('firefly.without_budget_between', [
+        $subTitle  = trans('firefly.without_budget_between', [
             'start' => $start->isoFormat($this->monthAndDayFormat),
-            'end'   => $end->isoFormat($this->monthAndDayFormat)
+            'end'   => $end->isoFormat($this->monthAndDayFormat),
         ]);
 
         // get first journal ever to set off the budget period overview.
@@ -108,8 +108,9 @@ class ShowController extends Controller
             ->setPage($page)
             ->withoutBudget()
             ->withAccountInformation()
-            ->withCategoryInformation();
-        $groups = $collector->getPaginatedGroups();
+            ->withCategoryInformation()
+        ;
+        $groups    = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.no-budget'));
 
         return view('budgets.no-budget', ['groups'   => $groups, 'subTitle' => $subTitle, 'periods'  => $periods, 'start'    => $start, 'end'      => $end]);
@@ -125,12 +126,12 @@ class ShowController extends Controller
      */
     public function noBudgetAll(Request $request): Factory|\Illuminate\Contracts\View\View
     {
-        $subTitle = (string) trans('firefly.all_journals_without_budget');
-        $first    = $this->journalRepos->firstNull();
-        $start    = $first instanceof TransactionJournal ? $first->date : new Carbon();
-        $end      = today(config('app.timezone'));
-        $page     = (int) $request->get('page');
-        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
+        $subTitle  = (string) trans('firefly.all_journals_without_budget');
+        $first     = $this->journalRepos->firstNull();
+        $start     = $first instanceof TransactionJournal ? $first->date : new Carbon();
+        $end       = today(config('app.timezone'));
+        $page      = (int) $request->get('page');
+        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
@@ -141,8 +142,9 @@ class ShowController extends Controller
             ->setPage($page)
             ->withoutBudget()
             ->withAccountInformation()
-            ->withCategoryInformation();
-        $groups = $collector->getPaginatedGroups();
+            ->withCategoryInformation()
+        ;
+        $groups    = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.no-budget-all'));
 
         return view('budgets.no-budget', ['groups'   => $groups, 'subTitle' => $subTitle, 'start'    => $start, 'end'      => $end]);
@@ -169,7 +171,7 @@ class ShowController extends Controller
 
         // collector:
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
+        $collector   = app(GroupCollectorInterface::class);
         $collector
             ->setRange($allStart, $allEnd)
             ->setBudget($budget)
@@ -177,11 +179,12 @@ class ShowController extends Controller
             ->setLimit($pageSize)
             ->setPage($page)
             ->withBudgetInformation()
-            ->withCategoryInformation();
-        $groups = $collector->getPaginatedGroups();
+            ->withCategoryInformation()
+        ;
+        $groups      = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.show', [$budget->id]));
 
-        $subTitle = (string) trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
+        $subTitle    = (string) trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
 
         return view('budgets.show', [
             'limits'      => $limits,
@@ -189,7 +192,7 @@ class ShowController extends Controller
             'budget'      => $budget,
             'repetition'  => $repetition,
             'groups'      => $groups,
-            'subTitle'    => $subTitle
+            'subTitle'    => $subTitle,
         ]);
     }
 
@@ -215,7 +218,7 @@ class ShowController extends Controller
             'name'     => $budget->name,
             'start'    => $budgetLimit->start_date->isoFormat($this->monthAndDayFormat),
             'end'      => $budgetLimit->end_date->isoFormat($this->monthAndDayFormat),
-            'currency' => $budgetLimit->transactionCurrency->name
+            'currency' => $budgetLimit->transactionCurrency->name,
         ]);
         if ($this->convertToPrimary) {
             $currencySymbol = $this->primaryCurrency->symbol;
@@ -223,7 +226,7 @@ class ShowController extends Controller
 
         // collector:
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
+        $collector      = app(GroupCollectorInterface::class);
 
         $collector
             ->setRange($budgetLimit->start_date, $budgetLimit->end_date)
@@ -232,15 +235,16 @@ class ShowController extends Controller
             ->setLimit($pageSize)
             ->setPage($page)
             ->withBudgetInformation()
-            ->withCategoryInformation();
-        $groups = $collector->getPaginatedGroups();
+            ->withCategoryInformation()
+        ;
+        $groups         = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.show.limit', [$budget->id, $budgetLimit->id]));
 
         /** @var Carbon $start */
-        $start       = session('first', today(config('app.timezone'))->startOfYear());
-        $end         = today(config('app.timezone'));
-        $attachments = $this->repository->getAttachments($budget);
-        $limits      = $this->getLimits($budget, $start, $end);
+        $start          = session('first', today(config('app.timezone'))->startOfYear());
+        $end            = today(config('app.timezone'));
+        $attachments    = $this->repository->getAttachments($budget);
+        $limits         = $this->getLimits($budget, $start, $end);
 
         return view('budgets.show', [
             'limits'         => $limits,
@@ -249,7 +253,7 @@ class ShowController extends Controller
             'budgetLimit'    => $budgetLimit,
             'groups'         => $groups,
             'subTitle'       => $subTitle,
-            'currencySymbol' => $currencySymbol
+            'currencySymbol' => $currencySymbol,
         ]);
     }
 }
diff --git a/app/Http/Controllers/Category/CreateController.php b/app/Http/Controllers/Category/CreateController.php
index adbfcba7c8..9621e69202 100644
--- a/app/Http/Controllers/Category/CreateController.php
+++ b/app/Http/Controllers/Category/CreateController.php
@@ -55,7 +55,7 @@ class CreateController extends Controller
         $this->middleware(function ($request, $next) {
             app('view')->share('title', (string) trans('firefly.categories'));
             app('view')->share('mainTitleIcon', 'fa-bookmark');
-            $this->repository = app(CategoryRepositoryInterface::class);
+            $this->repository  = app(CategoryRepositoryInterface::class);
             $this->attachments = app(AttachmentHelperInterface::class);
 
             return $next($request);
@@ -95,7 +95,7 @@ class CreateController extends Controller
 
         // store attachment(s):
         /** @var null|array $files */
-        $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
+        $files    = $request->hasFile('attachments') ? $request->file('attachments') : null;
         if (null !== $files && !auth()->user()->hasRole('demo')) {
             $this->attachments->saveAttachmentsForModel($category, $files);
         }
diff --git a/app/Http/Controllers/Category/EditController.php b/app/Http/Controllers/Category/EditController.php
index 4d8aefc958..37715b788f 100644
--- a/app/Http/Controllers/Category/EditController.php
+++ b/app/Http/Controllers/Category/EditController.php
@@ -55,7 +55,7 @@ class EditController extends Controller
         $this->middleware(function ($request, $next) {
             app('view')->share('title', (string) trans('firefly.categories'));
             app('view')->share('mainTitleIcon', 'fa-bookmark');
-            $this->repository = app(CategoryRepositoryInterface::class);
+            $this->repository  = app(CategoryRepositoryInterface::class);
             $this->attachments = app(AttachmentHelperInterface::class);
 
             return $next($request);
@@ -69,7 +69,7 @@ class EditController extends Controller
      */
     public function edit(Request $request, Category $category): Factory|\Illuminate\Contracts\View\View
     {
-        $subTitle = (string) trans('firefly.edit_category', ['name' => $category->name]);
+        $subTitle  = (string) trans('firefly.edit_category', ['name' => $category->name]);
 
         // put previous url in session if not redirect from store (not "return_to_edit").
         if (true !== session('categories.edit.fromUpdate')) {
@@ -87,7 +87,7 @@ class EditController extends Controller
      */
     public function update(CategoryFormRequest $request, Category $category): Redirector|RedirectResponse
     {
-        $data = $request->getCategoryData();
+        $data     = $request->getCategoryData();
         $this->repository->update($category, $data);
 
         $request->session()->flash('success', (string) trans('firefly.updated_category', ['name' => $category->name]));
@@ -95,7 +95,7 @@ class EditController extends Controller
 
         // store new attachment(s):
         /** @var null|array $files */
-        $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
+        $files    = $request->hasFile('attachments') ? $request->file('attachments') : null;
         if (null !== $files && !auth()->user()->hasRole('demo')) {
             $this->attachments->saveAttachmentsForModel($category, $files);
         }
diff --git a/app/Http/Controllers/Category/NoCategoryController.php b/app/Http/Controllers/Category/NoCategoryController.php
index 6e26658377..db9b36a2a6 100644
--- a/app/Http/Controllers/Category/NoCategoryController.php
+++ b/app/Http/Controllers/Category/NoCategoryController.php
@@ -76,7 +76,7 @@ class NoCategoryController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function show(Request $request, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function show(Request $request, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         Log::debug('Start of noCategory()');
         $start ??= session('start');
@@ -84,14 +84,14 @@ class NoCategoryController extends Controller
 
         /** @var Carbon $start */
         /** @var Carbon $end */
-        $page     = (int) $request->get('page');
-        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
-        $subTitle = trans('firefly.without_category_between', [
+        $page      = (int) $request->get('page');
+        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
+        $subTitle  = trans('firefly.without_category_between', [
             'start' => $start->isoFormat($this->monthAndDayFormat),
-            'end'   => $end->isoFormat($this->monthAndDayFormat)
+            'end'   => $end->isoFormat($this->monthAndDayFormat),
         ]);
-        $first    = $this->journalRepos->firstNull()->date ?? clone $start;
-        $periods  = $this->getNoModelPeriodOverview('category', $first, $end);
+        $first     = $this->journalRepos->firstNull()->date ?? clone $start;
+        $periods   = $this->getNoModelPeriodOverview('category', $first, $end);
 
         Log::debug(sprintf('Start for noCategory() is %s', $start->format('Y-m-d')));
         Log::debug(sprintf('End for noCategory() is %s', $end->format('Y-m-d')));
@@ -105,8 +105,9 @@ class NoCategoryController extends Controller
             ->withoutCategory()
             ->withAccountInformation()
             ->withBudgetInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]);
-        $groups = $collector->getPaginatedGroups();
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
+        ;
+        $groups    = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category', [$start->format('Y-m-d'), $end->format('Y-m-d')]));
 
         return view('categories.no-category', [
@@ -114,7 +115,7 @@ class NoCategoryController extends Controller
             'subTitle' => $subTitle,
             'periods'  => $periods,
             'start'    => $start,
-            'end'      => $end
+            'end'      => $end,
         ]);
     }
 
@@ -129,16 +130,16 @@ class NoCategoryController extends Controller
     public function showAll(Request $request): Factory|\Illuminate\Contracts\View\View
     {
         // default values:
-        $start    = null;
-        $end      = null;
-        $periods  = new Collection();
-        $page     = (int) $request->get('page');
-        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
+        $start     = null;
+        $end       = null;
+        $periods   = new Collection();
+        $page      = (int) $request->get('page');
+        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
         Log::debug('Start of noCategory()');
-        $subTitle = (string) trans('firefly.all_journals_without_category');
-        $first    = $this->journalRepos->firstNull();
-        $start    = $first instanceof TransactionJournal ? $first->date : new Carbon();
-        $end      = today(config('app.timezone'));
+        $subTitle  = (string) trans('firefly.all_journals_without_category');
+        $first     = $this->journalRepos->firstNull();
+        $start     = $first instanceof TransactionJournal ? $first->date : new Carbon();
+        $end       = today(config('app.timezone'));
         Log::debug(sprintf('Start for noCategory() is %s', $start->format('Y-m-d')));
         Log::debug(sprintf('End for noCategory() is %s', $end->format('Y-m-d')));
 
@@ -151,8 +152,9 @@ class NoCategoryController extends Controller
             ->withoutCategory()
             ->withAccountInformation()
             ->withBudgetInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]);
-        $groups = $collector->getPaginatedGroups();
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
+        ;
+        $groups    = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category.all'));
 
         return view('categories.no-category', [
@@ -160,7 +162,7 @@ class NoCategoryController extends Controller
             'subTitle' => $subTitle,
             'periods'  => $periods,
             'start'    => $start,
-            'end'      => $end
+            'end'      => $end,
         ]);
     }
 }
diff --git a/app/Http/Controllers/Category/ShowController.php b/app/Http/Controllers/Category/ShowController.php
index 86665e69a1..765c728d8c 100644
--- a/app/Http/Controllers/Category/ShowController.php
+++ b/app/Http/Controllers/Category/ShowController.php
@@ -75,7 +75,7 @@ class ShowController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function show(Request $request, Category $category, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function show(Request $request, Category $category, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         $start ??= session('start', today(config('app.timezone'))->startOfMonth());
         $end   ??= session('end', today(config('app.timezone'))->endOfMonth());
@@ -92,11 +92,11 @@ class ShowController extends Controller
         $subTitle     = trans('firefly.journals_in_period_for_category', [
             'name'  => $category->name,
             'start' => $start->isoFormat($this->monthAndDayFormat),
-            'end'   => $end->isoFormat($this->monthAndDayFormat)
+            'end'   => $end->isoFormat($this->monthAndDayFormat),
         ]);
 
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
+        $collector    = app(GroupCollectorInterface::class);
         $collector
             ->setRange($start, $end)
             ->setLimit($pageSize)
@@ -104,9 +104,10 @@ class ShowController extends Controller
             ->withAccountInformation()
             ->setCategory($category)
             ->withBudgetInformation()
-            ->withCategoryInformation();
+            ->withCategoryInformation()
+        ;
 
-        $groups = $collector->getPaginatedGroups();
+        $groups       = $collector->getPaginatedGroups();
         $groups->setPath($path);
 
         return view('categories.show', [
@@ -117,7 +118,7 @@ class ShowController extends Controller
             'subTitle'     => $subTitle,
             'subTitleIcon' => $subTitleIcon,
             'start'        => $start,
-            'end'          => $end
+            'end'          => $end,
         ]);
     }
 
@@ -139,17 +140,17 @@ class ShowController extends Controller
         $end          = null;
         $periods      = new Collection();
 
-        $subTitle = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]);
-        $first    = $this->repository->firstUseDate($category);
+        $subTitle     = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]);
+        $first        = $this->repository->firstUseDate($category);
 
         /** @var Carbon $start */
-        $start       = $first ?? today(config('app.timezone'));
-        $end         = today(config('app.timezone'));
-        $path        = route('categories.show.all', [$category->id]);
-        $attachments = $this->repository->getAttachments($category);
+        $start        = $first ?? today(config('app.timezone'));
+        $end          = today(config('app.timezone'));
+        $path         = route('categories.show.all', [$category->id]);
+        $attachments  = $this->repository->getAttachments($category);
 
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
+        $collector    = app(GroupCollectorInterface::class);
         $collector
             ->setRange($start, $end)
             ->setLimit($pageSize)
@@ -157,9 +158,10 @@ class ShowController extends Controller
             ->withAccountInformation()
             ->setCategory($category)
             ->withBudgetInformation()
-            ->withCategoryInformation();
+            ->withCategoryInformation()
+        ;
 
-        $groups = $collector->getPaginatedGroups();
+        $groups       = $collector->getPaginatedGroups();
         $groups->setPath($path);
 
         return view('categories.show', [
@@ -170,7 +172,7 @@ class ShowController extends Controller
             'subTitle'     => $subTitle,
             'subTitleIcon' => $subTitleIcon,
             'start'        => $start,
-            'end'          => $end
+            'end'          => $end,
         ]);
     }
 }
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index 7e642bdf5a..5d829c325b 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -70,8 +70,8 @@ class AccountController extends Controller
         parent::__construct();
 
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
-            $this->accountRepository = app(AccountRepositoryInterface::class);
+            $this->generator          = app(GeneratorInterface::class);
+            $this->accountRepository  = app(AccountRepositoryInterface::class);
             $this->currencyRepository = app(CurrencyRepositoryInterface::class);
 
             return $next($request);
@@ -89,14 +89,14 @@ class AccountController extends Controller
         Log::debug('ExpenseAccounts');
 
         /** @var Carbon $start */
-        $start = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $start                         = clone session('start', today(config('app.timezone'))->startOfMonth());
 
         /** @var Carbon $end */
-        $end = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $end                           = clone session('end', today(config('app.timezone'))->endOfMonth());
         $start->startOfDay();
         $end->endOfDay();
 
-        $cache = new CacheProperties();
+        $cache                         = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -106,13 +106,13 @@ class AccountController extends Controller
         }
 
         // prep some vars:
-        $currencies = [];
-        $chartData  = [];
-        $tempData   = [];
+        $currencies                    = [];
+        $chartData                     = [];
+        $tempData                      = [];
 
         // grab all accounts and names
-        $accounts     = $this->accountRepository->getAccountsByType([AccountTypeEnum::EXPENSE->value]);
-        $accountNames = $this->extractNames($accounts);
+        $accounts                      = $this->accountRepository->getAccountsByType([AccountTypeEnum::EXPENSE->value]);
+        $accountNames                  = $this->extractNames($accounts);
 
         // grab all balances
         Log::debug(sprintf('expenseAccounts: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
@@ -144,35 +144,35 @@ class AccountController extends Controller
                     continue;
                 }
                 // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
-                $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
-                $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
+                $searchCode   = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
+                $searchCode   = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
                 // Log::debug(sprintf('Search code is %s', $searchCode));
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
                 $startBalance = $startBalances[$account->id][$key] ?? '0';
                 //                Log::debug(sprintf('Start balance is %s', $startBalance));
-                $diff = bcsub($endBalance, $startBalance);
+                $diff         = bcsub($endBalance, $startBalance);
                 $currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
                 if (0 !== bccomp($diff, '0')) {
                     // store the values in a temporary array.
                     $tempData[] = [
-                        'name'       => $accountNames[$account->id],
-                        'difference' => $diff,
-                        'diff_float' => (float) $diff, // intentional float
-                        'currency_id' => $currencies[$searchCode]->id
+                        'name'        => $accountNames[$account->id],
+                        'difference'  => $diff,
+                        'diff_float'  => (float) $diff, // intentional float
+                        'currency_id' => $currencies[$searchCode]->id,
                     ];
                 }
             }
         }
         // recreate currencies, but on ID instead of code.
-        $newCurrencies = [];
+        $newCurrencies                 = [];
         foreach ($currencies as $currency) {
             $newCurrencies[$currency->id] = $currency;
         }
-        $currencies = $newCurrencies;
+        $currencies                    = $newCurrencies;
 
         // sort temp array by amount.
-        $amounts = array_column($tempData, 'diff_float');
+        $amounts                       = array_column($tempData, 'diff_float');
         array_multisort($amounts, SORT_DESC, $tempData);
 
         // loop all found currencies and build the data array for the chart.
@@ -181,24 +181,24 @@ class AccountController extends Controller
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
-            $dataSet = [
+            $dataSet                = [
                 'label'           => (string) trans('firefly.spent'),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => $this->expandNames($tempData)
+                'entries'         => $this->expandNames($tempData),
             ];
             $chartData[$currencyId] = $dataSet;
         }
 
         // loop temp data and place data in correct array:
         foreach ($tempData as $entry) {
-            $currencyId = $entry['currency_id'];
-            $name       = $entry['name'];
+            $currencyId                               = $entry['currency_id'];
+            $name                                     = $entry['name'];
             $chartData[$currencyId]['entries'][$name] = (float) $entry['difference'];
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data                          = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -220,7 +220,7 @@ class AccountController extends Controller
      */
     public function expenseBudget(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($this->convertToPrimary);
@@ -236,7 +236,8 @@ class AccountController extends Controller
             ->setAccounts(new Collection()->push($account))
             ->setRange($start, $end)
             ->withBudgetInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
+        ;
         $journals  = $collector->getExtractedJournals();
         $chartData = [];
         $result    = [];
@@ -244,9 +245,9 @@ class AccountController extends Controller
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $budgetId = (int) $journal['budget_id'];
-            $key      = sprintf('%d-%d', $budgetId, $journal['currency_id']);
-            $budgetIds[] = $budgetId;
+            $budgetId              = (int) $journal['budget_id'];
+            $key                   = sprintf('%d-%d', $budgetId, $journal['currency_id']);
+            $budgetIds[]           = $budgetId;
 
             // currency info:
             $currencyId            = (int) $journal['currency_id'];
@@ -270,22 +271,22 @@ class AccountController extends Controller
                     'currency_name'           => $currencyName,
                     'currency_symbol'         => $currencySymbol,
                     'currency_code'           => $currencyCode,
-                    'currency_decimal_places' => $currencyDecimalPlaces
+                    'currency_decimal_places' => $currencyDecimalPlaces,
                 ];
             }
             $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
 
-        $names = $this->getBudgetNames($budgetIds);
+        $names     = $this->getBudgetNames($budgetIds);
 
         foreach ($result as $row) {
-            $budgetId = $row['budget_id'];
-            $name     = $names[$budgetId];
-            $label    = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $budgetId          = $row['budget_id'];
+            $name              = $names[$budgetId];
+            $label             = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
 
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data      = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -307,7 +308,7 @@ class AccountController extends Controller
      */
     public function expenseCategory(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($end);
@@ -323,15 +324,16 @@ class AccountController extends Controller
             ->setAccounts(new Collection()->push($account))
             ->setRange($start, $end)
             ->withCategoryInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
+        ;
         $journals  = $collector->getExtractedJournals();
         $result    = [];
         $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $field = 'amount';
+            $key                   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $field                 = 'amount';
             if (!array_key_exists($key, $result)) {
                 // currency info:
                 $currencyId            = (int) $journal['currency_id'];
@@ -347,27 +349,27 @@ class AccountController extends Controller
                     $currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
                 }
 
-                $result[$key] = [
+                $result[$key]          = [
                     'total'                   => '0',
                     'category_id'             => (int) $journal['category_id'],
                     'currency_name'           => $currencyName,
                     'currency_code'           => $currencyCode,
                     'currency_symbol'         => $currencySymbol,
-                    'currency_decimal_places' => $currencyDecimalPlaces
+                    'currency_decimal_places' => $currencyDecimalPlaces,
                 ];
             }
             $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
-        $names = $this->getCategoryNames(array_keys($result));
+        $names     = $this->getCategoryNames(array_keys($result));
 
         foreach ($result as $row) {
-            $categoryId = $row['category_id'];
-            $name       = $names[$categoryId] ?? '(unknown)';
-            $label      = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $categoryId        = $row['category_id'];
+            $name              = $names[$categoryId] ?? '(unknown)';
+            $label             = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
 
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data      = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -380,9 +382,9 @@ class AccountController extends Controller
      *                                              */
     public function frontpage(AccountRepositoryInterface $repository): JsonResponse
     {
-        $start      = clone session('start', today(config('app.timezone'))->startOfMonth());
-        $end        = clone session('end', today(config('app.timezone'))->endOfMonth());
-        $defaultSet = $repository->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value])->pluck('id')->toArray();
+        $start          = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $end            = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $defaultSet     = $repository->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value])->pluck('id')->toArray();
         // Log::debug('Default set is ', $defaultSet);
         $frontpage      = Preferences::get('frontpageAccounts', $defaultSet);
         $frontpageArray = is_array($frontpage->data) ? $frontpage->data : [];
@@ -391,7 +393,7 @@ class AccountController extends Controller
             Preferences::set('frontpageAccounts', $defaultSet);
             Log::debug('frontpage set is empty!');
         }
-        $accounts = $repository->getAccountsById($frontpageArray);
+        $accounts       = $repository->getAccountsById($frontpageArray);
 
         // move to end of day for $end.
         $end->endOfDay();
@@ -415,7 +417,7 @@ class AccountController extends Controller
      */
     public function incomeCategory(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($this->convertToPrimary);
@@ -433,15 +435,16 @@ class AccountController extends Controller
             ->setAccounts(new Collection()->push($account))
             ->setRange($start, $end)
             ->withCategoryInformation()
-            ->setTypes([TransactionTypeEnum::DEPOSIT->value]);
+            ->setTypes([TransactionTypeEnum::DEPOSIT->value])
+        ;
         $journals  = $collector->getExtractedJournals();
         $result    = [];
         $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $field = 'amount';
+            $key                   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $field                 = 'amount';
             if (!array_key_exists($key, $result)) {
                 // currency info:
                 $currencyId            = (int) $journal['currency_id'];
@@ -457,26 +460,26 @@ class AccountController extends Controller
                     $currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
                 }
 
-                $result[$key] = [
+                $result[$key]          = [
                     'total'                   => '0',
                     'category_id'             => $journal['category_id'],
                     'currency_name'           => $currencyName,
                     'currency_code'           => $currencyCode,
                     'currency_symbol'         => $currencySymbol,
-                    'currency_decimal_places' => $currencyDecimalPlaces
+                    'currency_decimal_places' => $currencyDecimalPlaces,
                 ];
             }
             $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
 
-        $names = $this->getCategoryNames(array_keys($result));
+        $names     = $this->getCategoryNames(array_keys($result));
         foreach ($result as $row) {
-            $categoryId = $row['category_id'];
-            $name       = $names[$categoryId] ?? '(unknown)';
-            $label      = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $categoryId        = $row['category_id'];
+            $name              = $names[$categoryId] ?? '(unknown)';
+            $label             = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data      = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -494,7 +497,7 @@ class AccountController extends Controller
         $end->endOfDay();
         // TODO not sure if these date ranges will work as expected.
         Log::debug(sprintf('Now in period("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        $cache = new CacheProperties();
+        $cache           = new CacheProperties();
         $cache->addProperty('chart.account.period');
         $cache->addProperty($start);
         $cache->addProperty($end);
@@ -505,11 +508,11 @@ class AccountController extends Controller
         }
 
         // collect and filter balances for the entire period.
-        $step = $this->calculateStep($start, $end);
+        $step            = $this->calculateStep($start, $end);
         Log::debug(sprintf('Step is %s', $step));
-        $locale    = Steam::getLocale();
-        $return    = [];
-        $converter = new ExchangeRateConverter();
+        $locale          = Steam::getLocale();
+        $return          = [];
+        $converter       = new ExchangeRateConverter();
 
         // fix for issue https://github.com/firefly-iii/firefly-iii/issues/8041
         // have to make sure this chart is always based on the balance at the END of the period.
@@ -519,8 +522,8 @@ class AccountController extends Controller
         $format          = (string) trans('config.month_and_day_js', [], $locale);
         $accountCurrency = $this->accountRepository->getAccountCurrency($account);
         Log::debug('Get and filter balance for entire range start');
-        $range = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToPrimary);
-        $range = Steam::filterAccountBalances($range, $account, $this->convertToPrimary, $accountCurrency);
+        $range           = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToPrimary);
+        $range           = Steam::filterAccountBalances($range, $account, $this->convertToPrimary, $accountCurrency);
         Log::debug('Get and filter balance for entire range end');
         // temp, get end balance.
         //        Log::debug(sprintf('period: Call finalAccountBalance with date/time "%s"', $end->toIso8601String()));
@@ -531,14 +534,14 @@ class AccountController extends Controller
         $accountCurrency ??= $this->primaryCurrency; // do this AFTER getting the balances.
         Log::debug('Start chart loop.');
 
-        $newRange      = [];
-        $expectedIndex = 0;
+        $newRange        = [];
+        $expectedIndex   = 0;
         Log::debug('Balances exist at:');
         foreach ($range as $key => $value) {
             $newRange[] = ['date' => $key, 'info' => $value];
             Log::debug(sprintf('%d - %s (%s)', count($newRange) - 1, $key, json_encode($value)));
         }
-        $carbon = Carbon::createFromFormat('Y-m-d', $newRange[0]['date'])->endOfDay();
+        $carbon          = Carbon::createFromFormat('Y-m-d', $newRange[0]['date'])->endOfDay();
         Log::debug(sprintf('Start of loop, $carbon is %s', $carbon->format('Y-m-d H:i:s')));
         while ($end->gte($current)) {
             $momentBalance = $previous;
@@ -567,48 +570,48 @@ class AccountController extends Controller
 
             // check, perhaps recalculate the amount in currency X if the
             if ($accountCurrency->id !== $this->primaryCurrency->id && $this->convertToPrimary && array_key_exists($accountCurrency->code, $momentBalance)) {
-                $converted = $converter->convert($accountCurrency, $this->primaryCurrency, $current, $momentBalance[$accountCurrency->code]);
+                $converted                   = $converter->convert($accountCurrency, $this->primaryCurrency, $current, $momentBalance[$accountCurrency->code]);
                 $momentBalance['pc_balance'] = $converted;
             }
 
-            $return   = $this->updateChartKeys($return, $momentBalance);
-            $previous = $momentBalance;
+            $return        = $this->updateChartKeys($return, $momentBalance);
+            $previous      = $momentBalance;
 
             // process each balance thing.
             foreach ($momentBalance as $key => $amount) {
-                $label = $current->isoFormat($format);
+                $label                           = $current->isoFormat($format);
                 $return[$key]['entries'][$label] = $amount;
             }
-            $current = Navigation::addPeriod($current, $step);
+            $current       = Navigation::addPeriod($current, $step);
             // here too, to fix #8041, the data is corrected to the end of the period.
-            $current = Navigation::endOfX($current, $step, null);
+            $current       = Navigation::endOfX($current, $step, null);
         }
         Log::debug('End of chart loop.');
         // second loop (yes) to create nice array with info! Yay!
-        $chartData = [];
+        $chartData       = [];
 
         foreach ($return as $key => $info) {
             if ('balance' !== $key && 'pc_balance' !== $key) {
                 // assume it's a currency:
-                $setCurrency = $this->currencyRepository->findByCode((string) $key);
+                $setCurrency             = $this->currencyRepository->findByCode((string) $key);
                 $info['currency_symbol'] = $setCurrency->symbol;
-                $info['currency_code'] = $setCurrency->code;
-                $info['label'] = sprintf('%s (%s)', $account->name, $setCurrency->symbol);
+                $info['currency_code']   = $setCurrency->code;
+                $info['label']           = sprintf('%s (%s)', $account->name, $setCurrency->symbol);
             }
             if ('balance' === $key) {
                 $info['currency_symbol'] = $accountCurrency->symbol;
-                $info['currency_code'] = $accountCurrency->code;
-                $info['label'] = sprintf('%s (%s)', $account->name, $accountCurrency->symbol);
+                $info['currency_code']   = $accountCurrency->code;
+                $info['label']           = sprintf('%s (%s)', $account->name, $accountCurrency->symbol);
             }
             if ('pc_balance' === $key) {
                 $info['currency_symbol'] = $this->primaryCurrency->symbol;
-                $info['currency_code'] = $this->primaryCurrency->code;
-                $info['label'] = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->primaryCurrency->symbol);
+                $info['currency_code']   = $this->primaryCurrency->code;
+                $info['label']           = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->primaryCurrency->symbol);
             }
             $chartData[] = $info;
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data            = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -643,15 +646,15 @@ class AccountController extends Controller
     public function revenueAccounts(): JsonResponse
     {
         /** @var Carbon $start */
-        $start = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $start                         = clone session('start', today(config('app.timezone'))->startOfMonth());
 
         /** @var Carbon $end */
-        $end = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $end                           = clone session('end', today(config('app.timezone'))->endOfMonth());
 
         $start->startOfDay();
         $end->endOfDay();
 
-        $cache = new CacheProperties();
+        $cache                         = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -661,13 +664,13 @@ class AccountController extends Controller
         }
 
         // prep some vars:
-        $currencies = [];
-        $chartData  = [];
-        $tempData   = [];
+        $currencies                    = [];
+        $chartData                     = [];
+        $tempData                      = [];
 
         // grab all accounts and names
-        $accounts     = $this->accountRepository->getAccountsByType([AccountTypeEnum::REVENUE->value]);
-        $accountNames = $this->extractNames($accounts);
+        $accounts                      = $this->accountRepository->getAccountsByType([AccountTypeEnum::REVENUE->value]);
+        $accountNames                  = $this->extractNames($accounts);
 
         // grab all balances
         Log::debug(sprintf('revAccounts: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
@@ -699,36 +702,36 @@ class AccountController extends Controller
                     continue;
                 }
                 // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
-                $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
-                $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
+                $searchCode   = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
+                $searchCode   = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
                 // Log::debug(sprintf('Search code is %s', $searchCode));
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
                 $startBalance = $startBalances[$account->id][$key] ?? '0';
                 // Log::debug(sprintf('Start balance is %s', $startBalance));
-                $diff = bcsub($endBalance, $startBalance);
+                $diff         = bcsub($endBalance, $startBalance);
                 $currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
                 if (0 !== bccomp($diff, '0')) {
                     // store the values in a temporary array.
                     $tempData[] = [
-                        'name'       => $accountNames[$account->id],
-                        'difference' => $diff,
-                        'diff_float' => (float) $diff, // intentional float
-                        'currency_id' => $currencies[$searchCode]->id
+                        'name'        => $accountNames[$account->id],
+                        'difference'  => $diff,
+                        'diff_float'  => (float) $diff, // intentional float
+                        'currency_id' => $currencies[$searchCode]->id,
                     ];
                 }
             }
         }
 
         // recreate currencies, but on ID instead of code.
-        $newCurrencies = [];
+        $newCurrencies                 = [];
         foreach ($currencies as $currency) {
             $newCurrencies[$currency->id] = $currency;
         }
-        $currencies = $newCurrencies;
+        $currencies                    = $newCurrencies;
 
         // sort temp array by amount.
-        $amounts = array_column($tempData, 'diff_float');
+        $amounts                       = array_column($tempData, 'diff_float');
         array_multisort($amounts, SORT_ASC, $tempData);
 
         // loop all found currencies and build the data array for the chart.
@@ -737,24 +740,24 @@ class AccountController extends Controller
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
-            $dataSet = [
+            $dataSet                = [
                 'label'           => (string) trans('firefly.earned'),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => $this->expandNames($tempData)
+                'entries'         => $this->expandNames($tempData),
             ];
             $chartData[$currencyId] = $dataSet;
         }
 
         // loop temp data and place data in correct array:
         foreach ($tempData as $entry) {
-            $currencyId = $entry['currency_id'];
-            $name       = $entry['name'];
+            $currencyId                               = $entry['currency_id'];
+            $name                                     = $entry['name'];
             $chartData[$currencyId]['entries'][$name] = bcmul($entry['difference'], '-1');
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data                          = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php
index 4874795c94..818b47c030 100644
--- a/app/Http/Controllers/Chart/BillController.php
+++ b/app/Http/Controllers/Chart/BillController.php
@@ -54,9 +54,9 @@ class BillController extends Controller
      */
     public function frontpage(BillRepositoryInterface $repository): JsonResponse
     {
-        $start = session('start', today(config('app.timezone'))->startOfMonth());
-        $end   = session('end', today(config('app.timezone'))->endOfMonth());
-        $cache = new CacheProperties();
+        $start     = session('start', today(config('app.timezone'))->startOfMonth());
+        $end       = session('end', today(config('app.timezone'))->endOfMonth());
+        $cache     = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty('chart.bill.frontpage');
@@ -72,8 +72,8 @@ class BillController extends Controller
          * @var array $info
          */
         foreach ($paid as $info) {
-            $amount = $info['sum'];
-            $label  = (string) trans('firefly.paid_in_currency', ['currency'  => $info['name']]);
+            $amount            = $info['sum'];
+            $label             = (string) trans('firefly.paid_in_currency', ['currency'  => $info['name']]);
             $chartData[$label] = ['amount'          => $amount, 'currency_symbol' => $info['symbol'], 'currency_code'   => $info['code']];
         }
 
@@ -81,12 +81,12 @@ class BillController extends Controller
          * @var array $info
          */
         foreach ($unpaid as $info) {
-            $amount = $info['sum'];
-            $label  = (string) trans('firefly.unpaid_in_currency', ['currency'  => $info['name']]);
+            $amount            = $info['sum'];
+            $label             = (string) trans('firefly.unpaid_in_currency', ['currency'  => $info['name']]);
             $chartData[$label] = ['amount'          => $amount, 'currency_symbol' => $info['symbol'], 'currency_code'   => $info['code']];
         }
 
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data      = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -99,18 +99,18 @@ class BillController extends Controller
      */
     public function single(Bill $bill): JsonResponse
     {
-        $cache = new CacheProperties();
+        $cache      = new CacheProperties();
         $cache->addProperty('chart.bill.single');
         $cache->addProperty($bill->id);
         $cache->addProperty($this->convertToPrimary);
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale = Steam::getLocale();
+        $locale     = Steam::getLocale();
 
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
-        $journals  = $collector->setBill($bill)->getExtractedJournals();
+        $collector  = app(GroupCollectorInterface::class);
+        $journals   = $collector->setBill($bill)->getExtractedJournals();
 
         // sort the other way around:
         usort($journals, static function (array $left, array $right): int {
@@ -123,7 +123,7 @@ class BillController extends Controller
 
             return 0;
         });
-        $currency = $bill->transactionCurrency;
+        $currency   = $bill->transactionCurrency;
         if ($this->convertToPrimary) {
             $currency = $this->primaryCurrency;
         }
@@ -134,22 +134,22 @@ class BillController extends Controller
                 'label'           => (string) trans('firefly.min-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => []
+                'entries'         => [],
             ],
             [
                 'type'            => 'line',
                 'label'           => (string) trans('firefly.max-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => []
+                'entries'         => [],
             ],
             [
                 'type'            => 'bar',
                 'label'           => (string) trans('firefly.journal-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => []
-            ]
+                'entries'         => [],
+            ],
         ];
         $currencyId = $bill->transaction_currency_id;
         $amountMin  = $bill->amount_min;
@@ -159,7 +159,7 @@ class BillController extends Controller
             $amountMax = $bill->native_amount_max;
         }
         foreach ($journals as $journal) {
-            $date = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $date                           = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $chartData[0]['entries'][$date] = $amountMin; // minimum amount of bill
             $chartData[1]['entries'][$date] = $amountMax; // maximum amount of bill
 
@@ -167,7 +167,7 @@ class BillController extends Controller
             if (!array_key_exists($date, $chartData[2]['entries'])) {
                 $chartData[2]['entries'][$date] = '0';
             }
-            $amount = bcmul((string) $journal['amount'], '-1');
+            $amount                         = bcmul((string) $journal['amount'], '-1');
             if ($this->convertToPrimary && $currencyId !== $journal['currency_id']) {
                 $amount = bcmul($journal['pc_amount'] ?? '0', '-1');
             }
@@ -178,7 +178,7 @@ class BillController extends Controller
             $chartData[2]['entries'][$date] = bcadd($chartData[2]['entries'][$date], $amount); // amount of journal
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data       = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php
index 8ef0492d89..56625bf19e 100644
--- a/app/Http/Controllers/Chart/BudgetController.php
+++ b/app/Http/Controllers/Chart/BudgetController.php
@@ -68,11 +68,11 @@ class BudgetController extends Controller
         parent::__construct();
 
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
-            $this->repository = app(BudgetRepositoryInterface::class);
+            $this->generator     = app(GeneratorInterface::class);
+            $this->repository    = app(BudgetRepositoryInterface::class);
             $this->opsRepository = app(OperationsRepositoryInterface::class);
-            $this->blRepository = app(BudgetLimitRepositoryInterface::class);
-            $this->nbRepository = app(NoBudgetRepositoryInterface::class);
+            $this->blRepository  = app(BudgetLimitRepositoryInterface::class);
+            $this->nbRepository  = app(NoBudgetRepositoryInterface::class);
 
             return $next($request);
         });
@@ -84,11 +84,11 @@ class BudgetController extends Controller
     public function budget(Budget $budget): JsonResponse
     {
         /** @var Carbon $start */
-        $start = $this->repository->firstUseDate($budget) ?? session('start', today(config('app.timezone')));
+        $start          = $this->repository->firstUseDate($budget) ?? session('start', today(config('app.timezone')));
 
         /** @var Carbon $end */
-        $end   = session('end', today(config('app.timezone')));
-        $cache = new CacheProperties();
+        $end            = session('end', today(config('app.timezone')));
+        $cache          = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -98,7 +98,7 @@ class BudgetController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $step = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
+        $step           = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
         $collection     = new Collection()->push($budget);
         $chartData      = [];
         $loopStart      = clone $start;
@@ -107,19 +107,19 @@ class BudgetController extends Controller
         $defaultEntries = [];
         while ($end >= $loopStart) {
             /** @var Carbon $loopEnd */
-            $loopEnd = Navigation::endOfPeriod($loopStart, $step);
-            $spent   = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to primary currency.
-            $label = trim(Navigation::periodShow($loopStart, $step));
+            $loopEnd                = Navigation::endOfPeriod($loopStart, $step);
+            $spent                  = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to primary currency.
+            $label                  = trim(Navigation::periodShow($loopStart, $step));
 
             foreach ($spent as $row) {
-                $currencyId = $row['currency_id'];
+                $currencyId                               = $row['currency_id'];
                 $currencies[$currencyId] ??= $row; // don't mind the field 'sum'
                 // also store this day's sum:
                 $currencies[$currencyId]['spent'][$label] = $row['sum'];
             }
             $defaultEntries[$label] = 0;
             // set loop start to the next period:
-            $loopStart = clone $loopEnd;
+            $loopStart              = clone $loopEnd;
             $loopStart->addSecond();
         }
         // loop all currencies:
@@ -129,13 +129,13 @@ class BudgetController extends Controller
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => $defaultEntries
+                'entries'         => $defaultEntries,
             ];
             foreach ($currency['spent'] as $label => $spent) {
                 $chartData[$currencyId]['entries'][$label] = bcmul((string) $spent, '-1');
             }
         }
-        $data = $this->generator->multiSet(array_values($chartData));
+        $data           = $this->generator->multiSet(array_values($chartData));
         $cache->store($data);
 
         return response()->json($data);
@@ -152,9 +152,9 @@ class BudgetController extends Controller
             throw new FireflyException('This budget limit is not part of this budget.');
         }
 
-        $start = clone $budgetLimit->start_date;
-        $end   = clone $budgetLimit->end_date;
-        $cache = new CacheProperties();
+        $start                                  = clone $budgetLimit->start_date;
+        $end                                    = clone $budgetLimit->end_date;
+        $cache                                  = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -165,19 +165,19 @@ class BudgetController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale           = Steam::getLocale();
-        $entries          = [];
-        $amount           = $budgetLimit->amount ?? '0';
-        $budgetCollection = new Collection()->push($budget);
-        $currency         = $budgetLimit->transactionCurrency;
+        $locale                                 = Steam::getLocale();
+        $entries                                = [];
+        $amount                                 = $budgetLimit->amount ?? '0';
+        $budgetCollection                       = new Collection()->push($budget);
+        $currency                               = $budgetLimit->transactionCurrency;
         if ($this->convertToPrimary) {
             $amount   = $budgetLimit->native_amount ?? $amount;
             $currency = $this->primaryCurrency;
         }
 
         while ($start <= $end) {
-            $current  = clone $start;
-            $expenses = $this->opsRepository->sumExpenses(
+            $current          = clone $start;
+            $expenses         = $this->opsRepository->sumExpenses(
                 $current,
                 $current,
                 null,
@@ -185,17 +185,17 @@ class BudgetController extends Controller
                 $budgetLimit->transactionCurrency,
                 $this->convertToPrimary
             );
-            $spent    = $expenses[$currency->id]['sum'] ?? '0';
-            $amount   = bcadd((string) $amount, $spent);
-            $format   = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $spent            = $expenses[$currency->id]['sum'] ?? '0';
+            $amount           = bcadd((string) $amount, $spent);
+            $format           = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $entries[$format] = $amount;
 
             $start->addDay();
         }
-        $data = $this->generator->singleSet((string) trans('firefly.left'), $entries);
+        $data                                   = $this->generator->singleSet((string) trans('firefly.left'), $entries);
         // add currency symbol from budget limit:
         $data['datasets'][0]['currency_symbol'] = $currency->symbol;
-        $data['datasets'][0]['currency_code'] = $currency->code;
+        $data['datasets'][0]['currency_code']   = $currency->code;
         $cache->store($data);
         // var_dump($data);exit;
 
@@ -205,7 +205,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per asset account.
      */
-    public function expenseAsset(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseAsset(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -215,8 +215,8 @@ class BudgetController extends Controller
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty($budgetLimitId);
         $cache->addProperty('chart.budget.expense-asset');
-        $start = session('first', today(config('app.timezone'))->startOfYear());
-        $end   = today();
+        $start         = session('first', today(config('app.timezone'))->startOfYear());
+        $end           = today();
 
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
@@ -231,18 +231,18 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setBudget($budget);
-        $journals  = $collector->getExtractedJournals();
-        $result    = [];
-        $chartData = [];
+        $journals      = $collector->getExtractedJournals();
+        $result        = [];
+        $chartData     = [];
 
         // group by asset account ID:
         foreach ($journals as $journal) {
-            $key    = sprintf('%d-%d', $journal['source_account_id'], $journal['currency_id']);
-            $amount = $journal['amount'];
+            $key                    = sprintf('%d-%d', $journal['source_account_id'], $journal['currency_id']);
+            $amount                 = $journal['amount'];
 
-            $symbol = $journal['currency_symbol'];
-            $code   = $journal['currency_code'];
-            $name   = $journal['currency_name'];
+            $symbol                 = $journal['currency_symbol'];
+            $code                   = $journal['currency_code'];
+            $name                   = $journal['currency_name'];
 
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
             if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id) {
@@ -261,19 +261,19 @@ class BudgetController extends Controller
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names = $this->getAccountNames(array_keys($result));
+        $names         = $this->getAccountNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
-            $parts   = explode('-', $combinedId);
-            $assetId = (int) $parts[0];
-            $title   = sprintf('%s (%s)', $names[$assetId] ?? '(empty)', $info['currency_name']);
+            $parts             = explode('-', $combinedId);
+            $assetId           = (int) $parts[0];
+            $title             = sprintf('%s (%s)', $names[$assetId] ?? '(empty)', $info['currency_name']);
             $chartData[$title] = [
                 'amount'          => $info['amount'],
                 'currency_symbol' => $info['currency_symbol'],
-                'currency_code'   => $info['currency_code']
+                'currency_code'   => $info['currency_code'],
             ];
         }
 
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data          = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -282,7 +282,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per category.
      */
-    public function expenseCategory(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseCategory(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -292,8 +292,8 @@ class BudgetController extends Controller
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty($budgetLimitId);
         $cache->addProperty('chart.budget.expense-category');
-        $start = session('first', today(config('app.timezone'))->startOfYear());
-        $end   = today();
+        $start         = session('first', today(config('app.timezone'))->startOfYear());
+        $end           = today();
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
             $end   = $budgetLimit->end_date;
@@ -307,15 +307,15 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setBudget($budget)->withCategoryInformation();
-        $journals  = $collector->getExtractedJournals();
-        $result    = [];
-        $chartData = [];
+        $journals      = $collector->getExtractedJournals();
+        $result        = [];
+        $chartData     = [];
         foreach ($journals as $journal) {
-            $key    = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $symbol = $journal['currency_symbol'];
-            $code   = $journal['currency_code'];
-            $name   = $journal['currency_name'];
-            $amount = $journal['amount'];
+            $key                    = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $symbol                 = $journal['currency_symbol'];
+            $code                   = $journal['currency_code'];
+            $name                   = $journal['currency_name'];
+            $amount                 = $journal['amount'];
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
             if (
                 $this->convertToPrimary
@@ -345,18 +345,18 @@ class BudgetController extends Controller
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names = $this->getCategoryNames(array_keys($result));
+        $names         = $this->getCategoryNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
-            $parts      = explode('-', $combinedId);
-            $categoryId = (int) $parts[0];
-            $title      = sprintf('%s (%s)', $names[$categoryId] ?? '(empty)', $info['currency_name']);
+            $parts             = explode('-', $combinedId);
+            $categoryId        = (int) $parts[0];
+            $title             = sprintf('%s (%s)', $names[$categoryId] ?? '(empty)', $info['currency_name']);
             $chartData[$title] = [
                 'amount'          => $info['amount'],
                 'currency_symbol' => $info['currency_symbol'],
-                'currency_code'   => $info['currency_code']
+                'currency_code'   => $info['currency_code'],
             ];
         }
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data          = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -365,7 +365,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per expense account.
      */
-    public function expenseExpense(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseExpense(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -375,8 +375,8 @@ class BudgetController extends Controller
         $cache->addProperty($budgetLimitId);
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty('chart.budget.expense-expense');
-        $start = session('first', today(config('app.timezone'))->startOfYear());
-        $end   = today();
+        $start         = session('first', today(config('app.timezone'))->startOfYear());
+        $end           = today();
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
             $end   = $budgetLimit->end_date;
@@ -390,17 +390,17 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setBudget($budget)->withAccountInformation();
-        $journals  = $collector->getExtractedJournals();
-        $result    = [];
-        $chartData = [];
+        $journals      = $collector->getExtractedJournals();
+        $result        = [];
+        $chartData     = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key    = sprintf('%d-%d', $journal['destination_account_id'], $journal['currency_id']);
-            $amount = $journal['amount'];
-            $symbol = $journal['currency_symbol'];
-            $code   = $journal['currency_code'];
-            $name   = $journal['currency_name'];
+            $key                    = sprintf('%d-%d', $journal['destination_account_id'], $journal['currency_id']);
+            $amount                 = $journal['amount'];
+            $symbol                 = $journal['currency_symbol'];
+            $code                   = $journal['currency_code'];
+            $name                   = $journal['currency_name'];
 
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
             if (
@@ -431,20 +431,20 @@ class BudgetController extends Controller
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names = $this->getAccountNames(array_keys($result));
+        $names         = $this->getAccountNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
-            $parts      = explode('-', $combinedId);
-            $opposingId = (int) $parts[0];
-            $name       = $names[$opposingId] ?? 'no name';
-            $title      = sprintf('%s (%s)', $name, $info['currency_name']);
+            $parts             = explode('-', $combinedId);
+            $opposingId        = (int) $parts[0];
+            $name              = $names[$opposingId] ?? 'no name';
+            $title             = sprintf('%s (%s)', $name, $info['currency_name']);
             $chartData[$title] = [
                 'amount'          => $info['amount'],
                 'currency_symbol' => $info['currency_symbol'],
-                'currency_code'   => $info['currency_code']
+                'currency_code'   => $info['currency_code'],
             ];
         }
 
-        $data = $this->generator->multiCurrencyPieChart($chartData);
+        $data          = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -455,10 +455,10 @@ class BudgetController extends Controller
      */
     public function frontpage(): JsonResponse
     {
-        $start = session('start', today(config('app.timezone'))->startOfMonth());
-        $end   = session('end', today(config('app.timezone'))->endOfMonth());
+        $start                            = session('start', today(config('app.timezone'))->startOfMonth());
+        $end                              = session('end', today(config('app.timezone'))->endOfMonth());
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache                            = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -467,15 +467,15 @@ class BudgetController extends Controller
             return response()->json($cache->get());
         }
         Log::debug('Regenerate frontpage chart from scratch.');
-        $chartGenerator = app(FrontpageChartGenerator::class);
+        $chartGenerator                   = app(FrontpageChartGenerator::class);
         $chartGenerator->setUser(auth()->user());
         $chartGenerator->setStart($start);
         $chartGenerator->setEnd($end);
         $chartGenerator->convertToPrimary = $this->convertToPrimary;
-        $chartGenerator->default = $this->primaryCurrency;
+        $chartGenerator->default          = $this->primaryCurrency;
 
-        $chartData = $chartGenerator->generate();
-        $data      = $this->generator->multiSet($chartData);
+        $chartData                        = $chartGenerator->generate();
+        $data                             = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -491,7 +491,7 @@ class BudgetController extends Controller
     public function period(Budget $budget, TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache          = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($accounts);
@@ -509,22 +509,22 @@ class BudgetController extends Controller
                 'type'            => 'bar',
                 'entries'         => [],
                 'currency_symbol' => $currency->symbol,
-                'currency_code'   => $currency->code
+                'currency_code'   => $currency->code,
             ],
             [
                 'label'           => (string) trans('firefly.box_budgeted_in_currency', ['currency'           => $currency->name]),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => []
-            ]
+                'entries'         => [],
+            ],
         ];
 
-        $currentStart = clone $start;
+        $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentStart = Navigation::startOfPeriod($currentStart, $preferredRange);
-            $title        = $currentStart->isoFormat($titleFormat);
-            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $currentStart                    = Navigation::startOfPeriod($currentStart, $preferredRange);
+            $title                           = $currentStart->isoFormat($titleFormat);
+            $currentEnd                      = Navigation::endOfPeriod($currentStart, $preferredRange);
 
             // default limit is no limit:
             $chartData[0]['entries'][$title] = 0;
@@ -533,21 +533,21 @@ class BudgetController extends Controller
             $chartData[1]['entries'][$title] = 0;
 
             // get budget limit in this period for this currency.
-            $limit = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd);
+            $limit                           = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd);
             if ($limit instanceof BudgetLimit) {
                 $chartData[1]['entries'][$title] = Steam::bcround($limit->amount, $currency->decimal_places);
             }
 
             // get spent amount in this period for this currency.
-            $sum    = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection()->push($budget), $currency);
-            $amount = Steam::positive($sum[$currency->id]['sum'] ?? '0');
+            $sum                             = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection()->push($budget), $currency);
+            $amount                          = Steam::positive($sum[$currency->id]['sum'] ?? '0');
             $chartData[0]['entries'][$title] = Steam::bcround($amount, $currency->decimal_places);
 
-            $currentStart = clone $currentEnd;
+            $currentStart                    = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data           = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -559,7 +559,7 @@ class BudgetController extends Controller
     public function periodNoBudget(TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache          = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($accounts);
@@ -575,15 +575,15 @@ class BudgetController extends Controller
         $currentStart   = clone $start;
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         while ($currentStart <= $end) {
-            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $title      = $currentStart->isoFormat($titleFormat);
-            $sum        = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency);
-            $amount     = Steam::positive($sum[$currency->id]['sum'] ?? '0');
+            $currentEnd        = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $title             = $currentStart->isoFormat($titleFormat);
+            $sum               = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency);
+            $amount            = Steam::positive($sum[$currency->id]['sum'] ?? '0');
             $chartData[$title] = Steam::bcround($amount, $currency->decimal_places);
-            $currentStart = Navigation::addPeriod($currentStart, $preferredRange, 0);
+            $currentStart      = Navigation::addPeriod($currentStart, $preferredRange, 0);
         }
 
-        $data = $this->generator->singleSet((string) trans('firefly.spent'), $chartData);
+        $data           = $this->generator->singleSet((string) trans('firefly.spent'), $chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BudgetReportController.php b/app/Http/Controllers/Chart/BudgetReportController.php
index 6a4906b90c..0b7f03a42c 100644
--- a/app/Http/Controllers/Chart/BudgetReportController.php
+++ b/app/Http/Controllers/Chart/BudgetReportController.php
@@ -59,7 +59,7 @@ class BudgetReportController extends Controller
     {
         parent::__construct();
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
+            $this->generator     = app(GeneratorInterface::class);
             $this->opsRepository = app(OperationsRepositoryInterface::class);
 
             return $next($request);
@@ -81,16 +81,16 @@ class BudgetReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -106,21 +106,21 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                    $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
 
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -137,20 +137,20 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $title = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']);
+                    $title                    = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
 
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -178,20 +178,20 @@ class BudgetReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['budgets'] as $currentBudget) {
                 foreach ($currentBudget['transaction_journals'] as $journal) {
-                    $key    = $journal['date']->isoFormat($format);
-                    $amount = Steam::positive($journal['amount']);
+                    $key                                   = $journal['date']->isoFormat($format);
+                    $amount                                = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data      = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -203,8 +203,8 @@ class BudgetReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key        = $currentStart->isoFormat($format);
+            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key          = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -225,20 +225,20 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $title = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']);
+                    $title                    = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
 
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index d3b61dad2c..a6024980fa 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -71,7 +71,7 @@ class CategoryController extends Controller
     public function all(Category $category): JsonResponse
     {
         // cache results:
-        $cache = new CacheProperties();
+        $cache                            = new CacheProperties();
         $cache->addProperty('chart.category.all');
         $cache->addProperty($category->id);
         $cache->addProperty($this->convertToPrimary);
@@ -80,18 +80,18 @@ class CategoryController extends Controller
         }
 
         /** @var CategoryRepositoryInterface $repository */
-        $repository = app(CategoryRepositoryInterface::class);
-        $start      = $repository->firstUseDate($category) ?? $this->getDate();
-        $range      = Navigation::getViewRange(false);
-        $start      = Navigation::startOfPeriod($start, $range);
-        $end        = $this->getDate();
+        $repository                       = app(CategoryRepositoryInterface::class);
+        $start                            = $repository->firstUseDate($category) ?? $this->getDate();
+        $range                            = Navigation::getViewRange(false);
+        $start                            = Navigation::startOfPeriod($start, $range);
+        $end                              = $this->getDate();
 
         /** @var WholePeriodChartGenerator $chartGenerator */
-        $chartGenerator = app(WholePeriodChartGenerator::class);
+        $chartGenerator                   = app(WholePeriodChartGenerator::class);
         $chartGenerator->convertToPrimary = $this->convertToPrimary;
 
-        $chartData = $chartGenerator->generate($category, $start, $end);
-        $data      = $this->generator->multiSet($chartData);
+        $chartData                        = $chartGenerator->generate($category, $start, $end);
+        $data                             = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -108,10 +108,10 @@ class CategoryController extends Controller
      */
     public function frontPage(): JsonResponse
     {
-        $start = session('start', today(config('app.timezone'))->startOfMonth());
-        $end   = session('end', today(config('app.timezone'))->endOfMonth());
+        $start              = session('start', today(config('app.timezone'))->startOfMonth());
+        $end                = session('end', today(config('app.timezone'))->endOfMonth());
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache              = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -144,7 +144,7 @@ class CategoryController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $data = $this->reportPeriodChart($accounts, $start, $end, $category);
+        $data  = $this->reportPeriodChart($accounts, $start, $end, $category);
 
         $cache->store($data);
 
@@ -154,7 +154,7 @@ class CategoryController extends Controller
     /**
      * Generate report chart for either with or without category.
      */
-    private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, null|Category $category): array
+    private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, ?Category $category): array
     {
         $income     = [];
         $expenses   = [];
@@ -164,8 +164,8 @@ class CategoryController extends Controller
             $noCatRepository = app(NoCategoryRepositoryInterface::class);
 
             // this gives us all currencies
-            $expenses = $noCatRepository->listExpenses($start, $end, $accounts);
-            $income   = $noCatRepository->listIncome($start, $end, $accounts);
+            $expenses        = $noCatRepository->listExpenses($start, $end, $accounts);
+            $income          = $noCatRepository->listIncome($start, $end, $accounts);
         }
 
         if ($category instanceof Category) {
@@ -173,9 +173,9 @@ class CategoryController extends Controller
             $opsRepository = app(OperationsRepositoryInterface::class);
             $categoryId    = $category->id;
             // this gives us all currencies
-            $collection = new Collection()->push($category);
-            $expenses   = $opsRepository->listExpenses($start, $end, $accounts, $collection);
-            $income     = $opsRepository->listIncome($start, $end, $accounts, $collection);
+            $collection    = new Collection()->push($category);
+            $expenses      = $opsRepository->listExpenses($start, $end, $accounts, $collection);
+            $income        = $opsRepository->listIncome($start, $end, $accounts, $collection);
         }
         $currencies = array_unique(array_merge(array_keys($income), array_keys($expenses)));
         $periods    = Navigation::listOfPeriods($start, $end);
@@ -184,42 +184,42 @@ class CategoryController extends Controller
         // make empty data array:
         // double foreach (bad) to make empty array:
         foreach ($currencies as $currencyId) {
-            $currencyInfo = $expenses[$currencyId] ?? $income[$currencyId];
-            $outKey       = sprintf('%d-out', $currencyId);
-            $inKey        = sprintf('%d-in', $currencyId);
+            $currencyInfo       = $expenses[$currencyId] ?? $income[$currencyId];
+            $outKey             = sprintf('%d-out', $currencyId);
+            $inKey              = sprintf('%d-in', $currencyId);
             $chartData[$outKey] = [
                 'label'           => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
                 'entries'         => [],
                 'type'            => 'bar',
-                'backgroundColor' => 'rgba(219, 68, 55, 0.5)' // red
+                'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
             ];
 
-            $chartData[$inKey] = [
+            $chartData[$inKey]  = [
                 'label'           => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
                 'entries'         => [],
                 'type'            => 'bar',
-                'backgroundColor' => 'rgba(0, 141, 76, 0.5)' // green
+                'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
             ];
             // loop empty periods:
             foreach (array_keys($periods) as $period) {
-                $label = $periods[$period];
+                $label                                 = $periods[$period];
                 $chartData[$outKey]['entries'][$label] = '0';
-                $chartData[$inKey]['entries'][$label] = '0';
+                $chartData[$inKey]['entries'][$label]  = '0';
             }
             // loop income and expenses for this category.:
-            $outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+            $outSet             = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
             foreach ($outSet['transaction_journals'] as $journal) {
-                $amount = Steam::positive($journal['amount']);
-                $date   = $journal['date']->isoFormat($format);
+                $amount                               = Steam::positive($journal['amount']);
+                $date                                 = $journal['date']->isoFormat($format);
                 $chartData[$outKey]['entries'][$date] ??= '0';
 
                 $chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]);
             }
 
-            $inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+            $inSet              = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
             foreach ($inSet['transaction_journals'] as $journal) {
-                $amount = Steam::positive($journal['amount']);
-                $date   = $journal['date']->isoFormat($format);
+                $amount                              = Steam::positive($journal['amount']);
+                $date                                = $journal['date']->isoFormat($format);
                 $chartData[$inKey]['entries'][$date] ??= '0';
                 $chartData[$inKey]['entries'][$date] = bcadd($amount, $chartData[$inKey]['entries'][$date]);
             }
@@ -242,7 +242,7 @@ class CategoryController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $data = $this->reportPeriodChart($accounts, $start, $end, null);
+        $data  = $this->reportPeriodChart($accounts, $start, $end, null);
 
         $cache->store($data);
 
@@ -258,14 +258,14 @@ class CategoryController extends Controller
      */
     public function specificPeriod(Category $category, Carbon $date): JsonResponse
     {
-        $range = Navigation::getViewRange(false);
-        $start = Navigation::startOfPeriod($date, $range);
-        $end   = session()->get('end');
+        $range          = Navigation::getViewRange(false);
+        $start          = Navigation::startOfPeriod($date, $range);
+        $end            = session()->get('end');
         if ($end < $start) {
             [$end, $start] = [$start, $end];
         }
 
-        $cache = new CacheProperties();
+        $cache          = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($category->id);
diff --git a/app/Http/Controllers/Chart/CategoryReportController.php b/app/Http/Controllers/Chart/CategoryReportController.php
index 67900c27b6..49d865794d 100644
--- a/app/Http/Controllers/Chart/CategoryReportController.php
+++ b/app/Http/Controllers/Chart/CategoryReportController.php
@@ -58,7 +58,7 @@ class CategoryReportController extends Controller
     {
         parent::__construct();
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
+            $this->generator     = app(GeneratorInterface::class);
             $this->opsRepository = app(OperationsRepositoryInterface::class);
 
             return $next($request);
@@ -75,20 +75,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName = $journal['budget_name'] ?? trans('firefly.no_budget');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['budget_name'] ?? trans('firefly.no_budget');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -106,16 +106,16 @@ class CategoryReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
                 foreach ($category['transaction_journals'] as $journal) {
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -133,16 +133,16 @@ class CategoryReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
                 foreach ($category['transaction_journals'] as $journal) {
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -157,20 +157,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -185,20 +185,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -223,13 +223,13 @@ class CategoryReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['categories'] as $currentCategory) {
                 foreach ($currentCategory['transaction_journals'] as $journal) {
-                    $key    = $journal['date']->isoFormat($format);
-                    $amount = Steam::positive($journal['amount']);
+                    $key                                   = $journal['date']->isoFormat($format);
+                    $amount                                = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
@@ -250,20 +250,20 @@ class CategoryReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['categories'] as $currentCategory) {
                 foreach ($currentCategory['transaction_journals'] as $journal) {
-                    $key    = $journal['date']->isoFormat($format);
-                    $amount = Steam::positive($journal['amount']);
+                    $key                                   = $journal['date']->isoFormat($format);
+                    $amount                                = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data      = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -278,8 +278,8 @@ class CategoryReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key        = $currentStart->isoFormat($format);
+            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key          = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -298,20 +298,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -326,20 +326,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/DoubleReportController.php b/app/Http/Controllers/Chart/DoubleReportController.php
index fa7bead748..8b002eb9b1 100644
--- a/app/Http/Controllers/Chart/DoubleReportController.php
+++ b/app/Http/Controllers/Chart/DoubleReportController.php
@@ -56,9 +56,9 @@ class DoubleReportController extends Controller
     {
         parent::__construct();
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
+            $this->generator     = app(GeneratorInterface::class);
             $this->opsRepository = app(OperationsRepositoryInterface::class);
-            $this->repository = app(AccountRepositoryInterface::class);
+            $this->repository    = app(AccountRepositoryInterface::class);
 
             return $next($request);
         });
@@ -74,19 +74,19 @@ class DoubleReportController extends Controller
         // loop expenses.
         foreach ($expenses as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName = $journal['budget_name'] ?? trans('firefly.no_budget');
-                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName             = $journal['budget_name'] ?? trans('firefly.no_budget');
+                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
-                $amount = Steam::positive($journal['amount']);
+                $amount                   = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data     = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -101,19 +101,19 @@ class DoubleReportController extends Controller
         // loop expenses.
         foreach ($spent as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
-                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
+                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
-                $amount = Steam::positive($journal['amount']);
+                $amount                   = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data     = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -128,19 +128,19 @@ class DoubleReportController extends Controller
         // loop income.
         foreach ($earned as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
-                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
+                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
-                $amount = Steam::positive($journal['amount']);
+                $amount                   = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data     = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -149,11 +149,11 @@ class DoubleReportController extends Controller
     {
         $chartData = [];
 
-        $opposing = $this->repository->expandWithDoubles(new Collection()->push($account));
-        $accounts = $accounts->merge($opposing);
-        $spent    = $this->opsRepository->listExpenses($start, $end, $accounts);
-        $earned   = $this->opsRepository->listIncome($start, $end, $accounts);
-        $format   = Navigation::preferredCarbonLocalizedFormat($start, $end);
+        $opposing  = $this->repository->expandWithDoubles(new Collection()->push($account));
+        $accounts  = $accounts->merge($opposing);
+        $spent     = $this->opsRepository->listExpenses($start, $end, $accounts);
+        $earned    = $this->opsRepository->listIncome($start, $end, $accounts);
+        $format    = Navigation::preferredCarbonLocalizedFormat($start, $end);
 
         // loop expenses.
         foreach ($spent as $currency) {
@@ -171,12 +171,12 @@ class DoubleReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['transaction_journals'] as $journal) {
-                $key    = $journal['date']->isoFormat($format);
-                $amount = Steam::positive($journal['amount']);
+                $key                                   = $journal['date']->isoFormat($format);
+                $amount                                = Steam::positive($journal['amount']);
                 $chartData[$spentKey]['entries'][$key] ??= '0';
                 $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
             }
@@ -197,18 +197,18 @@ class DoubleReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['transaction_journals'] as $journal) {
-                $key    = $journal['date']->isoFormat($format);
-                $amount = Steam::positive($journal['amount']);
+                $key                                    = $journal['date']->isoFormat($format);
+                $amount                                 = Steam::positive($journal['amount']);
                 $chartData[$earnedKey]['entries'][$key] ??= '0';
                 $chartData[$earnedKey]['entries'][$key] = bcadd($chartData[$earnedKey]['entries'][$key], $amount);
             }
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data      = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -216,7 +216,7 @@ class DoubleReportController extends Controller
     /**
      * TODO duplicate function
      */
-    private function getCounterpartName(Collection $accounts, int $id, string $name, null|string $iban): string
+    private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
     {
         /** @var Account $account */
         foreach ($accounts as $account) {
@@ -241,8 +241,8 @@ class DoubleReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key        = $currentStart->isoFormat($format);
+            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key          = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -265,16 +265,16 @@ class DoubleReportController extends Controller
 
                 // no tags? also deserves a sport
                 if (0 === count($journal['tags'])) {
-                    $includedJournals[] = $journalId;
+                    $includedJournals[]       = $journalId;
                     // do something
-                    $tagName = trans('firefly.no_tags');
-                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName                  = trans('firefly.no_tags');
+                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
 
@@ -284,22 +284,22 @@ class DoubleReportController extends Controller
                     if (in_array($journalId, $includedJournals, true)) {
                         continue;
                     }
-                    $includedJournals[] = $journalId;
+                    $includedJournals[]       = $journalId;
                     // do something
-                    $tagName = $tag['name'];
-                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName                  = $tag['name'];
+                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data             = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -318,16 +318,16 @@ class DoubleReportController extends Controller
 
                 // no tags? also deserves a sport
                 if (0 === count($journal['tags'])) {
-                    $includedJournals[] = $journalId;
+                    $includedJournals[]       = $journalId;
                     // do something
-                    $tagName = trans('firefly.no_tags');
-                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName                  = trans('firefly.no_tags');
+                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
 
@@ -337,22 +337,22 @@ class DoubleReportController extends Controller
                     if (in_array($journalId, $includedJournals, true)) {
                         continue;
                     }
-                    $includedJournals[] = $journalId;
+                    $includedJournals[]       = $journalId;
                     // do something
-                    $tagName = $tag['name'];
-                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName                  = $tag['name'];
+                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data             = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/ExpenseReportController.php b/app/Http/Controllers/Chart/ExpenseReportController.php
index 3091146a03..fb786d56f3 100644
--- a/app/Http/Controllers/Chart/ExpenseReportController.php
+++ b/app/Http/Controllers/Chart/ExpenseReportController.php
@@ -56,7 +56,7 @@ class ExpenseReportController extends Controller
     {
         parent::__construct();
         $this->middleware(function ($request, $next) {
-            $this->generator = app(GeneratorInterface::class);
+            $this->generator         = app(GeneratorInterface::class);
             $this->accountRepository = app(AccountRepositoryInterface::class);
 
             return $next($request);
@@ -72,7 +72,7 @@ class ExpenseReportController extends Controller
      */
     public function mainChart(Collection $accounts, Collection $expense, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache = new CacheProperties();
+        $cache        = new CacheProperties();
         $cache->addProperty('chart.expense.report.main');
         $cache->addProperty($accounts);
         $cache->addProperty($expense);
@@ -100,33 +100,33 @@ class ExpenseReportController extends Controller
         foreach ($combined as $name => $combination) {
             // first is always expense account:
             /** @var Account $exp */
-            $exp = $combination->first();
-            $chartData[$exp->id . '-in'] = [
+            $exp                              = $combination->first();
+            $chartData[$exp->id.'-in']        = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.income')),
                 'type'    => 'bar',
                 'yAxisID' => 'y-axis-0',
-                'entries' => []
+                'entries' => [],
             ];
-            $chartData[$exp->id . '-out'] = [
+            $chartData[$exp->id.'-out']       = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.expenses')),
                 'type'    => 'bar',
                 'yAxisID' => 'y-axis-0',
-                'entries' => []
+                'entries' => [],
             ];
             // total in, total out:
-            $chartData[$exp->id . '-total-in'] = [
+            $chartData[$exp->id.'-total-in']  = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_income')),
                 'type'    => 'line',
                 'fill'    => false,
                 'yAxisID' => 'y-axis-1',
-                'entries' => []
+                'entries' => [],
             ];
-            $chartData[$exp->id . '-total-out'] = [
+            $chartData[$exp->id.'-total-out'] = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_expenses')),
                 'type'    => 'line',
                 'fill'    => false,
                 'yAxisID' => 'y-axis-1',
-                'entries' => []
+                'entries' => [],
             ];
         }
 
@@ -134,35 +134,35 @@ class ExpenseReportController extends Controller
         $sumOfExpense = [];
 
         while ($currentStart < $end) {
-            $currentEnd = clone $currentStart;
-            $currentEnd = $currentEnd->{$function}(); // @phpstan-ignore-line
+            $currentEnd   = clone $currentStart;
+            $currentEnd   = $currentEnd->{$function}(); // @phpstan-ignore-line
 
             // get expenses grouped by opposing name:
-            $expenses = $this->groupByName($this->getExpensesForOpposing($accounts, $all, $currentStart, $currentEnd));
-            $income   = $this->groupByName($this->getIncomeForOpposing($accounts, $all, $currentStart, $currentEnd));
-            $label    = $currentStart->isoFormat($format);
+            $expenses     = $this->groupByName($this->getExpensesForOpposing($accounts, $all, $currentStart, $currentEnd));
+            $income       = $this->groupByName($this->getIncomeForOpposing($accounts, $all, $currentStart, $currentEnd));
+            $label        = $currentStart->isoFormat($format);
 
             foreach ($combined as $name => $combination) {
                 // first is always expense account:
                 /** @var Account $exp */
-                $exp            = $combination->first();
-                $labelIn        = $exp->id . '-in';
-                $labelOut       = $exp->id . '-out';
-                $labelSumIn     = $exp->id . '-total-in';
-                $labelSumOut    = $exp->id . '-total-out';
-                $currentIncome  = bcmul($income[$name] ?? '0', '-1');
-                $currentExpense = $expenses[$name] ?? '0';
+                $exp                                        = $combination->first();
+                $labelIn                                    = $exp->id.'-in';
+                $labelOut                                   = $exp->id.'-out';
+                $labelSumIn                                 = $exp->id.'-total-in';
+                $labelSumOut                                = $exp->id.'-total-out';
+                $currentIncome                              = bcmul($income[$name] ?? '0', '-1');
+                $currentExpense                             = $expenses[$name] ?? '0';
 
                 // add to sum:
-                $sumOfIncome[$exp->id] ??= '0';
+                $sumOfIncome[$exp->id]  ??= '0';
                 $sumOfExpense[$exp->id] ??= '0';
-                $sumOfIncome[$exp->id] = bcadd($sumOfIncome[$exp->id], $currentIncome);
-                $sumOfExpense[$exp->id] = bcadd($sumOfExpense[$exp->id], $currentExpense);
+                $sumOfIncome[$exp->id]                      = bcadd($sumOfIncome[$exp->id], $currentIncome);
+                $sumOfExpense[$exp->id]                     = bcadd($sumOfExpense[$exp->id], $currentExpense);
 
                 // add to chart:
-                $chartData[$labelIn]['entries'][$label] = $currentIncome;
-                $chartData[$labelOut]['entries'][$label] = $currentExpense;
-                $chartData[$labelSumIn]['entries'][$label] = $sumOfIncome[$exp->id];
+                $chartData[$labelIn]['entries'][$label]     = $currentIncome;
+                $chartData[$labelOut]['entries'][$label]    = $currentExpense;
+                $chartData[$labelSumIn]['entries'][$label]  = $sumOfIncome[$exp->id];
                 $chartData[$labelSumOut]['entries'][$label] = $sumOfExpense[$exp->id];
             }
 
@@ -172,7 +172,7 @@ class ExpenseReportController extends Controller
             $currentStart->startOfDay();
         }
         // remove all empty entries to prevent cluttering:
-        $newSet = [];
+        $newSet       = [];
         foreach ($chartData as $key => $entry) {
             // TODO not sure, this is a bad comparison.
             if (array_sum($entry['entries']) > 0) {
@@ -182,7 +182,7 @@ class ExpenseReportController extends Controller
         if (0 === count($newSet)) {
             $newSet = $chartData;
         }
-        $data = $this->generator->multiSet($newSet);
+        $data         = $this->generator->multiSet($newSet);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php
index 053680ada6..b9bb86c2f7 100644
--- a/app/Http/Controllers/Chart/PiggyBankController.php
+++ b/app/Http/Controllers/Chart/PiggyBankController.php
@@ -63,43 +63,43 @@ class PiggyBankController extends Controller
     public function history(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank): JsonResponse
     {
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache                  = new CacheProperties();
         $cache->addProperty('chart.piggy-bank.history');
         $cache->addProperty($piggyBank->id);
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $set    = $repository->getEvents($piggyBank);
-        $set    = $set->reverse();
-        $locale = Steam::getLocale();
+        $set                    = $repository->getEvents($piggyBank);
+        $set                    = $set->reverse();
+        $locale                 = Steam::getLocale();
 
         // get first event or start date of piggy bank or today
-        $startDate = $piggyBank->start_date ?? today(config('app.timezone'));
+        $startDate              = $piggyBank->start_date ?? today(config('app.timezone'));
 
         /** @var null|PiggyBankEvent $firstEvent */
-        $firstEvent = $set->first();
-        $firstDate  = null === $firstEvent ? new Carbon() : $firstEvent->date;
+        $firstEvent             = $set->first();
+        $firstDate              = null === $firstEvent ? new Carbon() : $firstEvent->date;
 
         // which ever is older:
-        $oldest = $startDate->lt($firstDate) ? $startDate : $firstDate;
-        $today  = today(config('app.timezone'));
+        $oldest                 = $startDate->lt($firstDate) ? $startDate : $firstDate;
+        $today                  = today(config('app.timezone'));
         // depending on diff, do something with range of chart.
-        $step = $this->calculateStep($oldest, $today);
+        $step                   = $this->calculateStep($oldest, $today);
 
-        $chartData = [];
+        $chartData              = [];
         while ($oldest <= $today) {
-            $filtered   = $set->filter(static fn(PiggyBankEvent $event) => $event->date->lte($oldest));
-            $currentSum = $filtered->sum('amount');
-            $label      = $oldest->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $filtered          = $set->filter(static fn (PiggyBankEvent $event) => $event->date->lte($oldest));
+            $currentSum        = $filtered->sum('amount');
+            $label             = $oldest->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $chartData[$label] = $currentSum;
-            $oldest = Navigation::addPeriod($oldest, $step);
+            $oldest            = Navigation::addPeriod($oldest, $step);
         }
-        $finalFiltered = $set->filter(static fn(PiggyBankEvent $event) => $event->date->lte($today));
-        $finalSum      = $finalFiltered->sum('amount');
-        $finalLabel    = $today->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+        $finalFiltered          = $set->filter(static fn (PiggyBankEvent $event) => $event->date->lte($today));
+        $finalSum               = $finalFiltered->sum('amount');
+        $finalLabel             = $today->isoFormat((string) trans('config.month_and_day_js', [], $locale));
         $chartData[$finalLabel] = $finalSum;
 
-        $data = $this->generator->singleSet($piggyBank->name, $chartData);
+        $data                   = $this->generator->singleSet($piggyBank->name, $chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php
index a07fe31322..0c0fae8fda 100644
--- a/app/Http/Controllers/Chart/ReportController.php
+++ b/app/Http/Controllers/Chart/ReportController.php
@@ -67,7 +67,7 @@ class ReportController extends Controller
     public function netWorth(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache             = new CacheProperties();
         $cache->addProperty('chart.report.net-worth');
         $cache->addProperty($start);
         $cache->addProperty(implode(',', $accounts->pluck('id')->toArray()));
@@ -75,12 +75,12 @@ class ReportController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale    = Steam::getLocale();
-        $current   = clone $start;
-        $chartData = [];
+        $locale            = Steam::getLocale();
+        $current           = clone $start;
+        $chartData         = [];
 
         /** @var NetWorthInterface $helper */
-        $helper = app(NetWorthInterface::class);
+        $helper            = app(NetWorthInterface::class);
         $helper->setUser(auth()->user());
 
         // filter accounts on having the preference for being included.
@@ -103,7 +103,7 @@ class ReportController extends Controller
             $balanceCurrent = clone $current;
             $balanceCurrent->subDay()->endOfDay(); // go to correct moment.
             Log::debug(sprintf('Call byAccounts("%s")', $balanceCurrent->format('Y-m-d H:i:s')));
-            $result = $helper->byAccounts($filtered, $balanceCurrent);
+            $result         = $helper->byAccounts($filtered, $balanceCurrent);
 
             // loop result, add to array.
             /** @var array $netWorthItem */
@@ -111,15 +111,15 @@ class ReportController extends Controller
                 if ('primary' === $key) {
                     continue;
                 }
-                $currencyId = $netWorthItem['currency_id'];
-                $label      = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+                $currencyId                                = $netWorthItem['currency_id'];
+                $label                                     = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale));
                 if (!array_key_exists($currencyId, $chartData)) {
                     $chartData[$currencyId] = [
-                        'label'           => 'Net worth in ' . $netWorthItem['currency_name'],
+                        'label'           => 'Net worth in '.$netWorthItem['currency_name'],
                         'type'            => 'line',
                         'currency_symbol' => $netWorthItem['currency_symbol'],
                         'currency_code'   => $netWorthItem['currency_code'],
-                        'entries'         => []
+                        'entries'         => [],
                     ];
                 }
                 $chartData[$currencyId]['entries'][$label] = $netWorthItem['balance'];
@@ -127,7 +127,7 @@ class ReportController extends Controller
             $current->addDays(7);
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data              = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -142,7 +142,7 @@ class ReportController extends Controller
     {
         $end->endOfDay();
         // chart properties for cache:
-        $cache = new CacheProperties();
+        $cache          = new CacheProperties();
         $cache->addProperty('chart.report.operations');
         $cache->addProperty($start);
         $cache->addProperty($accounts);
@@ -161,33 +161,33 @@ class ReportController extends Controller
         $chartData      = [];
 
         /** @var GroupCollectorInterface $collector */
-        $collector = app(GroupCollectorInterface::class);
+        $collector      = app(GroupCollectorInterface::class);
         $collector->setRange($start, $end)->withAccountInformation();
         $collector->setXorAccounts($accounts);
         $collector->setTypes([
             TransactionTypeEnum::WITHDRAWAL,
             TransactionTypeEnum::DEPOSIT,
             TransactionTypeEnum::RECONCILIATION,
-            TransactionTypeEnum::TRANSFER
+            TransactionTypeEnum::TRANSFER,
         ]);
-        $journals = $collector->getExtractedJournals();
+        $journals       = $collector->getExtractedJournals();
 
         // loop. group by currency and by period.
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $period     = $journal['date']->format($format);
-            $currencyId = (int) $journal['currency_id'];
-            $data[$currencyId] ??= [
+            $period                           = $journal['date']->format($format);
+            $currencyId                       = (int) $journal['currency_id'];
+            $data[$currencyId]          ??= [
                 'currency_id'             => $currencyId,
                 'currency_symbol'         => $journal['currency_symbol'],
                 'currency_code'           => $journal['currency_code'],
                 'currency_name'           => $journal['currency_name'],
-                'currency_decimal_places' => (int) $journal['currency_decimal_places']
+                'currency_decimal_places' => (int) $journal['currency_decimal_places'],
             ];
             $data[$currencyId][$period] ??= ['period' => $period, 'spent'  => '0', 'earned' => '0'];
             // in our outgoing?
-            $key    = 'spent';
-            $amount = Steam::positive($journal['amount']);
+            $key                              = 'spent';
+            $amount                           = Steam::positive($journal['amount']);
 
             // deposit = incoming
             // transfer or reconcile or opening balance, and these accounts are the destination.
@@ -211,23 +211,23 @@ class ReportController extends Controller
         /** @var array $currency */
         foreach ($data as $currency) {
             Log::debug(sprintf('Now processing currency "%s"', $currency['currency_name']));
-            $income  = [
+            $income       = [
                 'label'           => (string) trans('firefly.box_earned_in_currency', ['currency'           => $currency['currency_name']]),
                 'type'            => 'bar',
                 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
                 'currency_id'     => $currency['currency_id'],
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => []
+                'entries'         => [],
             ];
-            $expense = [
+            $expense      = [
                 'label'           => (string) trans('firefly.box_spent_in_currency', ['currency'           => $currency['currency_name']]),
                 'type'            => 'bar',
                 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
                 'currency_id'     => $currency['currency_id'],
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => []
+                'entries'         => [],
             ];
             // loop all possible periods between $start and $end
             $currentStart = clone $start;
@@ -241,28 +241,28 @@ class ReportController extends Controller
             Log::debug('Start of sub-loop');
             while ($currentStart <= $currentEnd) {
                 Log::debug(sprintf('Current start: %s', $currentStart->toW3cString()));
-                $key   = $currentStart->format($format);
-                $title = $currentStart->isoFormat($titleFormat);
+                $key          = $currentStart->format($format);
+                $title        = $currentStart->isoFormat($titleFormat);
                 // #8663 make sure the period exists in the data previously collected.
                 if (array_key_exists($key, $currency)) {
-                    $income['entries'][$title] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
+                    $income['entries'][$title]  = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
                     $expense['entries'][$title] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
                 }
                 // #9477 if the period is not in the data, add it with zero values.
                 if (!array_key_exists($key, $currency)) {
-                    $income['entries'][$title] = '0';
+                    $income['entries'][$title]  = '0';
                     $expense['entries'][$title] = '0';
                 }
                 $currentStart = Navigation::addPeriod($currentStart, $preferredRange);
             }
             Log::debug('End of sub-loop');
 
-            $chartData[] = $income;
-            $chartData[] = $expense;
+            $chartData[]  = $income;
+            $chartData[]  = $expense;
         }
         Log::debug('End of loop');
 
-        $data = $this->generator->multiSet($chartData);
+        $data           = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/TagReportController.php b/app/Http/Controllers/Chart/TagReportController.php
index 685dadf099..2f068f2dc6 100644
--- a/app/Http/Controllers/Chart/TagReportController.php
+++ b/app/Http/Controllers/Chart/TagReportController.php
@@ -75,20 +75,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['budget_name'] ?? trans('firefly.no_budget');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['budget_name'] ?? trans('firefly.no_budget');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -103,20 +103,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -131,20 +131,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -159,20 +159,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -187,20 +187,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -229,13 +229,13 @@ class TagReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['tags'] as $currentTag) {
                 foreach ($currentTag['transaction_journals'] as $journal) {
-                    $key    = $journal['date']->isoFormat($format);
-                    $amount = Steam::positive($journal['amount']);
+                    $key                                   = $journal['date']->isoFormat($format);
+                    $amount                                = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
@@ -256,20 +256,20 @@ class TagReportController extends Controller
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end)
+                'entries'         => $this->makeEntries($start, $end),
             ];
 
             foreach ($currency['tags'] as $currentTag) {
                 foreach ($currentTag['transaction_journals'] as $journal) {
-                    $key    = $journal['date']->isoFormat($format);
-                    $amount = Steam::positive($journal['amount']);
+                    $key                                   = $journal['date']->isoFormat($format);
+                    $amount                                = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiSet($chartData);
+        $data      = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -284,8 +284,8 @@ class TagReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key        = $currentStart->isoFormat($format);
+            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key          = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -304,20 +304,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -332,20 +332,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code']
+                        'currency_code'   => $currency['currency_code'],
                     ];
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -363,15 +363,15 @@ class TagReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -389,15 +389,15 @@ class TagReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code']
+                    'currency_code'   => $currency['currency_code'],
                 ];
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $amount = Steam::positive($journal['amount']);
+                    $amount                   = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
-        $data = $this->generator->multiCurrencyPieChart($result);
+        $data   = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/TransactionController.php b/app/Http/Controllers/Chart/TransactionController.php
index 5d151ba506..545c7af7d3 100644
--- a/app/Http/Controllers/Chart/TransactionController.php
+++ b/app/Http/Controllers/Chart/TransactionController.php
@@ -54,7 +54,7 @@ class TransactionController extends Controller
      */
     public function budgets(Carbon $start, Carbon $end)
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty('chart.transactions.budgets');
@@ -68,18 +68,18 @@ class TransactionController extends Controller
         $collector->withBudgetInformation();
         $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
 
-        $result = $collector->getExtractedJournals();
-        $data   = [];
+        $result    = $collector->getExtractedJournals();
+        $data      = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $budget = $journal['budget_name'] ?? (string) trans('firefly.no_budget');
-            $title  = sprintf('%s (%s)', $budget, $journal['currency_symbol']);
+            $budget                 = $journal['budget_name'] ?? (string) trans('firefly.no_budget');
+            $title                  = sprintf('%s (%s)', $budget, $journal['currency_symbol']);
             $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart = $this->generator->multiCurrencyPieChart($data);
+        $chart     = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -90,7 +90,7 @@ class TransactionController extends Controller
      */
     public function categories(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -114,18 +114,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result = $collector->getExtractedJournals();
-        $data   = [];
+        $result    = $collector->getExtractedJournals();
+        $data      = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $category = $journal['category_name'] ?? (string) trans('firefly.no_category');
-            $title    = sprintf('%s (%s)', $category, $journal['currency_symbol']);
+            $category               = $journal['category_name'] ?? (string) trans('firefly.no_category');
+            $title                  = sprintf('%s (%s)', $category, $journal['currency_symbol']);
             $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart = $this->generator->multiCurrencyPieChart($data);
+        $chart     = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -136,7 +136,7 @@ class TransactionController extends Controller
      */
     public function destinationAccounts(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -160,18 +160,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result = $collector->getExtractedJournals();
-        $data   = [];
+        $result    = $collector->getExtractedJournals();
+        $data      = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $name  = $journal['destination_account_name'];
-            $title = sprintf('%s (%s)', $name, $journal['currency_symbol']);
+            $name                   = $journal['destination_account_name'];
+            $title                  = sprintf('%s (%s)', $name, $journal['currency_symbol']);
             $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart = $this->generator->multiCurrencyPieChart($data);
+        $chart     = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -182,7 +182,7 @@ class TransactionController extends Controller
      */
     public function sourceAccounts(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache = new CacheProperties();
+        $cache     = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -206,18 +206,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result = $collector->getExtractedJournals();
-        $data   = [];
+        $result    = $collector->getExtractedJournals();
+        $data      = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $name  = $journal['source_account_name'];
-            $title = sprintf('%s (%s)', $name, $journal['currency_symbol']);
+            $name                   = $journal['source_account_name'];
+            $title                  = sprintf('%s (%s)', $name, $journal['currency_symbol']);
             $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart = $this->generator->multiCurrencyPieChart($data);
+        $chart     = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index b5e7e422ce..80d6ef8f56 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -61,10 +61,10 @@ abstract class Controller extends BaseController
     public protected(set) string $name;
     protected bool $convertToPrimary = false;
     protected string $dateTimeFormat;
-    protected null|TransactionCurrency $primaryCurrency;
+    protected ?TransactionCurrency $primaryCurrency;
     protected string $monthAndDayFormat;
     protected string $monthFormat;
-    protected string $redirectUrl = '/';
+    protected string $redirectUrl    = '/';
 
     /**
      * Controller constructor.
@@ -87,8 +87,8 @@ abstract class Controller extends BaseController
         );
 
         // share custom auth guard info.
-        $authGuard = config('firefly.authentication_guard');
-        $logoutUrl = config('firefly.custom_logout_url');
+        $authGuard        = config('firefly.authentication_guard');
+        $logoutUrl        = config('firefly.custom_logout_url');
 
         // overrule v2 layout back to v1.
         if ('true' === request()->get('force_default_layout') && 'v2' === config('view.layout')) {
@@ -101,15 +101,15 @@ abstract class Controller extends BaseController
         View::share('logoutUrl', $logoutUrl);
 
         // upload size
-        $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize'));
-        $maxPostSize = Steam::phpBytes(ini_get('post_max_size'));
-        $uploadSize  = min($maxFileSize, $maxPostSize);
+        $maxFileSize      = Steam::phpBytes(ini_get('upload_max_filesize'));
+        $maxPostSize      = Steam::phpBytes(ini_get('post_max_size'));
+        $uploadSize       = min($maxFileSize, $maxPostSize);
         View::share('uploadSize', $uploadSize);
 
         // share is alpha, is beta
-        $isAlpha   = false;
-        $isBeta    = false;
-        $isDevelop = false;
+        $isAlpha          = false;
+        $isBeta           = false;
+        $isDevelop        = false;
         if (str_contains((string) config('firefly.version'), 'alpha')) {
             $isAlpha = true;
         }
@@ -126,23 +126,23 @@ abstract class Controller extends BaseController
         View::share('FF_IS_DEVELOP', $isDevelop);
 
         $this->middleware(function ($request, $next): mixed {
-            $locale = Steam::getLocale();
+            $locale                  = Steam::getLocale();
             // translations for specific strings:
-            $this->monthFormat = (string) trans('config.month_js', [], $locale);
+            $this->monthFormat       = (string) trans('config.month_js', [], $locale);
             $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
-            $this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale);
-            $darkMode = 'browser';
-            $this->primaryCurrency = null;
+            $this->dateTimeFormat    = (string) trans('config.date_time_js', [], $locale);
+            $darkMode                = 'browser';
+            $this->primaryCurrency   = null;
             // get shown-intro-preference:
             if (auth()->check()) {
                 View::share('anonymous', Steam::anonymous());
-                $this->primaryCurrency = Amount::getPrimaryCurrency();
-                $language = Steam::getLanguage();
-                $locale   = Steam::getLocale();
-                $darkMode = Preferences::get('darkMode', 'browser')->data;
+                $this->primaryCurrency  = Amount::getPrimaryCurrency();
+                $language               = Steam::getLanguage();
+                $locale                 = Steam::getLocale();
+                $darkMode               = Preferences::get('darkMode', 'browser')->data;
                 $this->convertToPrimary = Amount::convertToPrimary();
-                $page      = $this->getPageName();
-                $shownDemo = $this->hasSeenDemo();
+                $page                   = $this->getPageName();
+                $shownDemo              = $this->hasSeenDemo();
                 View::share('language', $language);
                 View::share('locale', $locale);
                 View::share('convertToPrimary', $this->convertToPrimary);
diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php
index 0c30f7503b..0e15119815 100644
--- a/app/Http/Controllers/DebugController.php
+++ b/app/Http/Controllers/DebugController.php
@@ -137,14 +137,14 @@ class DebugController extends Controller
      */
     public function index(): Factory|\Illuminate\Contracts\View\View
     {
-        $table = $this->generateTable();
-        $table = str_replace(["\n", "\t", '  '], '', $table);
-        $now   = now(config('app.timezone'))->format('Y-m-d H:i:s');
+        $table      = $this->generateTable();
+        $table      = str_replace(["\n", "\t", '  '], '', $table);
+        $now        = now(config('app.timezone'))->format('Y-m-d H:i:s');
 
         // get latest log file:
-        $logger = Log::driver();
+        $logger     = Log::driver();
         // PHPstan doesn't recognize the method because of its polymorphic nature.
-        $handlers = $logger->getHandlers(); // @phpstan-ignore-line
+        $handlers   = $logger->getHandlers(); // @phpstan-ignore-line
         $logContent = '';
         foreach ($handlers as $handler) {
             if ($handler instanceof RotatingFileHandler) {
@@ -156,7 +156,7 @@ class DebugController extends Controller
         }
         if ('' !== $logContent) {
             // last few lines
-            $logContent = 'Truncated from this point <----|' . substr($logContent, -16384);
+            $logContent = 'Truncated from this point <----|'.substr($logContent, -16384);
         }
 
         return view('debug', ['table'      => $table, 'now'        => $now, 'logContent' => $logContent]);
@@ -198,18 +198,18 @@ class DebugController extends Controller
             'error_reporting' => $this->errorReporting((int) ini_get('error_reporting')),
             'upload_size'     => min($maxFileSize, $maxPostSize),
             'all_drivers'     => $drivers,
-            'current_driver'  => $currentDriver
+            'current_driver'  => $currentDriver,
         ];
     }
 
     private function getBuildInfo(): array
     {
         $return = [
-            'is_docker' => env('IS_DOCKER', false), // @phpstan-ignore-line
+            'is_docker'       => env('IS_DOCKER', false), // @phpstan-ignore-line
             'build'           => '(unknown)',
             'build_date'      => '(unknown)',
             'base_build'      => '(unknown)',
-            'base_build_date' => '(unknown)'
+            'base_build_date' => '(unknown)',
         ];
 
         try {
@@ -242,7 +242,7 @@ class DebugController extends Controller
 
     private function getAppInfo(): array
     {
-        $userGuard = config('auth.defaults.guard');
+        $userGuard      = config('auth.defaults.guard');
 
         $config         = FireflyConfig::get('last_rt_job', 0);
         $lastTime       = (int) $config->data;
@@ -267,26 +267,26 @@ class DebugController extends Controller
             // any of the cron jobs will do, they always run at the same time.
             // but this job is the oldest, so the biggest chance it ran once
 
-            'last_cronjob'     => $lastCronjob,
-            'last_cronjob_ago' => $lastCronjobAgo
+            'last_cronjob'       => $lastCronjob,
+            'last_cronjob_ago'   => $lastCronjobAgo,
         ];
     }
 
     private function getUserInfo(): array
     {
-        $userFlags = $this->getUserFlags();
+        $userFlags      = $this->getUserFlags();
 
         // user info
-        $userAgent = request()->header('user-agent');
+        $userAgent      = request()->header('user-agent');
 
         // set languages, see what happens:
         $original       = setlocale(LC_ALL, '0');
         $localeAttempts = [];
         $parts          = Steam::getLocaleArray(Steam::getLocale());
         foreach ($parts as $code) {
-            $code = trim($code);
+            $code                  = trim($code);
             Log::debug(sprintf('Trying to set %s', $code));
-            $result = setlocale(LC_ALL, $code);
+            $result                = setlocale(LC_ALL, $code);
             $localeAttempts[$code] = $result === $code;
         }
         setlocale(LC_ALL, (string) $original);
@@ -301,16 +301,16 @@ class DebugController extends Controller
             'locale_attempts'    => $localeAttempts,
             'locale'             => Steam::getLocale(),
             'language'           => Steam::getLanguage(),
-            'view_range'         => Preferences::get('viewRange', '1M')->data
+            'view_range'         => Preferences::get('viewRange', '1M')->data,
         ];
     }
 
     private function getUserFlags(): string
     {
-        $flags = [];
+        $flags      = [];
 
         /** @var User $user */
-        $user = auth()->user();
+        $user       = auth()->user();
 
         // has liabilities
         if ($user->accounts()->accountTypeIn([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value])->count() > 0) {
@@ -326,7 +326,7 @@ class DebugController extends Controller
         }
 
         // has stored reconciliations
-        $type = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
+        $type       = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
         if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) {
             $flags[] = ':ledger:';
         }
@@ -386,7 +386,7 @@ class DebugController extends Controller
                 if (null === $route->getName()) {
                     var_dump($route);
 
-                    exit();
+                    exit;
                 }
 
                 echo substr($route->uri(), 3);
@@ -398,7 +398,7 @@ class DebugController extends Controller
                 }
             }
 
-            exit();
+            exit;
         }
 
         $return = [];
@@ -427,25 +427,25 @@ class DebugController extends Controller
             if (null === $route->getName()) {
                 var_dump($route);
 
-                exit();
+                exit;
             }
             if (!str_contains($route->uri(), '{')) {
                 $return[$route->getName()] = route($route->getName());
 
                 continue;
             }
-            $params = [];
+            $params                    = [];
             foreach ($route->parameterNames() as $name) {
                 $params[] = $this->getParameter($name);
             }
             $return[$route->getName()] = route($route->getName(), $params);
         }
-        $count = 0;
+        $count  = 0;
         echo '
'; echo '

Routes

'; echo sprintf('

%s

', $count); foreach ($return as $name => $path) { - echo sprintf('%2$s
', $path, $name) . PHP_EOL; + echo sprintf('%2$s
', $path, $name).PHP_EOL; ++$count; if (0 === ($count % 10)) { echo '
'; @@ -453,7 +453,7 @@ class DebugController extends Controller } } - exit(); + exit; } private function getParameter(string $name): string diff --git a/app/Http/Controllers/Export/IndexController.php b/app/Http/Controllers/Export/IndexController.php index b8ed8e9075..cc0903e402 100644 --- a/app/Http/Controllers/Export/IndexController.php +++ b/app/Http/Controllers/Export/IndexController.php @@ -83,30 +83,31 @@ class IndexController extends Controller // get first transaction in DB: $firstDate = today(config('app.timezone')); $firstDate->subYear(); - $journal = $this->journalRepository->firstNull(); + $journal = $this->journalRepository->firstNull(); if ($journal instanceof TransactionJournal) { Log::debug('First journal is NULL, using today() - 1 year.'); $firstDate = clone $journal->date; } $generator->setStart($firstDate); - $result = $generator->export(); + $result = $generator->export(); - $name = sprintf('%s_transaction_export.csv', Carbon::now()->format('Y_m_d')); - $quoted = sprintf('"%s"', addcslashes($name, '"\\')); + $name = sprintf('%s_transaction_export.csv', Carbon::now()->format('Y_m_d')); + $quoted = sprintf('"%s"', addcslashes($name, '"\\')); // headers for CSV file. /** @var LaravelResponse $response */ - $response = response($result['transactions']); + $response = response($result['transactions']); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'text/x-csv') - ->header('Content-Disposition', 'attachment; filename=' . $quoted) + ->header('Content-Disposition', 'attachment; filename='.$quoted) // ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen((string) $result['transactions'])); + ->header('Content-Length', (string) strlen((string) $result['transactions'])) + ; // return CSV file made from 'transactions' array. return $response; diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index b4c36d90d0..2ff59a6f95 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -63,8 +63,8 @@ class HomeController extends Controller */ public function dateRange(Request $request): JsonResponse { - $stringStart = ''; - $stringEnd = ''; + $stringStart = ''; + $stringEnd = ''; try { $stringStart = e((string) $request->get('start')); @@ -99,7 +99,7 @@ class HomeController extends Controller Log::debug('Range is now marked as "custom".'); } - $diff = $start->diffInDays($end, true) + 1; + $diff = $start->diffInDays($end, true) + 1; if ($diff > 366) { $request->session()->flash('warning', (string) trans('firefly.warning_much_data', ['days' => (int) $diff])); @@ -154,13 +154,13 @@ class HomeController extends Controller } /** @var Carbon $start */ - $start = session('start', today(config('app.timezone'))->startOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); - $accounts = $repository->getAccountsById($frontpageArray); - $today = today(config('app.timezone')); - $accounts = $accounts->sortBy('order'); // sort frontpage accounts by order + $end = session('end', today(config('app.timezone'))->endOfMonth()); + $accounts = $repository->getAccountsById($frontpageArray); + $today = today(config('app.timezone')); + $accounts = $accounts->sortBy('order'); // sort frontpage accounts by order Log::debug('Frontpage accounts are ', $frontpageArray); @@ -170,14 +170,14 @@ class HomeController extends Controller // collect groups for each transaction. foreach ($accounts as $account) { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts(new Collection()->push($account))->withAccountInformation()->setRange($start, $end)->setLimit(10)->setPage(1); - $set = $collector->getExtractedJournals(); + $set = $collector->getExtractedJournals(); $transactions[] = ['transactions' => $set, 'account' => $account]; } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); event(new RequestedVersionCheckStatus($user)); return view('index', [ @@ -188,7 +188,7 @@ class HomeController extends Controller 'start' => $start, 'end' => $end, 'today' => $today, - 'pageTitle' => $pageTitle + 'pageTitle' => $pageTitle, ]); } @@ -197,11 +197,11 @@ class HomeController extends Controller $subTitle = (string) trans('firefly.welcome_back'); $pageTitle = (string) trans('firefly.main_dashboard_page_title'); - $start = session('start', today(config('app.timezone'))->startOfMonth()); - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); event(new RequestedVersionCheckStatus($user)); return view('index', ['subTitle' => $subTitle, 'start' => $start, 'end' => $end, 'pageTitle' => $pageTitle]); diff --git a/app/Http/Controllers/JavascriptController.php b/app/Http/Controllers/JavascriptController.php index 38ade39a93..a6aea3ccbf 100644 --- a/app/Http/Controllers/JavascriptController.php +++ b/app/Http/Controllers/JavascriptController.php @@ -57,16 +57,16 @@ class JavascriptController extends Controller AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value + AccountTypeEnum::CREDITCARD->value, ]); $data = ['accounts' => []]; /** @var Account $account */ foreach ($accounts as $account) { - $accountId = $account->id; - $currency = (int) $repository->getMetaValue($account, 'currency_id'); - $currency = 0 === $currency ? $this->primaryCurrency->id : $currency; - $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; + $accountId = $account->id; + $currency = (int) $repository->getMetaValue($account, 'currency_id'); + $currency = 0 === $currency ? $this->primaryCurrency->id : $currency; + $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; $data['accounts'][$accountId] = $entry; } @@ -83,8 +83,8 @@ class JavascriptController extends Controller /** @var TransactionCurrency $currency */ foreach ($currencies as $currency) { - $currencyId = $currency->id; - $entry = ['name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol]; + $currencyId = $currency->id; + $entry = ['name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol]; $data['currencies'][$currencyId] = $entry; } @@ -100,19 +100,19 @@ class JavascriptController extends Controller */ public function variables(Request $request, AccountRepositoryInterface $repository): Response { - $account = $repository->find((int) $request->get('account')); - $currency = $this->primaryCurrency; + $account = $repository->find((int) $request->get('account')); + $currency = $this->primaryCurrency; if ($account instanceof Account) { $currency = $repository->getAccountCurrency($account) ?? $this->primaryCurrency; } - $locale = Steam::getLocale(); - $accounting = Amount::getJsConfig(); + $locale = Steam::getLocale(); + $accounting = Amount::getJsConfig(); $accounting['frac_digits'] = $currency->decimal_places; - $pref = Preferences::get('language', config('firefly.default_language', 'en_US')); - $lang = $pref->data; - $dateRange = $this->getDateRangeConfig(); - $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string) config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); - $data = [ + $pref = Preferences::get('language', config('firefly.default_language', 'en_US')); + $lang = $pref->data; + $dateRange = $this->getDateRangeConfig(); + $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string) config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); + $data = [ 'currencyCode' => $currency->code, 'currencySymbol' => $currency->symbol, 'accountingLocaleInfo' => $accounting, @@ -121,7 +121,7 @@ class JavascriptController extends Controller 'dateRangeTitle' => $dateRange['title'], 'locale' => $locale, 'dateRangeConfig' => $dateRange['configuration'], - 'uid' => $uid + 'uid' => $uid, ]; $request->session()->keep(['two-factor-secret']); @@ -137,9 +137,9 @@ class JavascriptController extends Controller $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $data = ['start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d')]; + $data = ['start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d')]; return response()->view('v2.javascript.variables', $data)->header('Content-Type', 'text/javascript'); } diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index 0cf87b23d8..4f88b98e31 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -63,11 +63,11 @@ class BoxController extends Controller { // Cache result, return cache if present. /** @var Carbon $start */ - $start = session('start', today(config('app.timezone'))->startOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); - $cache = new CacheProperties(); + $end = session('end', today(config('app.timezone'))->endOfMonth()); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($this->convertToPrimary); @@ -76,61 +76,61 @@ class BoxController extends Controller return response()->json($cache->get()); } // prep some arrays: - $incomes = []; - $expenses = []; - $sums = []; - $currency = $this->primaryCurrency; + $incomes = []; + $expenses = []; + $sums = []; + $currency = $this->primaryCurrency; // collect income of user: /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $set = $collector->getExtractedJournals(); + $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToPrimary && $this->primaryCurrency->id !== (int) $journal['currency_id'] + $currencyId = $this->convertToPrimary && $this->primaryCurrency->id !== (int) $journal['currency_id'] ? $this->primaryCurrency->id : (int) $journal['currency_id']; - $amount = Amount::getAmountFromJournal($journal); + $amount = Amount::getAmountFromJournal($journal); $incomes[$currencyId] ??= '0'; $incomes[$currencyId] = bcadd($incomes[$currencyId], Steam::positive($amount)); - $sums[$currencyId] ??= '0'; - $sums[$currencyId] = bcadd($sums[$currencyId], Steam::positive($amount)); + $sums[$currencyId] ??= '0'; + $sums[$currencyId] = bcadd($sums[$currencyId], Steam::positive($amount)); } // collect expenses /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $set = $collector->getExtractedJournals(); + $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToPrimary ? $this->primaryCurrency->id : (int) $journal['currency_id']; - $amount = Amount::getAmountFromJournal($journal); + $currencyId = $this->convertToPrimary ? $this->primaryCurrency->id : (int) $journal['currency_id']; + $amount = Amount::getAmountFromJournal($journal); $expenses[$currencyId] ??= '0'; $expenses[$currencyId] = bcadd($expenses[$currencyId], $amount); - $sums[$currencyId] ??= '0'; - $sums[$currencyId] = bcadd($sums[$currencyId], $amount); + $sums[$currencyId] ??= '0'; + $sums[$currencyId] = bcadd($sums[$currencyId], $amount); } // format amounts: - $keys = array_keys($sums); + $keys = array_keys($sums); foreach ($keys as $currencyId) { - $currency = $repository->find($currencyId); - $sums[$currencyId] = Amount::formatAnything($currency, $sums[$currencyId], false); - $incomes[$currencyId] = Amount::formatAnything($currency, $incomes[$currencyId] ?? '0', false); + $currency = $repository->find($currencyId); + $sums[$currencyId] = Amount::formatAnything($currency, $sums[$currencyId], false); + $incomes[$currencyId] = Amount::formatAnything($currency, $incomes[$currencyId] ?? '0', false); $expenses[$currencyId] = Amount::formatAnything($currency, $expenses[$currencyId] ?? '0', false); } if (0 === count($sums)) { - $currency = $this->primaryCurrency; - $sums[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); - $incomes[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); + $currency = $this->primaryCurrency; + $sums[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); + $incomes[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); $expenses[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); } - $response = ['incomes' => $incomes, 'expenses' => $expenses, 'sums' => $sums, 'size' => count($sums), 'preferred' => $currency->id]; + $response = ['incomes' => $incomes, 'expenses' => $expenses, 'sums' => $sums, 'size' => count($sums), 'preferred' => $currency->id]; $cache->store($response); return response()->json($response); @@ -141,7 +141,7 @@ class BoxController extends Controller */ public function netWorth(): JsonResponse { - $date = today(config('app.timezone'))->endOfDay(); + $date = today(config('app.timezone'))->endOfDay(); // start and end in the future? use $end if ($this->notInSessionRange($date)) { @@ -150,7 +150,7 @@ class BoxController extends Controller } /** @var NetWorthInterface $netWorthHelper */ - $netWorthHelper = app(NetWorthInterface::class); + $netWorthHelper = app(NetWorthInterface::class); $netWorthHelper->setUser(auth()->user()); /** @var AccountRepositoryInterface $accountRepository */ @@ -160,12 +160,12 @@ class BoxController extends Controller AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); Log::debug(sprintf('Found %d accounts.', $allAccounts->count())); // filter list on preference of being included. - $filtered = $allAccounts->filter(static function (Account $account) use ($accountRepository): bool { + $filtered = $allAccounts->filter(static function (Account $account) use ($accountRepository): bool { $includeNetWorth = $accountRepository->getMetaValue($account, 'include_net_worth'); $result = null === $includeNetWorth || '1' === $includeNetWorth; if (false === $result) { @@ -175,15 +175,15 @@ class BoxController extends Controller return $result; }); - $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); - $return = []; + $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); + $return = []; foreach ($netWorthSet as $key => $data) { if ('primary' === $key) { continue; } $return[$data['currency_id']] = Amount::formatFlat($data['currency_symbol'], $data['currency_decimal_places'], $data['balance'], false); } - $return = ['net_worths' => array_values($return)]; + $return = ['net_worths' => array_values($return)]; return response()->json($return); } diff --git a/app/Http/Controllers/Json/BudgetController.php b/app/Http/Controllers/Json/BudgetController.php index c4da7bafaa..985059bc18 100644 --- a/app/Http/Controllers/Json/BudgetController.php +++ b/app/Http/Controllers/Json/BudgetController.php @@ -56,7 +56,7 @@ class BudgetController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->cleanupBudgets(); @@ -90,7 +90,7 @@ class BudgetController extends Controller 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]); } } diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index 5c64ba6f73..3072be7416 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -52,24 +52,24 @@ class FrontpageController extends Controller $pcAmount = $repository->getCurrentPrimaryCurrencyAmount($piggyBank); if (1 === bccomp($amount, '0')) { // percentage! - $pct = 0; + $pct = 0; if (0 !== bccomp((string) $piggyBank->target_amount, '0')) { $pct = (int) bcmul(bcdiv($amount, (string) $piggyBank->target_amount), '100'); } - $entry = [ - 'id' => $piggyBank->id, - 'name' => $piggyBank->name, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'target' => $piggyBank->target_amount, - 'pc_target' => $piggyBank->native_target_amount, - 'percentage' => $pct, + $entry = [ + 'id' => $piggyBank->id, + 'name' => $piggyBank->name, + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'target' => $piggyBank->target_amount, + 'pc_target' => $piggyBank->native_target_amount, + 'percentage' => $pct, // currency: 'currency_symbol' => $piggyBank->transactionCurrency->symbol, 'currency_decimal_places' => $piggyBank->transactionCurrency->decimal_places, 'primary_currency_symbol' => $this->primaryCurrency->symbol, - 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places + 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, ]; $info[] = $entry; @@ -77,7 +77,7 @@ class FrontpageController extends Controller } // sort by current percentage (lowest at the top) - uasort($info, static fn(array $a, array $b): int => $a['percentage'] <=> $b['percentage']); + uasort($info, static fn (array $a, array $b): int => $a['percentage'] <=> $b['percentage']); $html = ''; if (0 !== count($info)) { @@ -87,7 +87,7 @@ class FrontpageController extends Controller $html = view('json.piggy-banks', [ 'info' => $info, 'convertToPrimary' => $convertToPrimary, - 'primary' => $primary + 'primary' => $primary, ])->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render json.piggy-banks: %s', $e->getMessage())); diff --git a/app/Http/Controllers/Json/IntroController.php b/app/Http/Controllers/Json/IntroController.php index 4af241a1d6..c045981885 100644 --- a/app/Http/Controllers/Json/IntroController.php +++ b/app/Http/Controllers/Json/IntroController.php @@ -39,10 +39,10 @@ class IntroController extends Controller /** * Returns the introduction wizard for a page. */ - public function getIntroSteps(string $route, null|string $specificPage = null): JsonResponse + public function getIntroSteps(string $route, ?string $specificPage = null): JsonResponse { Log::debug(sprintf('getIntroSteps for route "%s" and page "%s"', $route, $specificPage)); - $specificPage ??= ''; + $specificPage ??= ''; $steps = $this->getBasicSteps($route); $specificSteps = $this->getSpecificSteps($route, $specificPage); if (0 === count($specificSteps)) { @@ -56,8 +56,8 @@ class IntroController extends Controller // remove last step: array_pop($steps); // merge arrays and add last step again - $steps = array_merge($steps, $specificSteps); - $steps[] = $lastStep; + $steps = array_merge($steps, $specificSteps); + $steps[] = $lastStep; } if (!$this->hasOutroStep($route)) { $steps = array_merge($steps, $specificSteps); @@ -78,7 +78,7 @@ class IntroController extends Controller return false; } - $hasStep = array_key_exists('outro', $elements); + $hasStep = array_key_exists('outro', $elements); Log::debug('Elements is array', $elements); Log::debug('Keys is', array_keys($elements)); @@ -90,11 +90,11 @@ class IntroController extends Controller /** * Enable the boxes for a specific page again. */ - public function postEnable(string $route, null|string $specialPage = null): JsonResponse + public function postEnable(string $route, ?string $specialPage = null): JsonResponse { $specialPage ??= ''; - $route = str_replace('.', '_', $route); - $key = sprintf('shown_demo_%s', $route); + $route = str_replace('.', '_', $route); + $key = sprintf('shown_demo_%s', $route); if ('' !== $specialPage) { $key = sprintf('%s_%s', $key, $specialPage); } @@ -108,10 +108,10 @@ class IntroController extends Controller /** * Set that you saw them. */ - public function postFinished(string $route, null|string $specialPage = null): JsonResponse + public function postFinished(string $route, ?string $specialPage = null): JsonResponse { $specialPage ??= ''; - $key = sprintf('shown_demo_%s', $route); + $key = sprintf('shown_demo_%s', $route); if ('' !== $specialPage) { $key = sprintf('%s_%s', $key, $specialPage); } diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index 574cc74608..5268a6e7dd 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -68,7 +68,7 @@ class ReconcileController extends Controller * * @throws FireflyException */ - public function overview(Request $request, null|Account $account = null, null|Carbon $start = null, null|Carbon $end = null): JsonResponse + public function overview(Request $request, ?Account $account = null, ?Carbon $start = null, ?Carbon $end = null): JsonResponse { $startBalance = $request->get('startBalance'); $endBalance = $request->get('endBalance'); @@ -101,13 +101,13 @@ class ReconcileController extends Controller /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setJournalIds($selectedIds); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); } // Collect all journals already reconciled if (count($clearedIds) > 0) { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setJournalIds($clearedIds); $clearedJournals = $collector->getExtractedJournals(); } @@ -128,10 +128,10 @@ class ReconcileController extends Controller Log::debug(sprintf('End balance: "%s"', $endBalance)); Log::debug(sprintf('Cleared amount: "%s"', $clearedAmount)); Log::debug(sprintf('Amount: "%s"', $amount)); - $difference = bcadd(bcadd(bcsub($startBalance ?? '0', $endBalance ?? '0'), $clearedAmount), $amount); - $diffCompare = bccomp($difference, '0'); - $countCleared = count($clearedJournals); - $reconSum = bcadd(bcadd($startBalance ?? '0', $amount), $clearedAmount); + $difference = bcadd(bcadd(bcsub($startBalance ?? '0', $endBalance ?? '0'), $clearedAmount), $amount); + $diffCompare = bccomp($difference, '0'); + $countCleared = count($clearedJournals); + $reconSum = bcadd(bcadd($startBalance ?? '0', $amount), $clearedAmount); try { $view = view('accounts.reconcile.overview', [ @@ -147,7 +147,7 @@ class ReconcileController extends Controller 'route' => $route, 'countCleared' => $countCleared, 'reconSum' => $reconSum, - 'selectedIds' => $selectedIds + 'selectedIds' => $selectedIds, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('View error: %s', $e->getMessage())); @@ -157,14 +157,14 @@ class ReconcileController extends Controller throw new FireflyException($view, 0, $e); } - $return = ['post_url' => $route, 'html' => $view]; + $return = ['post_url' => $route, 'html' => $view]; return response()->json($return); } private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string { - $toAdd = '0'; + $toAdd = '0'; Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description'])); // not much magic below we need to cover using tests. @@ -200,7 +200,7 @@ class ReconcileController extends Controller * * @throws FireflyException */ - public function transactions(Account $account, null|Carbon $start = null, null|Carbon $end = null) + public function transactions(Account $account, ?Carbon $start = null, ?Carbon $end = null) { if (!$start instanceof Carbon || !$end instanceof Carbon) { throw new FireflyException('Invalid dates submitted.'); @@ -210,10 +210,10 @@ class ReconcileController extends Controller } $start->endOfDay(); $end->endOfDay(); - $startDate = clone $start; + $startDate = clone $start; $startDate->subDay(); - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // correct Log::debug(sprintf('transactions: Call accountsBalancesOptimized with date/time "%s"', $startDate->toIso8601String())); Log::debug(sprintf('transactions2: Call accountsBalancesOptimized with date/time "%s"', $end->toIso8601String())); @@ -222,8 +222,8 @@ class ReconcileController extends Controller // $startBalance = Steam::bcround(Steam::finalAccountBalance($account, $startDate)['balance'], $currency->decimal_places); // $endBalance = Steam::bcround(Steam::finalAccountBalance($account, $end)['balance'], $currency->decimal_places); - $startBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $startDate)[$account->id]; - $endBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]; + $startBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $startDate)[$account->id]; + $endBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]; // round balances. foreach ($startBalance as $key => $value) { $startBalance[$key] = Steam::bcround($value, $currency->decimal_places); @@ -236,7 +236,7 @@ class ReconcileController extends Controller $selectionStart = clone $start; $selectionStart->startOfDay(); $selectionStart->subDays(3); - $selectionEnd = clone $end; + $selectionEnd = clone $end; $selectionEnd->endOfDay(); $selectionEnd->addDays(3); @@ -245,16 +245,17 @@ class ReconcileController extends Controller // grab transactions: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setRange($selectionStart, $selectionEnd) ->withBudgetInformation() ->withCategoryInformation() - ->withAccountInformation(); - $array = $collector->getExtractedJournals(); - $journals = $this->processTransactions($account, $array); + ->withAccountInformation() + ; + $array = $collector->getExtractedJournals(); + $journals = $this->processTransactions($account, $array); try { $html = view('accounts.reconcile.transactions', [ @@ -264,7 +265,7 @@ class ReconcileController extends Controller 'start' => $start, 'end' => $end, 'selectionStart' => $selectionStart, - 'selectionEnd' => $selectionEnd + 'selectionEnd' => $selectionEnd, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render: %s', $e->getMessage())); @@ -286,7 +287,7 @@ class ReconcileController extends Controller /** @var array $journal */ foreach ($array as $journal) { - $inverse = false; + $inverse = false; if (TransactionTypeEnum::DEPOSIT->value === $journal['transaction_type_type']) { $inverse = true; diff --git a/app/Http/Controllers/Json/RecurrenceController.php b/app/Http/Controllers/Json/RecurrenceController.php index 84df7c15a5..10c4c14ec9 100644 --- a/app/Http/Controllers/Json/RecurrenceController.php +++ b/app/Http/Controllers/Json/RecurrenceController.php @@ -67,20 +67,20 @@ class RecurrenceController extends Controller */ public function events(Request $request): JsonResponse { - $occurrences = []; - $return = []; - $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); - $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); - $firstDate = Carbon::createFromFormat('Y-m-d', $request->get('first_date')); - $endDate = '' !== (string) $request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null; - $endsAt = (string) $request->get('ends'); - $repetitionType = explode(',', (string) $request->get('type'))[0]; - $repetitions = (int) $request->get('reps'); - $weekend = (int) $request->get('weekend'); - $repetitionMoment = ''; - $skip = (int) $request->get('skip'); - $skip = $skip < 0 || $skip > 31 ? 0 : $skip; - $weekend = $weekend < 1 || $weekend > 4 ? 1 : $weekend; + $occurrences = []; + $return = []; + $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); + $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); + $firstDate = Carbon::createFromFormat('Y-m-d', $request->get('first_date')); + $endDate = '' !== (string) $request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null; + $endsAt = (string) $request->get('ends'); + $repetitionType = explode(',', (string) $request->get('type'))[0]; + $repetitions = (int) $request->get('reps'); + $weekend = (int) $request->get('weekend'); + $repetitionMoment = ''; + $skip = (int) $request->get('skip'); + $skip = $skip < 0 || $skip > 31 ? 0 : $skip; + $weekend = $weekend < 1 || $weekend > 4 ? 1 : $weekend; if (!$endDate instanceof Carbon) { // safety catch: @@ -98,7 +98,7 @@ class RecurrenceController extends Controller return response()->json(); } // if $firstDate is beyond start, use that one: - $actualStart = clone $firstDate; + $actualStart = clone $firstDate; if ('weekly' === $repetitionType || 'monthly' === $repetitionType) { $repetitionMoment = explode(',', (string) $request->get('type'))[1] ?? '1'; @@ -110,12 +110,12 @@ class RecurrenceController extends Controller $repetitionMoment = explode(',', (string) $request->get('type'))[1] ?? '2025-01-01'; } $actualStart->startOfDay(); - $repetition = new RecurrenceRepetition(); - $repetition->repetition_type = $repetitionType; + $repetition = new RecurrenceRepetition(); + $repetition->repetition_type = $repetitionType; $repetition->repetition_moment = $repetitionMoment; - $repetition->repetition_skip = $skip; - $repetition->weekend = $weekend; - $actualEnd = clone $end; + $repetition->repetition_skip = $skip; + $repetition->weekend = $weekend; + $actualEnd = clone $end; if ('until_date' === $endsAt) { $actualEnd = $endDate; @@ -132,14 +132,14 @@ class RecurrenceController extends Controller /** @var Carbon $current */ foreach ($occurrences as $current) { if ($current->gte($start)) { - $event = [ - 'id' => $repetitionType . $firstDate->format('Ymd'), + $event = [ + 'id' => $repetitionType.$firstDate->format('Ymd'), 'title' => 'X', 'allDay' => true, 'start' => $current->format('Y-m-d'), 'end' => $current->format('Y-m-d'), 'editable' => false, - 'rendering' => 'background' + 'rendering' => 'background', ]; $return[] = $event; } @@ -153,8 +153,8 @@ class RecurrenceController extends Controller */ public function suggest(Request $request): JsonResponse { - $string = '' === (string) $request->get('date') ? Carbon::now()->format('Y-m-d') : (string) $request->get('date'); - $today = today(config('app.timezone'))->startOfDay(); + $string = '' === (string) $request->get('date') ? Carbon::now()->format('Y-m-d') : (string) $request->get('date'); + $today = today(config('app.timezone'))->startOfDay(); try { $date = Carbon::createFromFormat('Y-m-d', $string, config('app.timezone')); @@ -171,7 +171,7 @@ class RecurrenceController extends Controller Log::debug(sprintf('date = %s, today = %s. date > today? %s', $date->toAtomString(), $today->toAtomString(), var_export($date > $today, true))); Log::debug(sprintf('past = true? %s', var_export('true' === (string) $request->get('past'), true))); - $result = []; + $result = []; if ($date > $today || 'true' === (string) $request->get('past')) { Log::debug('Will fill dropdown.'); $weekly = sprintf('weekly,%s', $date->dayOfWeekIso); @@ -184,20 +184,20 @@ class RecurrenceController extends Controller 'daily' => ['label' => (string) trans('firefly.recurring_daily'), 'selected' => str_starts_with($preSelected, 'daily')], $weekly => [ 'label' => (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), - 'selected' => str_starts_with($preSelected, 'weekly') + 'selected' => str_starts_with($preSelected, 'weekly'), ], $monthly => [ 'label' => (string) trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), - 'selected' => str_starts_with($preSelected, 'monthly') + 'selected' => str_starts_with($preSelected, 'monthly'), ], $ndom => [ 'label' => (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), - 'selected' => str_starts_with($preSelected, 'ndom') + 'selected' => str_starts_with($preSelected, 'ndom'), ], $yearly => [ 'label' => (string) trans('firefly.recurring_yearly', ['date' => $yearlyDate]), - 'selected' => str_starts_with($preSelected, 'yearly') - ] + 'selected' => str_starts_with($preSelected, 'yearly'), + ], ]; } Log::debug('Dropdown is', $result); diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index db3c8a19ce..64d42e318b 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -47,7 +47,7 @@ class RuleController extends Controller $keys = array_keys(config('firefly.rule-actions')); $actions = []; foreach ($keys as $key) { - $actions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice'); + $actions[$key] = (string) trans('firefly.rule_action_'.$key.'_choice'); } try { diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index 05b3a8b3c6..905ff872a3 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -68,8 +68,8 @@ class NewUserController extends Controller app('view')->share('title', (string) trans('firefly.welcome')); app('view')->share('mainTitleIcon', 'fa-fire'); - $types = config('firefly.accountTypesByIdentifier.asset'); - $count = $this->repository->count($types); + $types = config('firefly.accountTypesByIdentifier.asset'); + $count = $this->repository->count($types); $languages = []; @@ -85,7 +85,7 @@ class NewUserController extends Controller */ public function submit(NewUserFormRequest $request, CurrencyRepositoryInterface $currencyRepository): Redirector|RedirectResponse { - $language = $request->convertString('language'); + $language = $request->convertString('language'); if (!array_key_exists($language, config('firefly.languages'))) { $language = 'en_US'; } @@ -93,7 +93,7 @@ class NewUserController extends Controller // set language preference: Preferences::set('language', $language); // Store currency preference from input: - $currency = $currencyRepository->find((int) $request->input('amount_currency_id_bank_balance')); + $currency = $currencyRepository->find((int) $request->input('amount_currency_id_bank_balance')); // if is null, set to EUR: if (!$currency instanceof TransactionCurrency) { @@ -109,10 +109,11 @@ class NewUserController extends Controller $currencyRepository->makePrimary($currency); // store frontpage preferences: - $accounts = $this->repository + $accounts = $this->repository ->getAccountsByType([AccountTypeEnum::ASSET->value]) ->pluck('id') - ->toArray(); + ->toArray() + ; Preferences::set('frontpageAccounts', $accounts); // mark. @@ -128,7 +129,7 @@ class NewUserController extends Controller 'invoice_date' => false, 'internal_reference' => false, 'notes' => true, - 'attachments' => true + 'attachments' => true, ]; Preferences::set('transaction_journal_optional_fields', $visibleFields); diff --git a/app/Http/Controllers/ObjectGroup/EditController.php b/app/Http/Controllers/ObjectGroup/EditController.php index f888b22070..d2156380d3 100644 --- a/app/Http/Controllers/ObjectGroup/EditController.php +++ b/app/Http/Controllers/ObjectGroup/EditController.php @@ -88,7 +88,7 @@ class EditController extends Controller session()->flash('success', (string) trans('firefly.updated_object_group', ['title' => $objectGroup->title])); Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('object-groups.edit.url')); + $redirect = redirect($this->getPreviousUrl('object-groups.edit.url')); if (1 === (int) $request->get('return_to_edit')) { session()->put('object-groups.edit.fromUpdate', true); diff --git a/app/Http/Controllers/PiggyBank/AmountController.php b/app/Http/Controllers/PiggyBank/AmountController.php index b780249bbc..acd50dedef 100644 --- a/app/Http/Controllers/PiggyBank/AmountController.php +++ b/app/Http/Controllers/PiggyBank/AmountController.php @@ -87,16 +87,16 @@ class AmountController extends Controller $maxAmount )); - $accounts[] = [ + $accounts[] = [ 'account' => $account, 'left_on_account' => $leftOnAccount, 'total_saved' => $totalSaved, 'left_to_save' => $leftToSave, - 'max_amount' => $maxAmount + 'max_amount' => $maxAmount, ]; - $total = bcadd($total, $leftOnAccount); + $total = bcadd($total, $leftOnAccount); } - $total = (float) $total; // intentional float. + $total = (float) $total; // intentional float. return view('piggy-banks.add', ['piggyBank' => $piggyBank, 'accounts' => $accounts, 'total' => $total]); } @@ -117,14 +117,14 @@ class AmountController extends Controller $leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $account, $date); $leftToSave = bcsub($piggyBank->target_amount, $totalSaved); $maxAmount = 0 === bccomp($piggyBank->target_amount, '0') ? $leftOnAccount : min($leftOnAccount, $leftToSave); - $accounts[] = [ + $accounts[] = [ 'account' => $account, 'left_on_account' => $leftOnAccount, 'total_saved' => $totalSaved, 'left_to_save' => $leftToSave, - 'max_amount' => $maxAmount + 'max_amount' => $maxAmount, ]; - $total = bcadd($total, $leftOnAccount); + $total = bcadd($total, $leftOnAccount); } return view('piggy-banks.add-mobile', ['piggyBank' => $piggyBank, 'total' => $total, 'accounts' => $accounts]); @@ -142,7 +142,7 @@ class AmountController extends Controller /** @var Account $account */ foreach ($piggyBank->accounts as $account) { - $amount = (string) ($amounts[$account->id] ?? '0'); + $amount = (string) ($amounts[$account->id] ?? '0'); if ('' === $amount || 0 === bccomp($amount, '0')) { continue; } @@ -158,7 +158,7 @@ class AmountController extends Controller $amount = $leftToSave; } - $canAddAmount = $this->piggyRepos->canAddAmount($piggyBank, $account, $amount); + $canAddAmount = $this->piggyRepos->canAddAmount($piggyBank, $account, $amount); if ($canAddAmount) { $this->piggyRepos->addAmount($piggyBank, $account, $amount); $total = bcadd($total, $amount); @@ -170,7 +170,7 @@ class AmountController extends Controller 'success', (string) trans('firefly.added_amount_to_piggy', [ 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), - 'name' => $piggyBank->name + 'name' => $piggyBank->name, ]) ); Preferences::mark(); @@ -182,7 +182,7 @@ class AmountController extends Controller 'error', (string) trans('firefly.cannot_add_amount_piggy', [ 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), - 'name' => e($piggyBank->name) + 'name' => e($piggyBank->name), ]) ); @@ -198,7 +198,7 @@ class AmountController extends Controller if (!is_array($amounts)) { $amounts = []; } - $total = '0'; + $total = '0'; /** @var Account $account */ foreach ($piggyBank->accounts as $account) { @@ -219,7 +219,7 @@ class AmountController extends Controller 'success', (string) trans('firefly.removed_amount_from_piggy', [ 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), - 'name' => $piggyBank->name + 'name' => $piggyBank->name, ]) ); Preferences::mark(); @@ -231,7 +231,7 @@ class AmountController extends Controller 'error', (string) trans('firefly.cannot_remove_from_piggy', [ 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), - 'name' => e($piggyBank->name) + 'name' => e($piggyBank->name), ]) ); diff --git a/app/Http/Controllers/PiggyBank/CreateController.php b/app/Http/Controllers/PiggyBank/CreateController.php index 2c6be7d1a9..0da83ba343 100644 --- a/app/Http/Controllers/PiggyBank/CreateController.php +++ b/app/Http/Controllers/PiggyBank/CreateController.php @@ -57,7 +57,7 @@ class CreateController extends Controller app('view')->share('mainTitleIcon', 'fa-bullseye'); $this->attachments = app(AttachmentHelperInterface::class); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); return $next($request); }); @@ -73,7 +73,7 @@ class CreateController extends Controller $subTitle = (string) trans('firefly.new_piggy_bank'); $subTitleIcon = 'fa-plus'; $request->old('_token'); - $preFilled = $request->old(); + $preFilled = $request->old(); if (!array_key_exists('transaction_currency_id', $preFilled)) { $preFilled['transaction_currency_id'] = $this->primaryCurrency->id; } @@ -96,7 +96,7 @@ class CreateController extends Controller */ public function store(PiggyBankStoreRequest $request) { - $data = $request->getPiggyBankData(); + $data = $request->getPiggyBankData(); if (null === $data['start_date']) { $data['start_date'] = today(config('app.timezone')); @@ -109,7 +109,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($piggyBank, $files); } @@ -121,7 +121,7 @@ class CreateController extends Controller if (count($this->attachments->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } - $redirect = redirect($this->getPreviousUrl('piggy-banks.create.url')); + $redirect = redirect($this->getPreviousUrl('piggy-banks.create.url')); if (1 === (int) $request->get('create_another')) { session()->put('piggy-banks.create.fromStore', true); diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php index ef4e2e4d9a..4d80f1e53a 100644 --- a/app/Http/Controllers/PiggyBank/EditController.php +++ b/app/Http/Controllers/PiggyBank/EditController.php @@ -57,7 +57,7 @@ class EditController extends Controller app('view')->share('mainTitleIcon', 'fa-bullseye'); $this->attachments = app(AttachmentHelperInterface::class); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); return $next($request); }); @@ -82,10 +82,10 @@ class EditController extends Controller $subTitleIcon = 'fa-pencil'; $note = $piggyBank->notes()->first(); // Flash some data to fill the form. - $targetDate = $piggyBank->target_date?->format('Y-m-d'); - $startDate = $piggyBank->start_date?->format('Y-m-d'); + $targetDate = $piggyBank->target_date?->format('Y-m-d'); + $startDate = $piggyBank->start_date?->format('Y-m-d'); - $preFilled = [ + $preFilled = [ 'name' => $piggyBank->name, 'transaction_currency_id' => (int) $piggyBank->transaction_currency_id, 'target_amount' => Steam::bcround($piggyBank->target_amount, $piggyBank->transactionCurrency->decimal_places), @@ -93,7 +93,7 @@ class EditController extends Controller 'start_date' => $startDate, 'accounts' => [], 'object_group' => null !== $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '', - 'notes' => null === $note ? '' : $note->text + 'notes' => null === $note ? '' : $note->text, ]; foreach ($piggyBank->accounts as $account) { $preFilled['accounts'][] = $account->id; @@ -113,7 +113,7 @@ class EditController extends Controller 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'piggyBank' => $piggyBank, - 'preFilled' => $preFilled + 'preFilled' => $preFilled, ]); } @@ -130,7 +130,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($piggyBank, $files); } @@ -142,7 +142,7 @@ class EditController extends Controller if (count($this->attachments->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } - $redirect = redirect($this->getPreviousUrl('piggy-banks.edit.url')); + $redirect = redirect($this->getPreviousUrl('piggy-banks.edit.url')); if (1 === (int) $request->get('return_to_edit')) { session()->put('piggy-banks.edit.fromUpdate', true); diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php index 3e1164dd22..0c12201142 100644 --- a/app/Http/Controllers/PiggyBank/IndexController.php +++ b/app/Http/Controllers/PiggyBank/IndexController.php @@ -107,25 +107,25 @@ class IndexController extends Controller /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters(new ParameterBag()); - $piggyBanks = []; + $piggyBanks = []; // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $collection = $enrichment->enrich($collection); + $collection = $enrichment->enrich($collection); /** @var PiggyBank $piggy */ foreach ($collection as $piggy) { - $array = $transformer->transform($piggy); - $groupOrder = (int) $array['object_group_order']; + $array = $transformer->transform($piggy); + $groupOrder = (int) $array['object_group_order']; $piggyBanks[$groupOrder] ??= [ 'object_group_id' => $array['object_group_id'] ?? 0, 'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'), - 'piggy_banks' => [] + 'piggy_banks' => [], ]; - $array['attachments'] = $this->piggyRepos->getAttachments($piggy); + $array['attachments'] = $this->piggyRepos->getAttachments($piggy); // sum the total amount for the index. $piggyBanks[$groupOrder]['piggy_banks'][] = $array; @@ -137,10 +137,10 @@ class IndexController extends Controller private function collectAccounts(Collection $collection): array { /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); // transform piggies using the transformer: - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('end', $end); /** @var AccountTransformer $accountTransformer */ @@ -148,10 +148,10 @@ class IndexController extends Controller $accountTransformer->setParameters($parameters); // enrich each account. - $enrichment = new AccountEnrichment(); + $enrichment = new AccountEnrichment(); $enrichment->setUser(auth()->user()); $enrichment->setDate($end); - $return = []; + $return = []; /** @var PiggyBank $piggy */ foreach ($collection as $piggy) { @@ -164,12 +164,12 @@ class IndexController extends Controller $array = $accountTransformer->transform($account); $accountId = (int) $array['id']; if (!array_key_exists($accountId, $return)) { - $return[$accountId] = $array; + $return[$accountId] = $array; // add some interesting details: - $return[$accountId]['left'] = $return[$accountId]['current_balance']; - $return[$accountId]['saved'] = '0'; - $return[$accountId]['target'] = '0'; + $return[$accountId]['left'] = $return[$accountId]['current_balance']; + $return[$accountId]['saved'] = '0'; + $return[$accountId]['target'] = '0'; $return[$accountId]['to_save'] = '0'; } } @@ -189,9 +189,9 @@ class IndexController extends Controller foreach ($piggyBank['accounts'] as $piggyAccount) { $accountId = $piggyAccount['account_id']; if (array_key_exists($accountId, $accounts)) { - $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']); - $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']); - $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']); + $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']); + $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']); + $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']); $accounts[$accountId]['to_save'] = bcadd((string) $accounts[$accountId]['to_save'], bcsub( (string) $piggyBank['target_amount'], (string) $piggyAccount['current_amount'] @@ -210,7 +210,7 @@ class IndexController extends Controller foreach ($piggyBanks as $groupOrder => $group) { $groupId = $group['object_group_id']; foreach ($group['piggy_banks'] as $piggy) { - $currencyId = $piggy['currency_id']; + $currencyId = $piggy['currency_id']; $sums[$groupId][$currencyId] ??= [ 'target' => '0', 'saved' => '0', @@ -219,20 +219,20 @@ class IndexController extends Controller 'currency_id' => $currencyId, 'currency_code' => $piggy['currency_code'], 'currency_symbol' => $piggy['currency_symbol'], - 'currency_decimal_places' => $piggy['currency_decimal_places'] + 'currency_decimal_places' => $piggy['currency_decimal_places'], ]; // target_amount // current_amount // left_to_save // save_per_month - $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); - $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); - $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); + $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); + $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); + $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']); } } foreach ($piggyBanks as $groupOrder => $group) { - $groupId = $group['object_group_id']; + $groupId = $group['object_group_id']; $piggyBanks[$groupOrder]['sums'] = $sums[$groupId] ?? []; } diff --git a/app/Http/Controllers/PiggyBank/ShowController.php b/app/Http/Controllers/PiggyBank/ShowController.php index 1095eeb525..8d5d9aad37 100644 --- a/app/Http/Controllers/PiggyBank/ShowController.php +++ b/app/Http/Controllers/PiggyBank/ShowController.php @@ -70,19 +70,19 @@ class ShowController extends Controller public function show(PiggyBank $piggyBank): Factory|\Illuminate\Contracts\View\View { /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); // transform piggies using the transformer: - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('end', $end); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); /** @var PiggyBank $piggyBank */ - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); @@ -97,7 +97,7 @@ class ShowController extends Controller 'events' => $events, 'subTitle' => $subTitle, 'piggy' => $piggy, - 'attachments' => $attachments + 'attachments' => $attachments, ]); } } diff --git a/app/Http/Controllers/Popup/ReportController.php b/app/Http/Controllers/Popup/ReportController.php index 9a760ada5e..7cbaf063db 100644 --- a/app/Http/Controllers/Popup/ReportController.php +++ b/app/Http/Controllers/Popup/ReportController.php @@ -49,13 +49,13 @@ class ReportController extends Controller app('view')->share('start', $attributes['startDate']); app('view')->share('end', $attributes['endDate']); - $html = match ($attributes['location']) { - default => sprintf('Firefly III cannot handle "%s"-popups.', $attributes['location']), + $html = match ($attributes['location']) { + default => sprintf('Firefly III cannot handle "%s"-popups.', $attributes['location']), 'budget-spent-amount' => $this->budgetSpentAmount($attributes), - 'expense-entry' => $this->expenseEntry($attributes), - 'income-entry' => $this->incomeEntry($attributes), - 'category-entry' => $this->categoryEntry($attributes), - 'budget-entry' => $this->budgetEntry($attributes) + 'expense-entry' => $this->expenseEntry($attributes), + 'income-entry' => $this->incomeEntry($attributes), + 'category-entry' => $this->categoryEntry($attributes), + 'budget-entry' => $this->budgetEntry($attributes) }; return response()->json(['html' => $html]); diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index e10d306154..7866ccfb86 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -79,20 +79,20 @@ class PreferencesController extends Controller */ public function index(AccountRepositoryInterface $repository): Factory|\Illuminate\Contracts\View\View { - $accounts = $repository->getAccountsByType([ + $accounts = $repository->getAccountsByType([ AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); - $isDocker = env('IS_DOCKER', false); // @phpstan-ignore-line - $groupedAccounts = []; + $isDocker = env('IS_DOCKER', false); // @phpstan-ignore-line + $groupedAccounts = []; /** @var Account $account */ foreach ($accounts as $account) { - $type = $account->accountType->type; - $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); + $type = $account->accountType->type; + $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value], true)) { $role = sprintf('opt_group_l_%s', $type); @@ -106,48 +106,48 @@ class PreferencesController extends Controller ksort($groupedAccounts); /** @var array $accountIds */ - $accountIds = $accounts->pluck('id')->toArray(); - $viewRange = Navigation::getViewRange(false); - $frontpageAccountsPref = Preferences::get('frontpageAccounts', $accountIds); - $frontpageAccounts = $frontpageAccountsPref->data; + $accountIds = $accounts->pluck('id')->toArray(); + $viewRange = Navigation::getViewRange(false); + $frontpageAccountsPref = Preferences::get('frontpageAccounts', $accountIds); + $frontpageAccounts = $frontpageAccountsPref->data; if (!is_array($frontpageAccounts)) { $frontpageAccounts = $accountIds; } - $language = Steam::getLanguage(); - $languages = config('firefly.languages'); - $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; - $listPageSize = Preferences::get('listPageSize', 50)->data; - $darkMode = Preferences::get('darkMode', 'browser')->data; - $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; - $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; - $convertToPrimary = $this->convertToPrimary; + $language = Steam::getLanguage(); + $languages = config('firefly.languages'); + $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; + $listPageSize = Preferences::get('listPageSize', 50)->data; + $darkMode = Preferences::get('darkMode', 'browser')->data; + $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; + $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; + $convertToPrimary = $this->convertToPrimary; if (is_array($fiscalYearStartStr)) { $fiscalYearStartStr = '01-01'; } - $fiscalYearStart = sprintf('%s-%s', Carbon::now()->format('Y'), (string) $fiscalYearStartStr); - $tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; - $availableDarkModes = config('firefly.available_dark_modes'); + $fiscalYearStart = sprintf('%s-%s', Carbon::now()->format('Y'), (string) $fiscalYearStartStr); + $tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; + $availableDarkModes = config('firefly.available_dark_modes'); // notifications settings - $slackUrl = Preferences::getEncrypted('slack_webhook_url', '')->data; - $pushoverAppToken = (string) Preferences::getEncrypted('pushover_app_token', '')->data; - $pushoverUserToken = (string) Preferences::getEncrypted('pushover_user_token', '')->data; - $ntfyServer = Preferences::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $ntfyTopic = (string) Preferences::getEncrypted('ntfy_topic', '')->data; - $ntfyAuth = '1' === Preferences::get('ntfy_auth', false)->data; - $ntfyUser = Preferences::getEncrypted('ntfy_user', '')->data; - $ntfyPass = (string) Preferences::getEncrypted('ntfy_pass', '')->data; - $channels = config('notifications.channels'); - $forcedAvailability = []; - $anonymous = Steam::anonymous(); + $slackUrl = Preferences::getEncrypted('slack_webhook_url', '')->data; + $pushoverAppToken = (string) Preferences::getEncrypted('pushover_app_token', '')->data; + $pushoverUserToken = (string) Preferences::getEncrypted('pushover_user_token', '')->data; + $ntfyServer = Preferences::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; + $ntfyTopic = (string) Preferences::getEncrypted('ntfy_topic', '')->data; + $ntfyAuth = '1' === Preferences::get('ntfy_auth', false)->data; + $ntfyUser = Preferences::getEncrypted('ntfy_user', '')->data; + $ntfyPass = (string) Preferences::getEncrypted('ntfy_pass', '')->data; + $channels = config('notifications.channels'); + $forcedAvailability = []; + $anonymous = Steam::anonymous(); // notification preferences - $notifications = []; + $notifications = []; foreach (config('notifications.notifications.user') as $key => $info) { if (true === $info['enabled']) { $notifications[$key] = [ 'enabled' => true === Preferences::get(sprintf('notification_%s', $key), true)->data, - 'configurable' => $info['configurable'] + 'configurable' => $info['configurable'], ]; } } @@ -155,7 +155,7 @@ class PreferencesController extends Controller foreach ($channels as $channel => $info) { $forcedAvailability[$channel] = true; } - $forcedAvailability['ntfy'] = '' !== $ntfyTopic; + $forcedAvailability['ntfy'] = '' !== $ntfyTopic; $forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken; ksort($languages); @@ -168,7 +168,7 @@ class PreferencesController extends Controller Log::error($e->getMessage()); $locales = []; } - $locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales; + $locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales; // an important fallback is that the frontPageAccount array gets refilled automatically // when it turns up empty. if (0 === count($frontpageAccounts)) { @@ -215,7 +215,7 @@ class PreferencesController extends Controller 'viewRange' => $viewRange, 'customFiscalYear' => $customFiscalYear, 'listPageSize' => $listPageSize, - 'fiscalYearStart' => $fiscalYearStart + 'fiscalYearStart' => $fiscalYearStart, ]); } @@ -241,7 +241,7 @@ class PreferencesController extends Controller } // extract notifications: - $all = $request->all(); + $all = $request->all(); foreach (config('notifications.notifications.user') as $key => $info) { $key = sprintf('notification_%s', $key); if (array_key_exists($key, $all)) { @@ -277,7 +277,7 @@ class PreferencesController extends Controller } // convert primary - $convertToPrimary = 1 === (int) $request->get('convertToPrimary'); + $convertToPrimary = 1 === (int) $request->get('convertToPrimary'); if ($convertToPrimary && !$this->convertToPrimary) { // set to true! Log::debug('User sets convertToPrimary to true.'); @@ -289,9 +289,9 @@ class PreferencesController extends Controller Preferences::set('convert_to_primary', $convertToPrimary); // custom fiscal year - $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); + $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); Preferences::set('customFiscalYear', $customFiscalYear); - $fiscalYearString = (string) $request->get('fiscalYearStart'); + $fiscalYearString = (string) $request->get('fiscalYearStart'); if ('' !== $fiscalYearString) { $fiscalYearStart = Carbon::parse($fiscalYearString, config('app.timezone'))->format('m-d'); Preferences::set('fiscalYearStart', $fiscalYearStart); @@ -299,15 +299,15 @@ class PreferencesController extends Controller // save page size: Preferences::set('listPageSize', 50); - $listPageSize = (int) $request->get('listPageSize'); + $listPageSize = (int) $request->get('listPageSize'); if ($listPageSize > 0 && $listPageSize < 1337) { Preferences::set('listPageSize', $listPageSize); } // language: /** @var Preference $currentLang */ - $currentLang = Preferences::get('language', 'en_US'); - $lang = $request->get('language'); + $currentLang = Preferences::get('language', 'en_US'); + $lang = $request->get('language'); if (array_key_exists($lang, config('firefly.languages'))) { Preferences::set('language', $lang); } @@ -324,8 +324,8 @@ class PreferencesController extends Controller } // optional fields for transactions: - $setOptions = $request->get('tj') ?? []; - $optionalTj = [ + $setOptions = $request->get('tj') ?? []; + $optionalTj = [ 'interest_date' => array_key_exists('interest_date', $setOptions), 'book_date' => array_key_exists('book_date', $setOptions), 'process_date' => array_key_exists('process_date', $setOptions), @@ -337,18 +337,18 @@ class PreferencesController extends Controller 'attachments' => array_key_exists('attachments', $setOptions), 'external_url' => array_key_exists('external_url', $setOptions), 'location' => array_key_exists('location', $setOptions), - 'links' => array_key_exists('links', $setOptions) + 'links' => array_key_exists('links', $setOptions), ]; Preferences::set('transaction_journal_optional_fields', $optionalTj); // dark mode - $darkMode = $request->get('darkMode') ?? 'browser'; + $darkMode = $request->get('darkMode') ?? 'browser'; if (in_array($darkMode, config('firefly.available_dark_modes'), true)) { Preferences::set('darkMode', $darkMode); } // anonymous amounts? - $anonymous = '1' === $request->get('anonymous'); + $anonymous = '1' === $request->get('anonymous'); Preferences::set('anonymous', $anonymous); // save and continue diff --git a/app/Http/Controllers/Profile/MfaController.php b/app/Http/Controllers/Profile/MfaController.php index 6250612398..b5a71e0adc 100644 --- a/app/Http/Controllers/Profile/MfaController.php +++ b/app/Http/Controllers/Profile/MfaController.php @@ -75,7 +75,7 @@ class MfaController extends Controller return $next($request); }); - $authGuard = config('firefly.authentication_guard'); + $authGuard = config('firefly.authentication_guard'); $this->internalAuth = 'web' === $authGuard; Log::debug(sprintf('ProfileController::__construct(). Authentication guard is "%s"', $authGuard)); @@ -106,7 +106,7 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $enabledMFA = null !== auth()->user()->mfa_secret; + $enabledMFA = null !== auth()->user()->mfa_secret; if (false === $enabledMFA) { request()->session()->flash('info', trans('firefly.mfa_not_enabled')); @@ -121,7 +121,7 @@ class MfaController extends Controller Preferences::mark(); // send user notification. - $user = auth()->user(); + $user = auth()->user(); Log::channel('audit')->info(sprintf('User "%s" has generated new backup codes.', $user->email)); event(new UserHasGeneratedNewBackupCodes($user)); @@ -135,7 +135,7 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $enabledMFA = null !== auth()->user()->mfa_secret; + $enabledMFA = null !== auth()->user()->mfa_secret; if (false === $enabledMFA) { request()->session()->flash('info', trans('firefly.mfa_already_disabled')); @@ -162,7 +162,7 @@ class MfaController extends Controller $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Preferences::delete('temp-mfa-secret'); Preferences::delete('temp-mfa-codes'); @@ -206,9 +206,9 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $domain = $this->getDomain(); - $secret = Google2FA::generateSecretKey(); - $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret); + $domain = $this->getDomain(); + $secret = Google2FA::generateSecretKey(); + $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret); Preferences::set('temp-mfa-secret', $secret); @@ -230,10 +230,10 @@ class MfaController extends Controller } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // verify password. - $password = $request->get('password'); + $password = $request->get('password'); if (!auth()->validate(['email' => $user->email, 'password' => $password])) { session()->flash('error', 'Bad user pw, no MFA for you!'); @@ -246,7 +246,7 @@ class MfaController extends Controller if (is_array($secret)) { $secret = null; } - $secret = (string) $secret; + $secret = (string) $secret; $repository->setMFACode($user, $secret); @@ -256,7 +256,7 @@ class MfaController extends Controller Preferences::mark(); // also save the code so replay attack is prevented. - $mfaCode = $request->get('code'); + $mfaCode = $request->get('code'); $this->addToMFAHistory($mfaCode); // make sure MFA is logged out. @@ -283,8 +283,8 @@ class MfaController extends Controller private function addToMFAHistory(string $mfaCode): void { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; + $mfaHistory = Preferences::get('mfa_history', [])->data; + $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; $mfaHistory[] = $entry; Preferences::set('mfa_history', $mfaHistory); diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index 8a5a812b70..9bea42d046 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -78,7 +78,7 @@ class ProfileController extends Controller return $next($request); }); - $authGuard = config('firefly.authentication_guard'); + $authGuard = config('firefly.authentication_guard'); $this->internalAuth = 'web' === $authGuard; Log::debug(sprintf('ProfileController::__construct(). Authentication guard is "%s"', $authGuard)); @@ -152,7 +152,8 @@ class ProfileController extends Controller $count = DB::table('oauth_clients') ->where('personal_access_client', true) ->whereNull('user_id') - ->count(); + ->count() + ; $subTitle = $user->email; $userId = $user->id; $enabled2FA = null !== $user->mfa_secret; @@ -170,7 +171,7 @@ class ProfileController extends Controller $repository->createPersonalAccessClient(null, $name, 'http://localhost'); } - $accessToken = Preferences::get('access_token'); + $accessToken = Preferences::get('access_token'); if (null === $accessToken) { $token = $user->generateAccessToken(); $accessToken = Preferences::set('access_token', $token); @@ -182,7 +183,7 @@ class ProfileController extends Controller 'userId' => $userId, 'accessToken' => $accessToken, 'enabled2FA' => $enabled2FA, - 'isInternalAuth' => $isInternalAuth + 'isInternalAuth' => $isInternalAuth, ]); } @@ -276,7 +277,7 @@ class ProfileController extends Controller $new = $request->get('new_password'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); try { $this->validatePassword($user, $current, $new); @@ -398,8 +399,8 @@ class ProfileController extends Controller } // find preference with this token value. - $set = Preferences::findByName('email_change_undo_token'); - $user = null; + $set = Preferences::findByName('email_change_undo_token'); + $user = null; /** @var Preference $preference */ foreach ($set as $preference) { @@ -412,7 +413,7 @@ class ProfileController extends Controller } // found user.which email address to return to? - $set = Preferences::beginsWith($user, 'previous_email_'); + $set = Preferences::beginsWith($user, 'previous_email_'); /** @var null|string $match */ $match = null; diff --git a/app/Http/Controllers/Recurring/CreateController.php b/app/Http/Controllers/Recurring/CreateController.php index 6a9b58c527..eebc80e5ed 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -65,9 +65,9 @@ class CreateController extends Controller app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('subTitle', (string) trans('firefly.create_new_recurrence')); - $this->repository = app(RecurringRepositoryInterface::class); - $this->budgetRepos = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); + $this->budgetRepos = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); $this->billRepository = app(BillRepositoryInterface::class); return $next($request); @@ -92,23 +92,23 @@ class CreateController extends Controller $this->rememberPreviousUrl('recurring.create.url'); } $request->session()->forget('recurring.create.fromStore'); - $repetitionEnds = [ + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times') + 'times' => (string) trans('firefly.repeat_times'), ]; - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), ]; - $hasOldInput = null !== $request->old('_token'); // flash some data - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); // flash some data + $preFilled = [ 'first_date' => $tomorrow->format('Y-m-d'), 'transaction_type' => $hasOldInput ? $request->old('transaction_type') : 'withdrawal', 'active' => $hasOldInput ? (bool) $request->old('active') : true, - 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true + 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true, ]; $request->session()->flash('preFilled', $preFilled); @@ -119,7 +119,7 @@ class CreateController extends Controller 'weekendResponses' => $weekendResponses, 'preFilled' => $preFilled, 'repetitionEnds' => $repetitionEnds, - 'budgets' => $budgets + 'budgets' => $budgets, ]); } @@ -139,31 +139,31 @@ class CreateController extends Controller $this->rememberPreviousUrl('recurring.create.url'); } $request->session()->forget('recurring.create.fromStore'); - $repetitionEnds = [ + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times') + 'times' => (string) trans('firefly.repeat_times'), ]; - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), ]; // fill prefilled with journal info - $type = strtolower((string) $journal->transactionType->type); + $type = strtolower((string) $journal->transactionType->type); /** @var Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); /** @var Transaction $dest */ - $dest = $journal->transactions()->where('amount', '>', 0)->first(); - $category = null !== $journal->categories()->first() ? $journal->categories()->first()->name : ''; - $budget = null !== $journal->budgets()->first() ? $journal->budgets()->first()->id : 0; - $bill = null !== $journal->bill ? $journal->bill->id : 0; - $hasOldInput = null !== $request->old('_token'); // flash some data - $preFilled = []; + $dest = $journal->transactions()->where('amount', '>', 0)->first(); + $category = null !== $journal->categories()->first() ? $journal->categories()->first()->name : ''; + $budget = null !== $journal->budgets()->first() ? $journal->budgets()->first()->id : 0; + $bill = null !== $journal->bill ? $journal->bill->id : 0; + $hasOldInput = null !== $request->old('_token'); // flash some data + $preFilled = []; if ($hasOldInput) { $preFilled = [ 'title' => $request->old('title'), @@ -182,7 +182,7 @@ class CreateController extends Controller 'budget_id' => $request->old('budget_id'), 'bill_id' => $request->old('bill_id'), 'active' => (bool) $request->old('active'), - 'apply_rules' => (bool) $request->old('apply_rules') + 'apply_rules' => (bool) $request->old('apply_rules'), ]; } if (false === $hasOldInput) { @@ -203,7 +203,7 @@ class CreateController extends Controller 'budget_id' => $budget, 'bill_id' => $bill, 'active' => true, - 'apply_rules' => true + 'apply_rules' => true, ]; } $request->session()->flash('preFilled', $preFilled); @@ -215,7 +215,7 @@ class CreateController extends Controller 'weekendResponses' => $weekendResponses, 'preFilled' => $preFilled, 'repetitionEnds' => $repetitionEnds, - 'budgets' => $budgets + 'budgets' => $budgets, ]); } @@ -228,7 +228,7 @@ class CreateController extends Controller */ public function store(RecurrenceFormRequest $request) { - $data = $request->getAll(); + $data = $request->getAll(); try { $recurrence = $this->repository->store($data); @@ -244,7 +244,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($recurrence, $files); } diff --git a/app/Http/Controllers/Recurring/DeleteController.php b/app/Http/Controllers/Recurring/DeleteController.php index 92fa26bb6d..82de7747eb 100644 --- a/app/Http/Controllers/Recurring/DeleteController.php +++ b/app/Http/Controllers/Recurring/DeleteController.php @@ -66,7 +66,7 @@ class DeleteController extends Controller */ public function delete(Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); + $subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); // put previous url in session $this->rememberPreviousUrl('recurrences.delete.url'); diff --git a/app/Http/Controllers/Recurring/EditController.php b/app/Http/Controllers/Recurring/EditController.php index bfe5b26196..42be36daea 100644 --- a/app/Http/Controllers/Recurring/EditController.php +++ b/app/Http/Controllers/Recurring/EditController.php @@ -69,9 +69,9 @@ class EditController extends Controller app('view')->share('title', (string) trans('firefly.recurrences')); app('view')->share('subTitle', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); - $this->budgetRepos = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); + $this->budgetRepos = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); $this->billRepository = app(BillRepositoryInterface::class); return $next($request); @@ -88,29 +88,29 @@ class EditController extends Controller public function edit(Request $request, Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { // TODO this should be in the repository. - $count = $recurrence->recurrenceTransactions()->count(); + $count = $recurrence->recurrenceTransactions()->count(); if (0 === $count) { throw new FireflyException('This recurring transaction has no meta-data. You will have to delete it and recreate it. Sorry!'); } // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); /** @var Recurrence $recurrence */ - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); - $array = $transformer->transform($recurrence); - $budgets = ExpandedForm::makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); - $bills = ExpandedForm::makeSelectListWithEmpty($this->billRepository->getActiveBills()); + $transformer = app(RecurrenceTransformer::class); + $array = $transformer->transform($recurrence); + $budgets = ExpandedForm::makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); + $bills = ExpandedForm::makeSelectListWithEmpty($this->billRepository->getActiveBills()); /** @var RecurrenceRepetition $repetition */ - $repetition = $recurrence->recurrenceRepetitions()->first(); - $currentRepType = $repetition->repetition_type; + $repetition = $recurrence->recurrenceRepetitions()->first(); + $currentRepType = $repetition->repetition_type; if ('' !== $repetition->repetition_moment) { $currentRepType = sprintf('%s,%s', $currentRepType, $repetition->repetition_moment); } @@ -121,11 +121,11 @@ class EditController extends Controller } $request->session()->forget('recurrences.edit.fromUpdate'); - $repetitionEnd = 'forever'; - $repetitionEnds = [ + $repetitionEnd = 'forever'; + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times') + 'times' => (string) trans('firefly.repeat_times'), ]; if (null !== $recurrence->repeat_until) { $repetitionEnd = 'until_date'; @@ -134,24 +134,24 @@ class EditController extends Controller $repetitionEnd = 'times'; } - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), ]; - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'transaction_type' => strtolower((string) $recurrence->transactionType->type), 'active' => $hasOldInput ? (bool) $request->old('active') : $recurrence->active, 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : $recurrence->apply_rules, 'deposit_source_id' => $array['transactions'][0]['source_id'], - 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'] + 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'], ]; - $array['first_date'] = substr((string) $array['first_date'], 0, 10); - $array['repeat_until'] = substr((string) $array['repeat_until'], 0, 10); - $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); + $array['first_date'] = substr((string) $array['first_date'], 0, 10); + $array['repeat_until'] = substr((string) $array['repeat_until'], 0, 10); + $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); $array['transactions'][0]['amount'] = round((float) $array['transactions'][0]['amount'], $array['transactions'][0]['currency_decimal_places']); if (null !== $array['transactions'][0]['foreign_amount'] && '' !== $array['transactions'][0]['foreign_amount']) { $array['transactions'][0]['foreign_amount'] = round( @@ -169,7 +169,7 @@ class EditController extends Controller 'preFilled' => $preFilled, 'currentRepType' => $currentRepType, 'repetitionEnd' => $repetitionEnd, - 'repetitionEnds' => $repetitionEnds + 'repetitionEnds' => $repetitionEnds, ]); } @@ -190,7 +190,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($recurrence, $files); } @@ -203,7 +203,7 @@ class EditController extends Controller $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('recurrences.edit.url')); + $redirect = redirect($this->getPreviousUrl('recurrences.edit.url')); if (1 === (int) $request->get('return_to_edit')) { // set value so edit routine will not overwrite URL: $request->session()->put('recurrences.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Recurring/IndexController.php b/app/Http/Controllers/Recurring/IndexController.php index 754a13fd28..97583403b4 100644 --- a/app/Http/Controllers/Recurring/IndexController.php +++ b/app/Http/Controllers/Recurring/IndexController.php @@ -80,11 +80,11 @@ class IndexController extends Controller */ public function index(Request $request): Factory|\Illuminate\Contracts\View\View { - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $collection = $this->repository->get(); - $today = today(config('app.timezone')); - $year = today(config('app.timezone')); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $collection = $this->repository->get(); + $today = today(config('app.timezone')); + $year = today(config('app.timezone')); // split collection $total = $collection->count(); @@ -92,8 +92,8 @@ class IndexController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); $recurrences = $enrichment->enrich($recurrences); @@ -101,7 +101,7 @@ class IndexController extends Controller $transformer = app(RecurrenceTransformer::class); $transformer->setParameters(new ParameterBag()); - $recurring = []; + $recurring = []; /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { @@ -111,12 +111,12 @@ class IndexController extends Controller $year = clone $today; $year->addYear(); } - $array = $transformer->transform($recurrence); - $array['first_date'] = new Carbon($array['first_date']); + $array = $transformer->transform($recurrence); + $array['first_date'] = new Carbon($array['first_date']); $array['repeat_until'] = null === $array['repeat_until'] ? null : new Carbon($array['repeat_until']); - $array['latest_date'] = null === $array['latest_date'] ? null : new Carbon($array['latest_date']); + $array['latest_date'] = null === $array['latest_date'] ? null : new Carbon($array['latest_date']); // lazy but OK - $array['attachments'] = $recurrence->attachments()->count(); + $array['attachments'] = $recurrence->attachments()->count(); // make carbon objects out of occurrences foreach ($array['repetitions'] as $repIndex => $repetition) { @@ -125,11 +125,11 @@ class IndexController extends Controller } } - $recurring[] = $array; + $recurring[] = $array; } - $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); + $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); $paginator->setPath(route('recurring.index')); - $today = today(config('app.timezone')); + $today = today(config('app.timezone')); $this->verifyRecurringCronJob(); @@ -138,7 +138,7 @@ class IndexController extends Controller 'today' => $today, 'page' => $page, 'pageSize' => $pageSize, - 'total' => $total + 'total' => $total, ]); } } diff --git a/app/Http/Controllers/Recurring/ShowController.php b/app/Http/Controllers/Recurring/ShowController.php index 9ef2f28011..55940add74 100644 --- a/app/Http/Controllers/Recurring/ShowController.php +++ b/app/Http/Controllers/Recurring/ShowController.php @@ -77,49 +77,49 @@ class ShowController extends Controller */ public function show(Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { - $repos = app(AttachmentRepositoryInterface::class); + $repos = app(AttachmentRepositoryInterface::class); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); /** @var Recurrence $recurrence */ - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); + $transformer = app(RecurrenceTransformer::class); $transformer->setParameters(new ParameterBag()); - $array = $transformer->transform($recurrence); + $array = $transformer->transform($recurrence); - $groups = $this->repository->getTransactions($recurrence); - $today = today(config('app.timezone')); - $array['repeat_until'] = null !== $array['repeat_until'] ? new Carbon($array['repeat_until']) : null; + $groups = $this->repository->getTransactions($recurrence); + $today = today(config('app.timezone')); + $array['repeat_until'] = null !== $array['repeat_until'] ? new Carbon($array['repeat_until']) : null; $array['journal_count'] = $this->repository->getJournalCount($recurrence); // transform dates back to Carbon objects and expand information foreach ($array['repetitions'] as $index => $repetition) { foreach ($repetition['occurrences'] as $item => $occurrence) { - $date = new Carbon($occurrence)->startOfDay(); - $set = [ + $date = new Carbon($occurrence)->startOfDay(); + $set = [ 'date' => $date, - 'fired' => $this->repository->createdPreviously($recurrence, $date) || $this->repository->getJournalCount($recurrence, $date) > 0 + 'fired' => $this->repository->createdPreviously($recurrence, $date) || $this->repository->getJournalCount($recurrence, $date) > 0, ]; $array['repetitions'][$index]['occurrences'][$item] = $set; } } // add attachments to the recurrence object. - $attachments = $recurrence->attachments()->get(); - $array['attachments'] = []; - $attachmentTransformer = app(AttachmentTransformer::class); + $attachments = $recurrence->attachments()->get(); + $array['attachments'] = []; + $attachmentTransformer = app(AttachmentTransformer::class); /** @var Attachment $attachment */ foreach ($attachments as $attachment) { - $item = $attachmentTransformer->transform($attachment); - $item['file_exists'] = $repos->exists($attachment); // TODO this should be part of the transformer + $item = $attachmentTransformer->transform($attachment); + $item['file_exists'] = $repos->exists($attachment); // TODO this should be part of the transformer $array['attachments'][] = $item; } @@ -132,14 +132,14 @@ class ShowController extends Controller } } - $subTitle = (string) trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]); + $subTitle = (string) trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]); return view('recurring.show', [ 'recurrence' => $recurrence, 'subTitle' => $subTitle, 'array' => $array, 'groups' => $groups, - 'today' => $today + 'today' => $today, ]); } } diff --git a/app/Http/Controllers/Recurring/TriggerController.php b/app/Http/Controllers/Recurring/TriggerController.php index e9e305e344..15f3f60b87 100644 --- a/app/Http/Controllers/Recurring/TriggerController.php +++ b/app/Http/Controllers/Recurring/TriggerController.php @@ -62,26 +62,26 @@ class TriggerController extends Controller public function trigger(Recurrence $recurrence, TriggerRecurrenceRequest $request): RedirectResponse { - $all = $request->getAll(); - $date = $all['date']; + $all = $request->getAll(); + $date = $all['date']; // grab the date from the last time the recurrence fired: - $backupDate = $recurrence->latest_date; + $backupDate = $recurrence->latest_date; // fire the recurring cron job on the given date, then post-date the created transaction. Log::info(sprintf('Trigger: will now fire recurring cron job task for date "%s".', $date->format('Y-m-d H:i:s'))); /** @var CreateRecurringTransactions $job */ - $job = app(CreateRecurringTransactions::class); + $job = app(CreateRecurringTransactions::class); $job->setRecurrences(new Collection()->push($recurrence)); $job->setDate($date); $job->setForce(false); $job->handle(); Log::debug('Done with recurrence.'); - $groups = $job->getGroups(); + $groups = $job->getGroups(); $this->repository->markGroupsAsNow($groups); - $recurrence->latest_date = $backupDate; + $recurrence->latest_date = $backupDate; $recurrence->latest_date_tz = $backupDate?->format('e'); $recurrence->save(); Preferences::mark(); diff --git a/app/Http/Controllers/Report/AccountController.php b/app/Http/Controllers/Report/AccountController.php index a76016825b..d276a6eca2 100644 --- a/app/Http/Controllers/Report/AccountController.php +++ b/app/Http/Controllers/Report/AccountController.php @@ -45,7 +45,7 @@ class AccountController extends Controller public function general(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('account-report'); diff --git a/app/Http/Controllers/Report/BalanceController.php b/app/Http/Controllers/Report/BalanceController.php index 82cab48db8..7c15c74252 100644 --- a/app/Http/Controllers/Report/BalanceController.php +++ b/app/Http/Controllers/Report/BalanceController.php @@ -66,7 +66,7 @@ class BalanceController extends Controller */ public function general(Collection $accounts, Carbon $start, Carbon $end) { - $report = ['budgets' => [], 'accounts' => []]; + $report = ['budgets' => [], 'accounts' => []]; /** @var Account $account */ foreach ($accounts as $account) { @@ -77,38 +77,39 @@ class BalanceController extends Controller /** @var Budget $budget */ foreach ($budgets as $budget) { - $budgetId = $budget->id; - $report['budgets'][$budgetId] = [ + $budgetId = $budget->id; + $report['budgets'][$budgetId] = [ 'budget_id' => $budgetId, 'budget_name' => $budget->name, 'spent' => [], // per account - 'sums' => [] // per currency + 'sums' => [], // per currency ]; - $spent = []; + $spent = []; /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $journals = $collector + $collector = app(GroupCollectorInterface::class); + $journals = $collector ->setRange($start, $end) ->setSourceAccounts($accounts) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->setBudget($budget) - ->getExtractedJournals(); + ->getExtractedJournals() + ; /** @var array $journal */ foreach ($journals as $journal) { - $sourceAccount = $journal['source_account_id']; - $currencyId = $journal['currency_id']; - $spent[$sourceAccount] ??= [ + $sourceAccount = $journal['source_account_id']; + $currencyId = $journal['currency_id']; + $spent[$sourceAccount] ??= [ 'source_account_id' => $sourceAccount, 'currency_id' => $journal['currency_id'], 'currency_code' => $journal['currency_code'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'spent' => '0' + 'spent' => '0', ]; - $spent[$sourceAccount]['spent'] = bcadd($spent[$sourceAccount]['spent'], (string) $journal['amount']); + $spent[$sourceAccount]['spent'] = bcadd($spent[$sourceAccount]['spent'], (string) $journal['amount']); // also fix sum: $report['sums'][$budgetId][$currencyId] ??= [ @@ -117,16 +118,16 @@ class BalanceController extends Controller 'currency_code' => $journal['currency_code'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; - $report['sums'][$budgetId][$currencyId]['sum'] = bcadd($report['sums'][$budgetId][$currencyId]['sum'], (string) $journal['amount']); - $report['accounts'][$sourceAccount]['sum'] = bcadd($report['accounts'][$sourceAccount]['sum'], (string) $journal['amount']); + $report['sums'][$budgetId][$currencyId]['sum'] = bcadd($report['sums'][$budgetId][$currencyId]['sum'], (string) $journal['amount']); + $report['accounts'][$sourceAccount]['sum'] = bcadd($report['accounts'][$sourceAccount]['sum'], (string) $journal['amount']); // add currency info for account sum - $report['accounts'][$sourceAccount]['currency_id'] = $journal['currency_id']; - $report['accounts'][$sourceAccount]['currency_code'] = $journal['currency_code']; - $report['accounts'][$sourceAccount]['currency_name'] = $journal['currency_name']; - $report['accounts'][$sourceAccount]['currency_symbol'] = $journal['currency_symbol']; + $report['accounts'][$sourceAccount]['currency_id'] = $journal['currency_id']; + $report['accounts'][$sourceAccount]['currency_code'] = $journal['currency_code']; + $report['accounts'][$sourceAccount]['currency_name'] = $journal['currency_name']; + $report['accounts'][$sourceAccount]['currency_symbol'] = $journal['currency_symbol']; $report['accounts'][$sourceAccount]['currency_decimal_places'] = $journal['currency_decimal_places']; } $report['budgets'][$budgetId]['spent'] = $spent; diff --git a/app/Http/Controllers/Report/BillController.php b/app/Http/Controllers/Report/BillController.php index b4911f7fc0..b27c816a56 100644 --- a/app/Http/Controllers/Report/BillController.php +++ b/app/Http/Controllers/Report/BillController.php @@ -45,7 +45,7 @@ class BillController extends Controller */ public function overview(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('bill-report'); diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index ca7c63219e..855a531612 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -80,7 +80,7 @@ class BudgetController extends Controller $generator->setEnd($end); $generator->accountPerBudget(); - $report = $generator->getReport(); + $report = $generator->getReport(); return view('reports.budget.partials.account-per-budget', ['report' => $report, 'budgets' => $budgets]); } @@ -108,23 +108,23 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } } @@ -139,13 +139,13 @@ class BudgetController extends Controller */ public function avgExpenses(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); + $result = []; foreach ($spent as $currency) { foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -156,11 +156,11 @@ class BudgetController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; // intentional float } } @@ -204,7 +204,7 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; /** @var array $budget */ @@ -219,13 +219,13 @@ class BudgetController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$budgetId]['currencies'][$currencyId]['sum'] = bcadd( $report[$budgetId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } } @@ -233,9 +233,9 @@ class BudgetController extends Controller // loop again to get percentages. foreach ($report as $budgetId => $data) { foreach ($data['currencies'] as $currencyId => $dataX) { - $sum = $dataX['sum']; - $total = $sums[$currencyId]['sum'] ?? '0'; - $pct = '0'; + $sum = $dataX['sum']; + $total = $sums[$currencyId]['sum'] ?? '0'; + $pct = '0'; if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) { $pct = round((float) bcmul(bcdiv($sum, $total), '100')); // intentional float } @@ -264,7 +264,7 @@ class BudgetController extends Controller $generator->setEnd($end); $generator->general(); - $report = $generator->getReport(); + $report = $generator->getReport(); return view('reports.partials.budgets', ['report' => $report])->render(); } @@ -278,7 +278,7 @@ class BudgetController extends Controller */ public function period(Collection $accounts, Carbon $start, Carbon $end) { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('budget-period-report'); @@ -291,9 +291,9 @@ class BudgetController extends Controller $keyFormat = Navigation::preferredCarbonFormat($start, $end); // list expenses for budgets in account(s) - $expenses = $this->opsRepository->listExpenses($start, $end, $accounts); + $expenses = $this->opsRepository->listExpenses($start, $end, $accounts); - $report = []; + $report = []; foreach ($expenses as $currency) { foreach ($currency['budgets'] as $budget) { $count = 0; @@ -308,9 +308,9 @@ class BudgetController extends Controller } ++$count; - $key = sprintf('%d-%d', $budget['id'], $currency['currency_id']); - $dateKey = $journal['date']->format($keyFormat); - $report[$key] ??= [ + $key = sprintf('%d-%d', $budget['id'], $currency['currency_id']); + $dateKey = $journal['date']->format($keyFormat); + $report[$key] ??= [ 'id' => $budget['id'], 'name' => sprintf('%s (%s)', $budget['name'], $currency['currency_name']), 'sum' => '0', @@ -319,12 +319,12 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'entries' => [] + 'entries' => [], ]; $report[$key]['entries'][$dateKey] ??= '0'; $report[$key]['entries'][$dateKey] = bcadd((string) $journal['amount'], $report[$key]['entries'][$dateKey]); - $report[$key]['sum'] = bcadd($report[$key]['sum'], (string) $journal['amount']); - $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) count($periods)); + $report[$key]['sum'] = bcadd($report[$key]['sum'], (string) $journal['amount']); + $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) count($periods)); } } } @@ -351,15 +351,15 @@ class BudgetController extends Controller */ public function topExpenses(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); + $result = []; foreach ($spent as $currency) { foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { $result[] = [ - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float) $journal['amount'], // intentional float + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + 'amount_float' => (float) $journal['amount'], // intentional float 'amount' => $journal['amount'], 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), @@ -370,7 +370,7 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'budget_id' => $budget['id'], - 'budget_name' => $budget['name'] + 'budget_name' => $budget['name'], ]; } } diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index fd85b063f9..f61fa0ed36 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -57,7 +57,7 @@ class CategoryController extends Controller { parent::__construct(); $this->middleware(function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); $this->noCatRepository = app(NoCategoryRepositoryInterface::class); return $next($request); @@ -86,13 +86,13 @@ class CategoryController extends Controller /** @var array $category */ foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; - $report[$sourceAccountId]['currencies'][$currencyId] ??= [ + $sourceAccountId = $journal['source_account_id']; + $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'categories' => [] + 'categories' => [], ]; $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; @@ -100,7 +100,7 @@ class CategoryController extends Controller $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], (string) $journal['amount'] ); @@ -114,20 +114,20 @@ class CategoryController extends Controller /** @var array $category */ foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $report[$destinationId]['currencies'][$currencyId] ??= [ + $destinationId = $journal['destination_account_id']; + $report[$destinationId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'categories' => [] + 'categories' => [], ]; $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'], (string) $journal['amount'] ); - $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( + $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], (string) $journal['amount'] ); @@ -166,11 +166,11 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -178,18 +178,18 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -204,11 +204,11 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationAccountId = $journal['destination_account_id']; + $destinationAccountId = $journal['destination_account_id']; $report[$destinationAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -216,18 +216,18 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -242,13 +242,13 @@ class CategoryController extends Controller */ public function avgExpenses(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -259,11 +259,11 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; // intentional float } } @@ -292,13 +292,13 @@ class CategoryController extends Controller */ public function avgIncome(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -309,11 +309,11 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -361,7 +361,7 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; /** @var array $category */ @@ -377,19 +377,19 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$categoryId]['currencies'][$currencyId]['spent'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -403,7 +403,7 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; /** @var array $category */ @@ -419,19 +419,19 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$categoryId]['currencies'][$currencyId]['earned'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -448,7 +448,7 @@ class CategoryController extends Controller */ public function expenses(Collection $accounts, Carbon $start, Carbon $end) { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-period-expenses-report'); @@ -459,7 +459,7 @@ class CategoryController extends Controller // depending on the carbon format (a reliable way to determine the general date difference) // change the "listOfPeriods" call so the entire period gets included correctly. - $format = Navigation::preferredCarbonFormat($start, $end); + $format = Navigation::preferredCarbonFormat($start, $end); if ('Y' === $format) { $start->startOfYear(); @@ -485,13 +485,13 @@ class CategoryController extends Controller 'currency_code' => $currencyRow['currency_code'], 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'sum' => '0', - 'entries' => [] + 'entries' => [], ]; foreach ($categoryRow['transaction_journals'] as $journal) { - $date = $journal['date']->format($format); + $date = $journal['date']->format($format); $data[$key]['entries'][$date] ??= '0'; $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], (string) $journal['amount']); - $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); + $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); } } } @@ -499,7 +499,7 @@ class CategoryController extends Controller $cache->store($data); - $report = $data; + $report = $data; try { $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); @@ -522,7 +522,7 @@ class CategoryController extends Controller */ public function income(Collection $accounts, Carbon $start, Carbon $end): string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-period-income-report'); @@ -533,7 +533,7 @@ class CategoryController extends Controller // depending on the carbon format (a reliable way to determine the general date difference) // change the "listOfPeriods" call so the entire period gets included correctly. - $format = Navigation::preferredCarbonFormat($start, $end); + $format = Navigation::preferredCarbonFormat($start, $end); if ('Y' === $format) { $start->startOfYear(); @@ -559,19 +559,19 @@ class CategoryController extends Controller 'currency_code' => $currencyRow['currency_code'], 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'sum' => '0', - 'entries' => [] + 'entries' => [], ]; foreach ($categoryRow['transaction_journals'] as $journal) { - $date = $journal['date']->format($format); + $date = $journal['date']->format($format); $data[$key]['entries'][$date] ??= '0'; $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], (string) $journal['amount']); - $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); + $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); } } } } - $report = $data; + $report = $data; try { $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); @@ -595,7 +595,7 @@ class CategoryController extends Controller public function operations(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-report'); @@ -610,7 +610,7 @@ class CategoryController extends Controller $generator->setStart($start); $generator->setEnd($end); $generator->operations(); - $report = $generator->getReport(); + $report = $generator->getReport(); try { $result = view('reports.partials.categories', ['report' => $report])->render(); @@ -632,8 +632,8 @@ class CategoryController extends Controller */ public function topExpenses(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { @@ -651,7 +651,7 @@ class CategoryController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'category_id' => $category['id'], - 'category_name' => $category['name'] + 'category_name' => $category['name'], ]; } } @@ -680,8 +680,8 @@ class CategoryController extends Controller */ public function topIncome(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { @@ -699,7 +699,7 @@ class CategoryController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'category_id' => $category['id'], - 'category_name' => $category['name'] + 'category_name' => $category['name'], ]; } } diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php index 2ed0dab55b..073f7fb41b 100644 --- a/app/Http/Controllers/Report/DoubleController.php +++ b/app/Http/Controllers/Report/DoubleController.php @@ -56,7 +56,7 @@ class DoubleController extends Controller // translations: $this->middleware(function ($request, $next) { $this->accountRepository = app(AccountRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); return $next($request); }); @@ -75,8 +75,8 @@ class DoubleController extends Controller $result = []; foreach ($spent as $currency) { foreach ($currency['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -87,17 +87,17 @@ class DoubleController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'avg_float'); + $amounts = array_column($result, 'avg_float'); array_multisort($amounts, SORT_ASC, $result); try { @@ -125,8 +125,8 @@ class DoubleController extends Controller $result = []; foreach ($spent as $currency) { foreach ($currency['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -137,17 +137,17 @@ class DoubleController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'avg_float'); + $amounts = array_column($result, 'avg_float'); array_multisort($amounts, SORT_DESC, $result); try { @@ -174,8 +174,8 @@ class DoubleController extends Controller $report = []; $sums = []; // see what happens when we collect transactions. - $spent = $this->opsRepository->listExpenses($start, $end, $together); - $earned = $this->opsRepository->listIncome($start, $end, $together); + $spent = $this->opsRepository->listExpenses($start, $end, $together); + $earned = $this->opsRepository->listIncome($start, $end, $together); // group and list per account name (as long as its not in accounts, only in double) /** @var array $currency */ @@ -190,16 +190,16 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $destId = $journal['destination_account_id']; - $destName = $journal['destination_account_name']; - $destIban = $journal['destination_account_iban']; - $genericName = $this->getCounterpartName($withCounterpart, $destId, $destName, $destIban); - $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); + $destId = $journal['destination_account_id']; + $destName = $journal['destination_account_name']; + $destIban = $journal['destination_account_iban']; + $genericName = $this->getCounterpartName($withCounterpart, $destId, $destName, $destIban); + $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); $report[$objectName] ??= [ 'dest_name' => '', 'dest_iban' => '', @@ -212,17 +212,17 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; // set name $report[$objectName]['dest_name'] = $destName; $report[$objectName]['dest_iban'] = $destIban; // add amounts: - $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -238,16 +238,16 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $sourceName = $journal['source_account_name']; - $sourceIban = $journal['source_account_iban']; - $genericName = $this->getCounterpartName($withCounterpart, $sourceId, $sourceName, $sourceIban); - $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); + $sourceId = $journal['source_account_id']; + $sourceName = $journal['source_account_name']; + $sourceIban = $journal['source_account_iban']; + $genericName = $this->getCounterpartName($withCounterpart, $sourceId, $sourceName, $sourceIban); + $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); $report[$objectName] ??= [ 'dest_name' => '', 'dest_iban' => '', @@ -260,7 +260,7 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; // set name @@ -268,10 +268,10 @@ class DoubleController extends Controller $report[$objectName]['source_iban'] = $sourceIban; // add amounts: - $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -281,7 +281,7 @@ class DoubleController extends Controller /** * TODO this method is duplicated. */ - private function getCounterpartName(Collection $accounts, int $id, string $name, null|string $iban): string + private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string { /** @var Account $account */ foreach ($accounts as $account) { @@ -306,8 +306,8 @@ class DoubleController extends Controller $report = []; $sums = []; // see what happens when we collect transactions. - $spent = $this->opsRepository->listExpenses($start, $end, $together); - $earned = $this->opsRepository->listIncome($start, $end, $together); + $spent = $this->opsRepository->listExpenses($start, $end, $together); + $earned = $this->opsRepository->listIncome($start, $end, $together); // group and list per account name (as long as its not in accounts, only in double) /** @var array $currency */ @@ -322,12 +322,12 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $objectName = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']); + $objectName = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']); $report[$objectName] ??= [ 'account_id' => $journal['source_account_id'], 'account_name' => $objectName, @@ -338,14 +338,14 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; // set name // add amounts: $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -361,12 +361,12 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $objectName = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']); + $objectName = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']); $report[$objectName] ??= [ 'account_id' => $journal['destination_account_id'], 'account_name' => $objectName, @@ -377,14 +377,14 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; // add amounts: $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -418,13 +418,13 @@ class DoubleController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'source_account_name' => $journal['source_account_name'], - 'source_account_id' => $journal['source_account_id'] + 'source_account_id' => $journal['source_account_id'], ]; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'amount_float'); + $amounts = array_column($result, 'amount_float'); array_multisort($amounts, SORT_ASC, $result); try { @@ -466,13 +466,13 @@ class DoubleController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'source_account_name' => $journal['source_account_name'], - 'source_account_id' => $journal['source_account_id'] + 'source_account_id' => $journal['source_account_id'], ]; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'amount_float'); + $amounts = array_column($result, 'amount_float'); array_multisort($amounts, SORT_DESC, $result); try { diff --git a/app/Http/Controllers/Report/OperationsController.php b/app/Http/Controllers/Report/OperationsController.php index 1006868835..7769bcdf80 100644 --- a/app/Http/Controllers/Report/OperationsController.php +++ b/app/Http/Controllers/Report/OperationsController.php @@ -65,7 +65,7 @@ class OperationsController extends Controller public function expenses(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('expense-report'); @@ -99,7 +99,7 @@ class OperationsController extends Controller public function income(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('income-report'); @@ -135,7 +135,7 @@ class OperationsController extends Controller public function operations(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('inc-exp-report'); @@ -151,7 +151,7 @@ class OperationsController extends Controller /** @var int $currencyId */ foreach ($keys as $currencyId) { - $currencyInfo = $incomes['sums'][$currencyId] ?? $expenses['sums'][$currencyId]; + $currencyInfo = $incomes['sums'][$currencyId] ?? $expenses['sums'][$currencyId]; $sums[$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_name' => $currencyInfo['currency_name'], @@ -160,7 +160,7 @@ class OperationsController extends Controller 'currency_decimal_places' => $currencyInfo['currency_decimal_places'], 'in' => $incomes['sums'][$currencyId]['sum'] ?? '0', 'out' => $expenses['sums'][$currencyId]['sum'] ?? '0', - 'sum' => '0' + 'sum' => '0', ]; $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['in'], $sums[$currencyId]['out']); } diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index cbf3e04f4d..9d4fcd6c0a 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -81,13 +81,13 @@ class TagController extends Controller foreach ($currency['tags'] as $tag) { $tagId = $tag['id']; foreach ($tag['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; - $report[$sourceAccountId]['currencies'][$currencyId] ??= [ + $sourceAccountId = $journal['source_account_id']; + $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'tags' => [] + 'tags' => [], ]; $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; @@ -95,7 +95,7 @@ class TagController extends Controller $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'], (string) $journal['amount'] ); @@ -110,20 +110,20 @@ class TagController extends Controller foreach ($currency['tags'] as $tag) { $tagId = $tag['id']; foreach ($tag['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $report[$destinationId]['currencies'][$currencyId] ??= [ + $destinationId = $journal['destination_account_id']; + $report[$destinationId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'tags' => [] + 'tags' => [], ]; $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['earned'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['earned'], (string) $journal['amount'] ); - $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( + $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'], (string) $journal['amount'] ); @@ -162,11 +162,11 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -174,18 +174,18 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -200,11 +200,11 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $destinationAccountId = $journal['destination_account_id']; + $destinationAccountId = $journal['destination_account_id']; $report[$destinationAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -212,18 +212,18 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -238,13 +238,13 @@ class TagController extends Controller */ public function avgExpenses(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -255,11 +255,11 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -288,13 +288,13 @@ class TagController extends Controller */ public function avgIncome(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -305,11 +305,11 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -357,7 +357,7 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; /** @var array $tag */ @@ -376,18 +376,18 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$tagId]['currencies'][$currencyId]['spent'] = bcadd( (string) $report[$tagId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( (string) $report[$tagId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -401,7 +401,7 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0' + 'total_sum' => '0', ]; /** @var array $tag */ @@ -420,18 +420,18 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$tagId]['currencies'][$currencyId]['earned'] = bcadd( (string) $report[$tagId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( (string) $report[$tagId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -446,8 +446,8 @@ class TagController extends Controller */ public function topExpenses(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { @@ -465,7 +465,7 @@ class TagController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'tag_id' => $tag['id'], - 'tag_name' => $tag['name'] + 'tag_name' => $tag['name'], ]; } } @@ -494,15 +494,15 @@ class TagController extends Controller */ public function topIncome(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { $result[] = [ - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float) $journal['amount'], // intentional float. + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + 'amount_float' => (float) $journal['amount'], // intentional float. 'amount' => $journal['amount'], 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), @@ -513,7 +513,7 @@ class TagController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'tag_id' => $tag['id'], - 'tag_name' => $tag['name'] + 'tag_name' => $tag['name'], ]; } } diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index bcc7f1900f..54513e194f 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -65,7 +65,7 @@ class ReportController extends Controller app('view')->share('title', (string) trans('firefly.reports')); app('view')->share('mainTitleIcon', 'fa-bar-chart'); app('view')->share('subTitleIcon', 'fa-calendar'); - $this->helper = app(ReportHelperInterface::class); + $this->helper = app(ReportHelperInterface::class); $this->repository = app(BudgetRepositoryInterface::class); return $next($request); @@ -90,7 +90,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_audit', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Audit', $start, $end); @@ -117,7 +117,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_budget', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Budget', $start, $end); @@ -145,7 +145,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_category', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Category', $start, $end); @@ -174,7 +174,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_default', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Standard', $start, $end); @@ -200,7 +200,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_double', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Account', $start, $end); @@ -229,16 +229,16 @@ class ReportController extends Controller AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); // group accounts by role: - $groupedAccounts = []; + $groupedAccounts = []; /** @var Account $account */ foreach ($accounts as $account) { - $type = $account->accountType->type; - $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); + $type = $account->accountType->type; + $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value], true)) { $role = sprintf('opt_group_l_%s', $type); @@ -251,7 +251,7 @@ class ReportController extends Controller } ksort($groupedAccounts); - $accountList = implode(',', $accounts->pluck('id')->toArray()); + $accountList = implode(',', $accounts->pluck('id')->toArray()); $this->repository->cleanupBudgets(); return view('reports.index', [ @@ -260,7 +260,7 @@ class ReportController extends Controller 'start' => $start, 'accountList' => $accountList, 'groupedAccounts' => $groupedAccounts, - 'customFiscalYear' => $customFiscalYear + 'customFiscalYear' => $customFiscalYear, ]); } @@ -274,11 +274,11 @@ class ReportController extends Controller public function options(string $reportType) { $result = match ($reportType) { - default => $this->noReportOptions(), + default => $this->noReportOptions(), 'category' => $this->categoryReportOptions(), - 'budget' => $this->budgetReportOptions(), - 'tag' => $this->tagReportOptions(), - 'double' => $this->doubleReportOptions() + 'budget' => $this->budgetReportOptions(), + 'tag' => $this->tagReportOptions(), + 'double' => $this->doubleReportOptions() }; return response()->json(['html' => $result]); @@ -336,13 +336,13 @@ class ReportController extends Controller return view('errors.error')->with('message', (string) trans('firefly.end_after_start_date')); } - $url = match ($reportType) { - default => route('reports.report.default', [$accounts, $start, $end]), + $url = match ($reportType) { + default => route('reports.report.default', [$accounts, $start, $end]), 'category' => route('reports.report.category', [$accounts, $categories, $start, $end]), - 'audit' => route('reports.report.audit', [$accounts, $start, $end]), - 'budget' => route('reports.report.budget', [$accounts, $budgets, $start, $end]), - 'tag' => route('reports.report.tag', [$accounts, $tags, $start, $end]), - 'double' => route('reports.report.double', [$accounts, $double, $start, $end]) + 'audit' => route('reports.report.audit', [$accounts, $start, $end]), + 'budget' => route('reports.report.budget', [$accounts, $budgets, $start, $end]), + 'tag' => route('reports.report.tag', [$accounts, $tags, $start, $end]), + 'double' => route('reports.report.double', [$accounts, $double, $start, $end]) }; return redirect($url); @@ -366,7 +366,7 @@ class ReportController extends Controller app('view')->share('subTitle', trans('firefly.report_tag', [ 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ])); $generator = ReportGeneratorFactory::reportGenerator('Tag', $start, $end); diff --git a/app/Http/Controllers/Rule/CreateController.php b/app/Http/Controllers/Rule/CreateController.php index dd45904f06..614b8faa8b 100644 --- a/app/Http/Controllers/Rule/CreateController.php +++ b/app/Http/Controllers/Rule/CreateController.php @@ -77,17 +77,17 @@ class CreateController extends Controller * * @throws FireflyException */ - public function create(Request $request, null|RuleGroup $ruleGroup = null): Factory|\Illuminate\Contracts\View\View + public function create(Request $request, ?RuleGroup $ruleGroup = null): Factory|\Illuminate\Contracts\View\View { $this->createDefaultRuleGroup(); - $preFilled = ['strict' => true]; - $oldTriggers = []; - $oldActions = []; + $preFilled = ['strict' => true]; + $oldTriggers = []; + $oldActions = []; // build triggers from query, if present. - $query = (string) $request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { - $search = app(SearchInterface::class); + $search = app(SearchInterface::class); $search->parseQuery($query); $words = $search->getWords(); $excludedWords = $search->getExcludedWords(); @@ -104,7 +104,7 @@ class CreateController extends Controller $operators[] = ['type' => '-description_contains', 'value' => $excludedWord]; } } - $oldTriggers = $this->parseFromOperators($operators); + $oldTriggers = $this->parseFromOperators($operators); } // var_dump($oldTriggers);exit; @@ -119,7 +119,7 @@ class CreateController extends Controller $subTitleIcon = 'fa-clone'; // title depends on whether or not there is a rule group: - $subTitle = (string) trans('firefly.make_new_rule_no_group'); + $subTitle = (string) trans('firefly.make_new_rule_no_group'); if ($ruleGroup instanceof RuleGroup) { $subTitle = (string) trans('firefly.make_new_rule', ['title' => $ruleGroup->title]); } @@ -141,7 +141,7 @@ class CreateController extends Controller 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, 'ruleGroup' => $ruleGroup, - 'subTitle' => $subTitle + 'subTitle' => $subTitle, ]); } @@ -157,17 +157,17 @@ class CreateController extends Controller $request->session()->flash('info', (string) trans('firefly.instructions_rule_from_bill', ['name' => e($bill->name)])); $this->createDefaultRuleGroup(); - $preFilled = [ + $preFilled = [ 'strict' => true, 'title' => (string) trans('firefly.new_rule_for_bill_title', ['name' => $bill->name]), - 'description' => (string) trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]) + 'description' => (string) trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]), ]; // make triggers and actions from the bill itself. // get triggers and actions for bill: - $oldTriggers = $this->getTriggersForBill($bill); - $oldActions = $this->getActionsForBill($bill); + $oldTriggers = $this->getTriggersForBill($bill); + $oldActions = $this->getActionsForBill($bill); // restore actions and triggers from old input: if (null !== $request->old() && is_array($request->old()) && count($request->old()) > 0) { @@ -180,7 +180,7 @@ class CreateController extends Controller $subTitleIcon = 'fa-clone'; // title depends on whether there is a rule group: - $subTitle = (string) trans('firefly.make_new_rule_no_group'); + $subTitle = (string) trans('firefly.make_new_rule_no_group'); // flash old data $request->session()->flash('preFilled', $preFilled); @@ -198,7 +198,7 @@ class CreateController extends Controller 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, - 'subTitle' => $subTitle + 'subTitle' => $subTitle, ]); } @@ -213,16 +213,16 @@ class CreateController extends Controller $subTitle = (string) trans('firefly.make_new_rule_no_group'); // get triggers and actions for journal. - $oldTriggers = $this->getTriggersForJournal($journal); - $oldActions = []; + $oldTriggers = $this->getTriggersForJournal($journal); + $oldActions = []; $this->createDefaultRuleGroup(); // collect pre-filled information: - $preFilled = [ + $preFilled = [ 'strict' => true, 'title' => (string) trans('firefly.new_rule_for_journal_title', ['description' => $journal->description]), - 'description' => (string) trans('firefly.new_rule_for_journal_description', ['description' => $journal->description]) + 'description' => (string) trans('firefly.new_rule_for_journal_description', ['description' => $journal->description]), ]; // restore actions and triggers from old input: @@ -250,7 +250,7 @@ class CreateController extends Controller 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, - 'subTitle' => $subTitle + 'subTitle' => $subTitle, ]); } @@ -272,8 +272,8 @@ class CreateController extends Controller */ public function store(RuleFormRequest $request) { - $data = $request->getRuleData(); - $rule = $this->ruleRepos->store($data); + $data = $request->getRuleData(); + $rule = $this->ruleRepos->store($data); session()->flash('success_url', route('rules.select-transactions', [$rule->id])); session()->flash('success', (string) trans('firefly.stored_new_rule', ['title' => $rule->title])); Preferences::mark(); diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php index 7973aa82cc..2f0ce2402c 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -78,15 +78,15 @@ class EditController extends Controller */ public function edit(Request $request, Rule $rule): Factory|\Illuminate\Contracts\View\View { - $triggerCount = 0; - $actionCount = 0; - $oldActions = []; - $oldTriggers = []; + $triggerCount = 0; + $actionCount = 0; + $oldActions = []; + $oldTriggers = []; // build triggers from query, if present. - $query = (string) $request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { - $search = app(SearchInterface::class); + $search = app(SearchInterface::class); $search->parseQuery($query); $words = $search->getWords(); $excludedWords = $search->getExcludedWords(); @@ -103,15 +103,15 @@ class EditController extends Controller $operators[] = ['type' => '-description_contains', 'value' => $excludedWord]; } } - $oldTriggers = $this->parseFromOperators($operators); + $oldTriggers = $this->parseFromOperators($operators); } // has old input? if (null !== $request->old() && is_array($request->old()) && count($request->old()) > 0) { $oldTriggers = $this->getPreviousTriggers($request); $oldActions = $this->getPreviousActions($request); } - $triggerCount = count($oldTriggers); - $actionCount = count($oldActions); + $triggerCount = count($oldTriggers); + $actionCount = count($oldActions); // overrule old input and query data when it has no rule data: if (0 === $triggerCount && 0 === $actionCount) { @@ -121,11 +121,11 @@ class EditController extends Controller $actionCount = count($oldActions); } - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'active' => $hasOldInput ? (bool) $request->old('active') : $rule->active, 'stop_processing' => $hasOldInput ? (bool) $request->old('stop_processing') : $rule->stop_processing, - 'strict' => $hasOldInput ? (bool) $request->old('strict') : $rule->strict + 'strict' => $hasOldInput ? (bool) $request->old('strict') : $rule->strict, ]; // get rule trigger for update / store-journal: @@ -147,7 +147,7 @@ class EditController extends Controller 'oldTriggers' => $oldTriggers, 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, - 'actionCount' => $actionCount + 'actionCount' => $actionCount, ]); } @@ -167,7 +167,7 @@ class EditController extends Controller } asort($triggers); - $index = 0; + $index = 0; foreach ($submittedOperators as $operator) { try { $renderedEntries[] = view('rules.partials.trigger', [ @@ -175,7 +175,7 @@ class EditController extends Controller 'oldValue' => $operator['value'], 'oldChecked' => false, 'count' => $index + 1, - 'triggers' => $triggers + 'triggers' => $triggers, ])->render(); } catch (Throwable $e) { $message = sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage()); @@ -197,7 +197,7 @@ class EditController extends Controller */ public function update(RuleFormRequest $request, Rule $rule) { - $data = $request->getRuleData(); + $data = $request->getRuleData(); $this->ruleRepos->update($rule, $data); diff --git a/app/Http/Controllers/Rule/IndexController.php b/app/Http/Controllers/Rule/IndexController.php index 72a6cceb0d..ea33e10e9c 100644 --- a/app/Http/Controllers/Rule/IndexController.php +++ b/app/Http/Controllers/Rule/IndexController.php @@ -55,7 +55,7 @@ class IndexController extends Controller app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->ruleGroupRepos = app(RuleGroupRepositoryInterface::class); - $this->ruleRepos = app(RuleRepositoryInterface::class); + $this->ruleRepos = app(RuleRepositoryInterface::class); return $next($request); }); diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index f338f64fcb..0f5bc32464 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -71,8 +71,8 @@ class SelectController extends Controller { // Get parameters specified by the user /** @var User $user */ - $user = auth()->user(); - $accounts = implode(',', $request->get('accounts')); + $user = auth()->user(); + $accounts = implode(',', $request->get('accounts')); // create new rule engine: $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($user); @@ -93,7 +93,7 @@ class SelectController extends Controller // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); $newRuleEngine->fire(); - $resultCount = $newRuleEngine->getResults(); + $resultCount = $newRuleEngine->getResults(); session()->flash('success', trans_choice('firefly.applied_rule_selection', $resultCount, ['title' => $rule->title])); @@ -125,14 +125,14 @@ class SelectController extends Controller public function testTriggers(TestRuleFormRequest $request): JsonResponse { // build fake rule - $rule = new Rule(); + $rule = new Rule(); /** @var \Illuminate\Database\Eloquent\Collection $triggers */ - $triggers = new Collection(); - $rule->strict = '1' === $request->get('strict'); + $triggers = new Collection(); + $rule->strict = '1' === $request->get('strict'); // build trigger array from response - $textTriggers = $this->getValidTriggerList($request); + $textTriggers = $this->getValidTriggerList($request); // warn if nothing. if (0 === count($textTriggers)) { @@ -140,10 +140,10 @@ class SelectController extends Controller } foreach ($textTriggers as $textTrigger) { - $needsContext = config(sprintf('search.operators.%s.needs_context', $textTrigger['type'])) ?? true; - $trigger = new RuleTrigger(); - $trigger->trigger_type = $textTrigger['type']; - $trigger->trigger_value = $textTrigger['value']; + $needsContext = config(sprintf('search.operators.%s.needs_context', $textTrigger['type'])) ?? true; + $trigger = new RuleTrigger(); + $trigger->trigger_type = $textTrigger['type']; + $trigger->trigger_value = $textTrigger['value']; if (false === $needsContext) { $trigger->trigger_value = 'true'; } @@ -158,22 +158,22 @@ class SelectController extends Controller // create new rule engine: /** @var RuleEngineInterface $newRuleEngine */ - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); $newRuleEngine->setRefreshTriggers(false); - $collection = $newRuleEngine->find(); - $collection = $collection->slice(0, 20); + $collection = $newRuleEngine->find(); + $collection = $collection->slice(0, 20); // Warn the user if only a subset of transactions is returned - $warning = ''; + $warning = ''; if (0 === count($collection)) { $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response - $view = 'ERROR, see logs.'; + $view = 'ERROR, see logs.'; try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); @@ -196,7 +196,7 @@ class SelectController extends Controller */ public function testTriggersByRule(Rule $rule): JsonResponse { - $triggers = $rule->ruleTriggers; + $triggers = $rule->ruleTriggers; if (0 === count($triggers)) { return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); @@ -206,16 +206,16 @@ class SelectController extends Controller // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); - $collection = $newRuleEngine->find(); - $collection = $collection->slice(0, 20); + $collection = $newRuleEngine->find(); + $collection = $collection->slice(0, 20); - $warning = ''; + $warning = ''; if (0 === count($collection)) { $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response - $view = 'ERROR, see logs.'; + $view = 'ERROR, see logs.'; try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); diff --git a/app/Http/Controllers/RuleGroup/CreateController.php b/app/Http/Controllers/RuleGroup/CreateController.php index 3ca5107b60..cb063c6a35 100644 --- a/app/Http/Controllers/RuleGroup/CreateController.php +++ b/app/Http/Controllers/RuleGroup/CreateController.php @@ -90,7 +90,7 @@ class CreateController extends Controller session()->flash('success', (string) trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('rule-groups.create.url')); + $redirect = redirect($this->getPreviousUrl('rule-groups.create.url')); if (1 === (int) $request->get('create_another')) { session()->put('rule-groups.create.fromStore', true); diff --git a/app/Http/Controllers/RuleGroup/DeleteController.php b/app/Http/Controllers/RuleGroup/DeleteController.php index c026131365..9da90c8047 100644 --- a/app/Http/Controllers/RuleGroup/DeleteController.php +++ b/app/Http/Controllers/RuleGroup/DeleteController.php @@ -79,7 +79,7 @@ class DeleteController extends Controller */ public function destroy(Request $request, RuleGroup $ruleGroup): Redirector|RedirectResponse { - $title = $ruleGroup->title; + $title = $ruleGroup->title; /** @var RuleGroup $moveTo */ $moveTo = $this->repository->find((int) $request->get('move_rules_before_delete')); diff --git a/app/Http/Controllers/RuleGroup/EditController.php b/app/Http/Controllers/RuleGroup/EditController.php index ab1e2308cb..cc034d30de 100644 --- a/app/Http/Controllers/RuleGroup/EditController.php +++ b/app/Http/Controllers/RuleGroup/EditController.php @@ -67,7 +67,7 @@ class EditController extends Controller */ public function edit(Request $request, RuleGroup $ruleGroup): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.edit_rule_group', ['title' => $ruleGroup->title]); + $subTitle = (string) trans('firefly.edit_rule_group', ['title' => $ruleGroup->title]); $hasOldInput = null !== $request->old('_token'); $preFilled = ['active' => $hasOldInput ? (bool) $request->old('active') : $ruleGroup->active]; @@ -117,10 +117,10 @@ class EditController extends Controller */ public function update(RuleGroupFormRequest $request, RuleGroup $ruleGroup) { - $data = [ + $data = [ 'title' => $request->convertString('title'), 'description' => $request->stringWithNewlines('description'), - 'active' => 1 === (int) $request->input('active') + 'active' => 1 === (int) $request->input('active'), ]; $this->repository->update($ruleGroup, $data); diff --git a/app/Http/Controllers/RuleGroup/ExecutionController.php b/app/Http/Controllers/RuleGroup/ExecutionController.php index ec4b950215..fce16d4f26 100644 --- a/app/Http/Controllers/RuleGroup/ExecutionController.php +++ b/app/Http/Controllers/RuleGroup/ExecutionController.php @@ -71,8 +71,8 @@ class ExecutionController extends Controller { Log::debug(sprintf('You have selected rule group #%d', $ruleGroup->id)); // Get parameters specified by the user - $accounts = $request->get('accounts'); - $set = new Collection(); + $accounts = $request->get('accounts'); + $set = new Collection(); if (is_array($accounts)) { $set = $this->repository->getAccountsById($accounts); } @@ -92,8 +92,8 @@ class ExecutionController extends Controller $endDate = new Carbon($request->get('end')); $collector->setEnd($endDate); } - $final = $collector->getGroups(); - $ids = $final->pluck('id')->toArray(); + $final = $collector->getGroups(); + $ids = $final->pluck('id')->toArray(); Log::debug(sprintf('Found %d groups collected from %d account(s)', $final->count(), $set->count())); foreach (array_chunk($ids, 1337) as $setOfIds) { Log::debug(sprintf('Now processing %d groups', count($setOfIds))); diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index cc2e776a6c..f4b831210e 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -61,18 +61,18 @@ class SearchController extends Controller public function index(Request $request, SearchInterface $searcher): Factory|\Illuminate\Contracts\View\View { // search params: - $fullQuery = $request->get('search'); + $fullQuery = $request->get('search'); if (is_array($request->get('search'))) { $fullQuery = ''; } - $fullQuery = (string) $fullQuery; - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $ruleId = (int) $request->get('rule'); - $ruleChanged = false; + $fullQuery = (string) $fullQuery; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $ruleId = (int) $request->get('rule'); + $ruleChanged = false; // find rule, check if query is different, offer to update. - $ruleRepository = app(RuleRepositoryInterface::class); - $rule = $ruleRepository->find($ruleId); + $ruleRepository = app(RuleRepositoryInterface::class); + $rule = $ruleRepository->find($ruleId); if (null !== $rule) { $originalQuery = $ruleRepository->getSearchQuery($rule); if ($originalQuery !== $fullQuery) { @@ -99,7 +99,7 @@ class SearchController extends Controller 'subTitle' => $subTitle, 'ruleId' => $ruleId, 'ruleChanged' => $ruleChanged, - 'invalidOperators' => $invalidOperators + 'invalidOperators' => $invalidOperators, ]); } @@ -110,12 +110,12 @@ class SearchController extends Controller */ public function search(Request $request, SearchInterface $searcher): JsonResponse { - $entry = $request->get('query'); + $entry = $request->get('query'); if (!is_scalar($entry)) { $entry = ''; } - $fullQuery = (string) $entry; - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $fullQuery = (string) $entry; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); $searcher->parseQuery($fullQuery); @@ -124,7 +124,7 @@ class SearchController extends Controller $hasPages = $groups->hasPages(); $searchTime = round($searcher->searchTime(), 3); // in seconds $parameters = ['search' => $fullQuery]; - $url = route('search.index') . '?' . http_build_query($parameters); + $url = route('search.index').'?'.http_build_query($parameters); $groups->setPath($url); try { diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index 302effafc1..defcb6b4a4 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -53,16 +53,16 @@ class InstallController extends Controller public const string FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.'; public const string OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.'; - private string $lastError = ''; + private string $lastError = ''; // empty on purpose. - private array $upgradeCommands = [ + private array $upgradeCommands = [ // there are 5 initial commands // Check 4 places: InstallController, Docker image, UpgradeDatabase, composer.json - 'migrate' => ['--seed' => true, '--force' => true], - 'generate-keys' => [], // an exception :( + 'migrate' => ['--seed' => true, '--force' => true], + 'generate-keys' => [], // an exception :( 'firefly-iii:upgrade-database' => [], 'firefly-iii:set-latest-version' => ['--james-is-cool' => true], - 'firefly-iii:verify-security-alerts' => [] + 'firefly-iii:verify-security-alerts' => [], ]; /** @@ -95,10 +95,10 @@ class InstallController extends Controller $response = ['hasNextCommand' => false, 'done' => true, 'previous' => null, 'error' => false, 'errorMessage' => null]; Log::debug(sprintf('Will now run commands. Request index is %d', $requestIndex)); - $indexes = array_keys($this->upgradeCommands); + $indexes = array_keys($this->upgradeCommands); if (array_key_exists($requestIndex, $indexes)) { - $command = $indexes[$requestIndex]; - $parameters = $this->upgradeCommands[$command]; + $command = $indexes[$requestIndex]; + $parameters = $this->upgradeCommands[$command]; Log::debug(sprintf('Will now execute command "%s" with parameters', $command), $parameters); try { @@ -109,17 +109,17 @@ class InstallController extends Controller if (str_contains($e->getMessage(), 'open_basedir restriction in effect')) { $this->lastError = self::BASEDIR_ERROR; } - $result = false; + $result = false; $this->lastError = sprintf('%s %s', self::OTHER_ERROR, $e->getMessage()); } if (false === $result) { $response['errorMessage'] = $this->lastError; - $response['error'] = true; + $response['error'] = true; return response()->json($response); } $response['hasNextCommand'] = array_key_exists($requestIndex + 1, $indexes); - $response['previous'] = $command; + $response['previous'] = $command; } return response()->json($response); @@ -155,7 +155,7 @@ class InstallController extends Controller */ public function keys(): void { - $key = RSA::createKey(4096); + $key = RSA::createKey(4096); [$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')]; diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php index 14975b601d..6bc8cd7c80 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -64,7 +64,7 @@ class TagController extends Controller app('view')->share('mainTitleIcon', 'fa-tag'); $this->attachmentsHelper = app(AttachmentHelperInterface::class); - $this->repository = app(TagRepositoryInterface::class); + $this->repository = app(TagRepositoryInterface::class); return $next($request); }); @@ -81,12 +81,12 @@ class TagController extends Controller $subTitleIcon = 'fa-tag'; // location info: - $hasOldInput = null !== $request->old('_token'); - $locations = ['location' => [ + $hasOldInput = null !== $request->old('_token'); + $locations = ['location' => [ 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), - 'has_location' => $hasOldInput && 'true' === old('location_has_location') + 'has_location' => $hasOldInput && 'true' === old('location_has_location'), ]]; // put previous url in session if not redirect from store (not "create another"). @@ -123,16 +123,16 @@ class TagController extends Controller $subTitle = (string) trans('firefly.edit_tag', ['tag' => $tag->tag]); $subTitleIcon = 'fa-tag'; - $location = $this->repository->getLocation($tag); - $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); - $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); - $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); - $hasLocation = $location instanceof Location; - $locations = ['location' => [ + $location = $this->repository->getLocation($tag); + $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); + $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); + $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); + $hasLocation = $location instanceof Location; + $locations = ['location' => [ 'latitude' => old('location_latitude') ?? $latitude, 'longitude' => old('location_longitude') ?? $longitude, 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, - 'has_location' => $hasLocation || 'true' === old('location_has_location') + 'has_location' => $hasLocation || 'true' === old('location_has_location'), ]]; // put previous url in session if not redirect from store (not "return_to_edit"). @@ -152,9 +152,9 @@ class TagController extends Controller public function index(TagRepositoryInterface $repository): Factory|\Illuminate\Contracts\View\View { // start with the oldest tag - $first = session('first', today()) ?? today(); - $oldestTagDate = $repository->oldestTag() instanceof Tag ? $repository->oldestTag()->date : clone $first; - $newestTagDate = $repository->newestTag() instanceof Tag ? $repository->newestTag()->date : today(); + $first = session('first', today()) ?? today(); + $oldestTagDate = $repository->oldestTag() instanceof Tag ? $repository->oldestTag()->date : clone $first; + $newestTagDate = $repository->newestTag() instanceof Tag ? $repository->newestTag()->date : today(); $oldestTagDate->startOfYear(); $newestTagDate->endOfYear(); @@ -163,22 +163,22 @@ class TagController extends Controller request()->session()->flash('error', trans('firefly.bad_date_transaction')); } - $tags = []; + $tags = []; $tags['no-date'] = $repository->getTagsInYear(null); while ($newestTagDate > $oldestTagDate) { - $year = $newestTagDate->year; + $year = $newestTagDate->year; $tags[$year] = $repository->getTagsInYear($year); $newestTagDate->subYear(); } - $count = $repository->count(); + $count = $repository->count(); return view('tags.index', ['tags' => $tags, 'count' => $count]); } public function massDestroy(Request $request): RedirectResponse { - $tags = $request->get('tags'); + $tags = $request->get('tags'); if (null === $tags || !is_array($tags)) { session()->flash('info', (string) trans('firefly.select_tags_to_delete')); @@ -221,30 +221,30 @@ class TagController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function show(Request $request, Tag $tag, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function show(Request $request, Tag $tag, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View { // default values: $subTitleIcon = 'fa-tag'; $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $start ??= session('start'); - $end ??= session('end'); + $start ??= session('start'); + $end ??= session('end'); $location = $this->repository->getLocation($tag); $attachments = $this->repository->getAttachments($tag); $subTitle = trans('firefly.journals_in_period_for_tag', [ 'tag' => $tag->tag, 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat) + 'end' => $end->isoFormat($this->monthAndDayFormat), ]); - $startPeriod = $this->repository->firstUseDate($tag); + $startPeriod = $this->repository->firstUseDate($tag); $startPeriod ??= today(config('app.timezone')); - $endPeriod = clone $end; - $periods = $this->getTagPeriodOverview($tag, $startPeriod, $endPeriod); - $path = route('tags.show', [$tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $endPeriod = clone $end; + $periods = $this->getTagPeriodOverview($tag, $startPeriod, $endPeriod); + $path = route('tags.show', [$tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setRange($start, $end) @@ -254,10 +254,11 @@ class TagController extends Controller ->setTag($tag) ->withBudgetInformation() ->withCategoryInformation() - ->withAttachmentInformation(); - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation() + ; + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - $sums = $this->repository->sumsOfTag($tag, $start, $end); + $sums = $this->repository->sumsOfTag($tag, $start, $end); return view('tags.show', [ 'tag' => $tag, @@ -269,7 +270,7 @@ class TagController extends Controller 'groups' => $groups, 'start' => $start, 'end' => $end, - 'location' => $location + 'location' => $location, ]); } @@ -296,7 +297,7 @@ class TagController extends Controller $location = $this->repository->getLocation($tag); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setRange($start, $end) ->setLimit($pageSize) @@ -305,10 +306,11 @@ class TagController extends Controller ->setTag($tag) ->withBudgetInformation() ->withCategoryInformation() - ->withAttachmentInformation(); - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation() + ; + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - $sums = $this->repository->sumsOfTag($tag, $start, $end); + $sums = $this->repository->sumsOfTag($tag, $start, $end); return view('tags.show', [ 'tag' => $tag, @@ -320,7 +322,7 @@ class TagController extends Controller 'groups' => $groups, 'start' => $start, 'end' => $end, - 'location' => $location + 'location' => $location, ]); } @@ -329,10 +331,10 @@ class TagController extends Controller */ public function store(TagFormRequest $request): RedirectResponse { - $data = $request->collectTagData(); + $data = $request->collectTagData(); Log::debug('Data from request', $data); - $result = $this->repository->store($data); + $result = $this->repository->store($data); Log::debug('Data after storage', $result->toArray()); session()->flash('success', (string) trans('firefly.created_tag', ['tag' => $data['tag']])); @@ -340,7 +342,7 @@ class TagController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachmentsHelper->saveAttachmentsForModel($result, $files); } @@ -370,15 +372,15 @@ class TagController extends Controller */ public function update(TagFormRequest $request, Tag $tag): RedirectResponse { - $data = $request->collectTagData(); - $tag = $this->repository->update($tag, $data); + $data = $request->collectTagData(); + $tag = $this->repository->update($tag, $data); session()->flash('success', (string) trans('firefly.updated_tag', ['tag' => $data['tag']])); Preferences::mark(); // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachmentsHelper->saveAttachmentsForModel($tag, $files); } diff --git a/app/Http/Controllers/Transaction/BulkController.php b/app/Http/Controllers/Transaction/BulkController.php index d09f059e35..3ca968c110 100644 --- a/app/Http/Controllers/Transaction/BulkController.php +++ b/app/Http/Controllers/Transaction/BulkController.php @@ -72,7 +72,7 @@ class BulkController extends Controller */ public function edit(array $journals): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.mass_bulk_journals'); + $subTitle = (string) trans('firefly.mass_bulk_journals'); $this->rememberPreviousUrl('transactions.bulk-edit.url'); diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index a1cf19e0ce..9fc607961e 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -92,16 +92,16 @@ class ConvertController extends Controller } /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); /** @var TransactionJournal $first */ - $first = $group->transactionJournals()->first(); - $sourceType = $first->transactionType; + $first = $group->transactionJournals()->first(); + $sourceType = $first->transactionType; - $groupTitle = $group->title ?? $first->description; - $groupArray = $transformer->transformObject($group); - $subTitle = (string) trans('firefly.convert_to_' . $destinationType->type, ['description' => $groupTitle]); - $subTitleIcon = 'fa-exchange'; + $groupTitle = $group->title ?? $first->description; + $groupArray = $transformer->transformObject($group); + $subTitle = (string) trans('firefly.convert_to_'.$destinationType->type, ['description' => $groupTitle]); + $subTitleIcon = 'fa-exchange'; // get a list of asset accounts and liabilities and stuff, in various combinations: $validDepositSources = $this->getValidDepositSources(); @@ -110,11 +110,11 @@ class ConvertController extends Controller $assets = $this->getAssetAccounts(); // old input variables: - $preFilled = ['source_name' => old('source_name')]; + $preFilled = ['source_name' => old('source_name')]; if ($sourceType->type === $destinationType->type) { // cannot convert to its own type. Log::debug('This is already a transaction of the expected type..'); - session()->flash('info', (string) trans('firefly.convert_is_already_type_' . $destinationType->type)); + session()->flash('info', (string) trans('firefly.convert_is_already_type_'.$destinationType->type)); return redirect(route('transactions.show', [$group->id])); } @@ -131,7 +131,7 @@ class ConvertController extends Controller 'validWithdrawalDests' => $validWithdrawalDests, 'preFilled' => $preFilled, 'subTitle' => $subTitle, - 'subTitleIcon' => $subTitleIcon + 'subTitleIcon' => $subTitleIcon, ]); } @@ -144,22 +144,22 @@ class ConvertController extends Controller AccountTypeEnum::CASH->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); - $name = $account->name; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $name = $account->name; if ('' === $role) { $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; + $role = 'l_'.$account->accountType->type; } if (AccountTypeEnum::CASH->value === $account->accountType->type) { $role = 'cash_account'; @@ -169,7 +169,7 @@ class ConvertController extends Controller $role = 'revenue_account'; } - $key = (string) trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_'.$role); $grouped[$key][$account->id] = $name; } @@ -185,22 +185,22 @@ class ConvertController extends Controller AccountTypeEnum::CASH->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); - $name = $account->name; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $name = $account->name; if ('' === $role) { $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; + $role = 'l_'.$account->accountType->type; } if (AccountTypeEnum::CASH->value === $account->accountType->type) { $role = 'cash_account'; @@ -210,7 +210,7 @@ class ConvertController extends Controller $role = 'expense_account'; } - $key = (string) trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_'.$role); $grouped[$key][$account->id] = $name; } @@ -226,21 +226,21 @@ class ConvertController extends Controller $accountList = $this->accountRepository->getActiveAccountsByType([ AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $date = today()->endOfDay(); + $date = today()->endOfDay(); Log::debug(sprintf('getLiabilities: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balance = Steam::finalAccountBalance($account, $date)['balance']; - $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; - $role = sprintf('l_%s', $account->accountType->type); - $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); + $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; + $role = sprintf('l_%s', $account->accountType->type); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false)); } @@ -259,19 +259,19 @@ class ConvertController extends Controller // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $date = today()->endOfDay(); + $date = today()->endOfDay(); Log::debug(sprintf('getAssetAccounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balance = Steam::finalAccountBalance($account, $date)['balance']; - $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; + $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); if ('' === $role) { $role = 'no_account_type'; } - $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false)); } @@ -304,7 +304,7 @@ class ConvertController extends Controller // correct transfers: $group->refresh(); - session()->flash('success', (string) trans('firefly.converted_to_' . $destinationType->type)); + session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type)); event(new UpdatedTransactionGroup($group, true, true, true)); return redirect(route('transactions.show', [$group->id])); @@ -316,22 +316,22 @@ class ConvertController extends Controller private function convertJournal(TransactionJournal $journal, TransactionType $transactionType, array $data): TransactionJournal { /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setUser(auth()->user()); $validator->setTransactionType($transactionType->type); - $sourceId = $data['source_id'][$journal->id] ?? null; - $sourceName = $data['source_name'][$journal->id] ?? null; - $destinationId = $data['destination_id'][$journal->id] ?? null; - $destinationName = $data['destination_name'][$journal->id] ?? null; + $sourceId = $data['source_id'][$journal->id] ?? null; + $sourceName = $data['source_name'][$journal->id] ?? null; + $destinationId = $data['destination_id'][$journal->id] ?? null; + $destinationName = $data['destination_name'][$journal->id] ?? null; // double check it's not an empty string. - $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; - $sourceName = '' === $sourceName ? null : (string) $sourceName; - $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; - $destinationName = '' === $destinationName ? null : (string) $destinationName; - $validSource = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); - $validDestination = $validator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); + $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; + $sourceName = '' === $sourceName ? null : (string) $sourceName; + $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; + $destinationName = '' === $destinationName ? null : (string) $destinationName; + $validSource = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $validDestination = $validator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); if (false === $validSource) { throw new FireflyException(sprintf(trans('firefly.convert_invalid_source'), $journal->id)); @@ -342,12 +342,12 @@ class ConvertController extends Controller // TODO typeOverrule: the account validator may have another opinion on the transaction type. - $update = [ + $update = [ 'source_id' => $sourceId, 'source_name' => $sourceName, 'destination_id' => $destinationId, 'destination_name' => $destinationName, - 'type' => $transactionType->type + 'type' => $transactionType->type, ]; /** @var null|Transaction $sourceTransaction */ @@ -365,9 +365,9 @@ class ConvertController extends Controller && $destCurrency instanceof TransactionCurrency && $sourceCurrency->code !== $destCurrency->code ) { - $update['currency_id'] = $sourceCurrency->id; + $update['currency_id'] = $sourceCurrency->id; $update['foreign_currency_id'] = $destCurrency->id; - $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. + $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. } } @@ -382,14 +382,14 @@ class ConvertController extends Controller && $destCurrency instanceof TransactionCurrency && $sourceCurrency->code !== $destCurrency->code ) { - $update['currency_id'] = $sourceCurrency->id; + $update['currency_id'] = $sourceCurrency->id; $update['foreign_currency_id'] = $destCurrency->id; - $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. + $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. } } /** @var JournalUpdateService $service */ - $service = app(JournalUpdateService::class); + $service = app(JournalUpdateService::class); $service->setTransactionJournal($journal); $service->setData($update); $service->update(); diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index 2fa4748b53..d4afadafbe 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -80,8 +80,8 @@ class CreateController extends Controller Preferences::mark(); - $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; - $link = route('transactions.show', [$newGroup->id]); + $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; + $link = route('transactions.show', [$newGroup->id]); session()->flash('success', trans('firefly.stored_journal', ['description' => $title])); session()->flash('success_url', $link); @@ -103,19 +103,19 @@ class CreateController extends Controller * @throws NotFoundExceptionInterface * @throws UrlException */ - public function create(null|string $objectType): Factory|View + public function create(?string $objectType): Factory|View { Preferences::mark(); - $sourceId = (int) request()->get('source'); - $destinationId = (int) request()->get('destination'); + $sourceId = (int) request()->get('source'); + $destinationId = (int) request()->get('destination'); /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $cash = $accountRepository->getCashAccount(); - $preFilled = session()->has('preFilled') ? session('preFilled') : []; - $subTitle = (string) trans(sprintf('breadcrumbs.create_%s', strtolower((string) $objectType))); - $subTitleIcon = 'fa-plus'; + $accountRepository = app(AccountRepositoryInterface::class); + $cash = $accountRepository->getCashAccount(); + $preFilled = session()->has('preFilled') ? session('preFilled') : []; + $subTitle = (string) trans(sprintf('breadcrumbs.create_%s', strtolower((string) $objectType))); + $subTitleIcon = 'fa-plus'; /** @var null|array $optionalFields */ $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; @@ -129,23 +129,23 @@ class CreateController extends Controller $optionalFields = []; } // not really a fan of this, but meh. - $optionalDateFields = [ + $optionalDateFields = [ 'interest_date' => $optionalFields['interest_date'] ?? false, 'book_date' => $optionalFields['book_date'] ?? false, 'process_date' => $optionalFields['process_date'] ?? false, 'due_date' => $optionalFields['due_date'] ?? false, 'payment_date' => $optionalFields['payment_date'] ?? false, - 'invoice_date' => $optionalFields['invoice_date'] ?? false + 'invoice_date' => $optionalFields['invoice_date'] ?? false, ]; $optionalFields['external_url'] ??= false; - $optionalFields['location'] ??= false; - $optionalFields['location'] = - $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; + $optionalFields['location'] ??= false; + $optionalFields['location'] + = $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; // map info: - $longitude = config('firefly.default_location.longitude'); - $latitude = config('firefly.default_location.latitude'); - $zoomLevel = config('firefly.default_location.zoom_level'); + $longitude = config('firefly.default_location.longitude'); + $latitude = config('firefly.default_location.latitude'); + $zoomLevel = config('firefly.default_location.zoom_level'); session()->put('preFilled', $preFilled); @@ -164,7 +164,7 @@ class CreateController extends Controller 'allowedOpposingTypes' => $allowedOpposingTypes, 'accountToTypes' => $accountToTypes, 'sourceId' => $sourceId, - 'destinationId' => $destinationId + 'destinationId' => $destinationId, ]); } } diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php index 702d58c6f2..44a10c046d 100644 --- a/app/Http/Controllers/Transaction/DeleteController.php +++ b/app/Http/Controllers/Transaction/DeleteController.php @@ -76,12 +76,12 @@ class DeleteController extends Controller Log::debug(sprintf('Start of delete view for group #%d', $group->id)); - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { throw new NotFoundHttpException(); } $objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type); - $subTitle = (string) trans('firefly.delete_' . $objectType, ['description' => $group->title ?? $journal->description]); + $subTitle = (string) trans('firefly.delete_'.$objectType, ['description' => $group->title ?? $journal->description]); $previous = Steam::getSafePreviousUrl(); // put previous url in session Log::debug('Will try to remember previous URL'); @@ -92,7 +92,7 @@ class DeleteController extends Controller 'journal' => $journal, 'subTitle' => $subTitle, 'objectType' => $objectType, - 'previous' => $previous + 'previous' => $previous, ]); } @@ -106,15 +106,15 @@ class DeleteController extends Controller return $this->redirectGroupToAccount($group); } - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { throw new NotFoundHttpException(); } $objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type); - session()->flash('success', (string) trans('firefly.deleted_' . strtolower($objectType), ['description' => $group->title ?? $journal->description])); + session()->flash('success', (string) trans('firefly.deleted_'.strtolower($objectType), ['description' => $group->title ?? $journal->description])); // grab asset account(s) from group: - $accounts = []; + $accounts = []; /** @var TransactionJournal $currentJournal */ foreach ($group->transactionJournals as $currentJournal) { diff --git a/app/Http/Controllers/Transaction/EditController.php b/app/Http/Controllers/Transaction/EditController.php index 0314470867..36b1e84f5f 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -100,28 +100,28 @@ class EditController extends Controller $previousUrl = str_replace($search, '', $previousUrl); // settings necessary for v2 - $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; + $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; if (!is_array($optionalFields)) { $optionalFields = []; } // not really a fan of this, but meh. - $optionalDateFields = [ + $optionalDateFields = [ 'interest_date' => $optionalFields['interest_date'] ?? false, 'book_date' => $optionalFields['book_date'] ?? false, 'process_date' => $optionalFields['process_date'] ?? false, 'due_date' => $optionalFields['due_date'] ?? false, 'payment_date' => $optionalFields['payment_date'] ?? false, - 'invoice_date' => $optionalFields['invoice_date'] ?? false + 'invoice_date' => $optionalFields['invoice_date'] ?? false, ]; $optionalFields['external_url'] ??= false; - $optionalFields['location'] ??= false; - $optionalFields['location'] = - $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; + $optionalFields['location'] ??= false; + $optionalFields['location'] + = $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; // map info voor v2: - $longitude = config('firefly.default_location.longitude'); - $latitude = config('firefly.default_location.latitude'); - $zoomLevel = config('firefly.default_location.zoom_level'); + $longitude = config('firefly.default_location.longitude'); + $latitude = config('firefly.default_location.latitude'); + $zoomLevel = config('firefly.default_location.zoom_level'); return view('transactions.edit', [ 'cash' => $cash, @@ -137,7 +137,7 @@ class EditController extends Controller 'transactionGroup' => $transactionGroup, 'allowedOpposingTypes' => $allowedOpposingTypes, 'accountToTypes' => $accountToTypes, - 'previousUrl' => $previousUrl + 'previousUrl' => $previousUrl, ]); } diff --git a/app/Http/Controllers/Transaction/IndexController.php b/app/Http/Controllers/Transaction/IndexController.php index c65681dc2b..6229226676 100644 --- a/app/Http/Controllers/Transaction/IndexController.php +++ b/app/Http/Controllers/Transaction/IndexController.php @@ -74,16 +74,16 @@ class IndexController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function index(Request $request, string $objectType, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function index(Request $request, string $objectType, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View { if ('transfers' === $objectType) { $objectType = 'transfer'; } - $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); - $types = config('firefly.transactionTypesByType.' . $objectType); - $page = (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $subTitleIcon = config('firefly.transactionIconsByType.'.$objectType); + $types = config('firefly.transactionTypesByType.'.$objectType); + $page = (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; if (!$start instanceof Carbon) { $start = session('start'); @@ -96,23 +96,23 @@ class IndexController extends Controller } [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; - $startStr = $start->isoFormat($this->monthAndDayFormat); - $endStr = $end->isoFormat($this->monthAndDayFormat); - $subTitle = (string) trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); - $path = route('transactions.index', [$objectType, $start->format('Y-m-d'), $end->format('Y-m-d')]); - $firstJournal = $this->repository->firstNull(); - $startPeriod = $firstJournal instanceof TransactionJournal ? $firstJournal->date : new Carbon(); - $endPeriod = clone $end; + $startStr = $start->isoFormat($this->monthAndDayFormat); + $endStr = $end->isoFormat($this->monthAndDayFormat); + $subTitle = (string) trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); + $path = route('transactions.index', [$objectType, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $firstJournal = $this->repository->firstNull(); + $startPeriod = $firstJournal instanceof TransactionJournal ? $firstJournal->date : new Carbon(); + $endPeriod = clone $end; // limit to 3 years for the time being. if (now()->diffInYears($startPeriod, true) > 3) { $startPeriod = now()->subYears(3); } - $periods = $this->getTransactionPeriodOverview($objectType, $startPeriod, $endPeriod); + $periods = $this->getTransactionPeriodOverview($objectType, $startPeriod, $endPeriod); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setRange($start, $end) @@ -122,8 +122,9 @@ class IndexController extends Controller ->withBudgetInformation() ->withCategoryInformation() ->withAccountInformation() - ->withAttachmentInformation(); - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation() + ; + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); return view('transactions.index', [ @@ -133,7 +134,7 @@ class IndexController extends Controller 'groups' => $groups, 'periods' => $periods, 'start' => $start, - 'end' => $end + 'end' => $end, ]); } @@ -147,8 +148,8 @@ class IndexController extends Controller */ public function indexAll(Request $request, string $objectType): Factory|\Illuminate\Contracts\View\View { - $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); - $types = config('firefly.transactionTypesByType.' . $objectType); + $subTitleIcon = config('firefly.transactionIconsByType.'.$objectType); + $types = config('firefly.transactionTypesByType.'.$objectType); $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; $path = route('transactions.index.all', [$objectType]); @@ -156,10 +157,10 @@ class IndexController extends Controller $start = $first instanceof TransactionJournal ? $first->date : new Carbon(); $last = $this->repository->getLast(); $end = $last instanceof TransactionJournal ? $last->date : today(config('app.timezone')); - $subTitle = (string) trans('firefly.all_' . $objectType); + $subTitle = (string) trans('firefly.all_'.$objectType); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setRange($start, $end) @@ -169,8 +170,9 @@ class IndexController extends Controller ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->withAttachmentInformation(); - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation() + ; + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); return view('transactions.index', [ @@ -179,7 +181,7 @@ class IndexController extends Controller 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'start' => $start, - 'end' => $end + 'end' => $end, ]); } } diff --git a/app/Http/Controllers/Transaction/LinkController.php b/app/Http/Controllers/Transaction/LinkController.php index 7474558f83..6e9a7923d1 100644 --- a/app/Http/Controllers/Transaction/LinkController.php +++ b/app/Http/Controllers/Transaction/LinkController.php @@ -58,7 +58,7 @@ class LinkController extends Controller app('view')->share('mainTitleIcon', 'fa-exchange'); $this->journalRepository = app(JournalRepositoryInterface::class); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); return $next($request); }); @@ -106,10 +106,10 @@ class LinkController extends Controller */ public function store(JournalLinkRequest $request, TransactionJournal $journal): Redirector|RedirectResponse { - $linkInfo = $request->getLinkInfo(); + $linkInfo = $request->getLinkInfo(); Log::debug('We are here (store)'); - $other = $this->journalRepository->find($linkInfo['transaction_journal_id']); + $other = $this->journalRepository->find($linkInfo['transaction_journal_id']); if (!$other instanceof TransactionJournal) { session()->flash('error', (string) trans('firefly.invalid_link_selection')); diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index 492fed7021..4e25ba027d 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -122,26 +122,26 @@ class MassController extends Controller */ public function edit(array $journals): IlluminateView { - $subTitle = (string) trans('firefly.mass_edit_journals'); + $subTitle = (string) trans('firefly.mass_edit_journals'); /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); + $accountRepository = app(AccountRepositoryInterface::class); // valid withdrawal sources: - $array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionTypeEnum::WITHDRAWAL->value))); - $withdrawalSources = $accountRepository->getAccountsByType($array); + $array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionTypeEnum::WITHDRAWAL->value))); + $withdrawalSources = $accountRepository->getAccountsByType($array); // valid deposit destinations: $array = config(sprintf('firefly.source_dests.%s.%s', TransactionTypeEnum::DEPOSIT->value, AccountTypeEnum::REVENUE->value)); $depositDestinations = $accountRepository->getAccountsByType($array); /** @var BudgetRepositoryInterface $budgetRepository */ - $budgetRepository = app(BudgetRepositoryInterface::class); - $budgets = $budgetRepository->getBudgets(); + $budgetRepository = app(BudgetRepositoryInterface::class); + $budgets = $budgetRepository->getBudgets(); // reverse amounts foreach ($journals as $index => $journal) { - $journals[$index]['amount'] = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']); + $journals[$index]['amount'] = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']); $journals[$index]['foreign_amount'] = null === $journal['foreign_amount'] ? null : Steam::positive($journal['foreign_amount']); } @@ -152,7 +152,7 @@ class MassController extends Controller 'subTitle' => $subTitle, 'withdrawalSources' => $withdrawalSources, 'depositDestinations' => $depositDestinations, - 'budgets' => $budgets + 'budgets' => $budgets, ]); } @@ -168,7 +168,7 @@ class MassController extends Controller // TODO this is a weird error, should be caught. throw new FireflyException('This is not an array.'); } - $count = 0; + $count = 0; /** @var string $journalId */ foreach ($journalIds as $journalId) { @@ -194,15 +194,15 @@ class MassController extends Controller */ private function updateJournal(int $journalId, MassEditJournalRequest $request): void { - $journal = $this->repository->find($journalId); + $journal = $this->repository->find($journalId); if (!$journal instanceof TransactionJournal) { throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId)); } - $service = app(JournalUpdateService::class); + $service = app(JournalUpdateService::class); // for each field, call the update service. $service->setTransactionJournal($journal); - $data = [ + $data = [ 'date' => $this->getDateFromRequest($request, $journal->id, 'date'), 'description' => $this->getStringFromRequest($request, $journal->id, 'description'), 'source_id' => $this->getIntFromRequest($request, $journal->id, 'source_id'), @@ -212,7 +212,7 @@ class MassController extends Controller 'budget_id' => $this->getIntFromRequest($request, $journal->id, 'budget_id'), 'category_name' => $this->getStringFromRequest($request, $journal->id, 'category'), 'amount' => $this->getStringFromRequest($request, $journal->id, 'amount'), - 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount') + 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount'), ]; Log::debug(sprintf('Will update journal #%d with data.', $journal->id), $data); @@ -224,7 +224,7 @@ class MassController extends Controller event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, $runRecalculations)); } - private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): null|Carbon + private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon { $value = $request->get($key); if (!is_array($value)) { @@ -246,7 +246,7 @@ class MassController extends Controller return $carbon; } - private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): null|string + private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string { $value = $request->get($string); if (!is_array($value)) { @@ -259,7 +259,7 @@ class MassController extends Controller return (string) $value[$journalId]; } - private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): null|int + private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int { $value = $request->get($string); if (!is_array($value)) { diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php index 6ff71d9534..459c514923 100644 --- a/app/Http/Controllers/Transaction/ShowController.php +++ b/app/Http/Controllers/Transaction/ShowController.php @@ -57,7 +57,7 @@ class ShowController extends Controller // some useful repositories: $this->middleware(function ($request, $next) { - $this->repository = app(TransactionGroupRepositoryInterface::class); + $this->repository = app(TransactionGroupRepositoryInterface::class); $this->aleRepository = app(ALERepositoryInterface::class); app('view')->share('title', (string) trans('firefly.transactions')); @@ -83,51 +83,51 @@ class ShowController extends Controller public function show(TransactionGroup $transactionGroup): Factory|\Illuminate\Contracts\View\View { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($admin)->setTransactionGroup($transactionGroup)->withAPIInformation(); /** @var null|TransactionGroup $selectedGroup */ - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw new NotFoundHttpException(); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); - $splits = count($selectedGroup['transactions']); - $keys = array_keys($selectedGroup['transactions']); - $first = $selectedGroup['transactions'][array_shift($keys)]; + $splits = count($selectedGroup['transactions']); + $keys = array_keys($selectedGroup['transactions']); + $first = $selectedGroup['transactions'][array_shift($keys)]; unset($keys); if (null === $first) { throw new FireflyException('This transaction is broken :(.'); } - $type = (string) trans(sprintf('firefly.%s', $first['transaction_type_type'])); - $title = 1 === $splits ? $first['description'] : $selectedGroup['title']; - $subTitle = sprintf('%s: "%s"', $type, $title); + $type = (string) trans(sprintf('firefly.%s', $first['transaction_type_type'])); + $title = 1 === $splits ? $first['description'] : $selectedGroup['title']; + $subTitle = sprintf('%s: "%s"', $type, $title); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); /** @var array $selectedGroup */ - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters(new ParameterBag()); - $groupArray = $transformer->transformObject($transactionGroup); + $groupArray = $transformer->transformObject($transactionGroup); // do some calculations: - $amounts = $this->getAmounts($selectedGroup); - $accounts = $this->getAccounts($selectedGroup); + $amounts = $this->getAmounts($selectedGroup); + $accounts = $this->getAccounts($selectedGroup); foreach (array_keys($selectedGroup['transactions']) as $index) { $selectedGroup['transactions'][$index]['tags'] = $this->repository->getTagObjects( @@ -141,9 +141,9 @@ class ShowController extends Controller $logEntries[$journal['transaction_journal_id']] = $this->aleRepository->getForId(TransactionJournal::class, $journal['transaction_journal_id']); } - $events = $this->repository->getPiggyEvents($transactionGroup); - $attachments = $this->repository->getAttachments($transactionGroup); - $links = $this->repository->getLinks($transactionGroup); + $events = $this->repository->getPiggyEvents($transactionGroup); + $attachments = $this->repository->getAttachments($transactionGroup); + $links = $this->repository->getLinks($transactionGroup); return view('transactions.show', [ 'transactionGroup' => $transactionGroup, @@ -159,7 +159,7 @@ class ShowController extends Controller 'events' => $events, 'attachments' => $attachments, 'links' => $links, - 'accounts' => $accounts + 'accounts' => $accounts, ]); } @@ -168,7 +168,7 @@ class ShowController extends Controller $amounts = []; foreach ($group['transactions'] as $transaction) { // add normal amount: - $symbol = $transaction['currency_symbol']; + $symbol = $transaction['currency_symbol']; $amounts[$symbol] ??= ['amount' => '0', 'symbol' => $symbol, 'decimal_places' => $transaction['currency_decimal_places']]; $amounts[$symbol]['amount'] = bcadd($amounts[$symbol]['amount'], (string) $transaction['amount']); @@ -179,22 +179,22 @@ class ShowController extends Controller && 0 !== bccomp('0', (string) $transaction['foreign_amount']) ) { // same for foreign currency: - $foreignSymbol = $transaction['foreign_currency_symbol']; + $foreignSymbol = $transaction['foreign_currency_symbol']; $amounts[$foreignSymbol] ??= [ 'amount' => '0', 'symbol' => $foreignSymbol, - 'decimal_places' => $transaction['foreign_currency_decimal_places'] + 'decimal_places' => $transaction['foreign_currency_decimal_places'], ]; $amounts[$foreignSymbol]['amount'] = bcadd($amounts[$foreignSymbol]['amount'], (string) $transaction['foreign_amount']); } // add primary currency amount if (null !== $transaction['pc_amount'] && $transaction['currency_id'] !== $this->primaryCurrency->id) { // same for foreign currency: - $primarySymbol = $this->primaryCurrency->symbol; + $primarySymbol = $this->primaryCurrency->symbol; $amounts[$primarySymbol] ??= [ 'amount' => '0', 'symbol' => $this->primaryCurrency->symbol, - 'decimal_places' => $this->primaryCurrency->decimal_places + 'decimal_places' => $this->primaryCurrency->decimal_places, ]; $amounts[$primarySymbol]['amount'] = bcadd($amounts[$primarySymbol]['amount'], (string) $transaction['pc_amount']); } @@ -205,24 +205,24 @@ class ShowController extends Controller private function getAccounts(array $group): array { - $accounts = ['source' => [], 'destination' => []]; + $accounts = ['source' => [], 'destination' => []]; foreach ($group['transactions'] as $transaction) { - $accounts['source'][] = [ + $accounts['source'][] = [ 'type' => $transaction['source_account_type'], 'id' => $transaction['source_account_id'], 'name' => $transaction['source_account_name'], - 'iban' => $transaction['source_account_iban'] + 'iban' => $transaction['source_account_iban'], ]; $accounts['destination'][] = [ 'type' => $transaction['destination_account_type'], 'id' => $transaction['destination_account_id'], 'name' => $transaction['destination_account_name'], - 'iban' => $transaction['destination_account_iban'] + 'iban' => $transaction['destination_account_iban'], ]; } - $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR); + $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR); $accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR); return $accounts; diff --git a/app/Http/Controllers/TransactionCurrency/CreateController.php b/app/Http/Controllers/TransactionCurrency/CreateController.php index 967a9e47ba..8977be88ac 100644 --- a/app/Http/Controllers/TransactionCurrency/CreateController.php +++ b/app/Http/Controllers/TransactionCurrency/CreateController.php @@ -56,7 +56,7 @@ class CreateController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.currencies')); app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); return $next($request); @@ -71,7 +71,7 @@ class CreateController extends Controller public function create(Request $request): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); @@ -100,10 +100,10 @@ class CreateController extends Controller public function store(CurrencyFormRequest $request) { /** @var User $user */ - $user = auth()->user(); - $data = $request->getCurrencyData(); + $user = auth()->user(); + $data = $request->getCurrencyData(); if (!$this->userRepository->hasRole($user, 'owner')) { - Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.'); + Log::error('User '.auth()->user()->id.' is not admin, but tried to store a currency.'); Log::channel('audit')->warning('Tried to create (POST) currency without admin rights.', $data); return redirect($this->getPreviousUrl('currencies.create.url'))->withInput(); @@ -119,7 +119,7 @@ class CreateController extends Controller $request->session()->flash('error', (string) trans('firefly.could_not_store_currency')); $currency = null; } - $redirect = redirect($this->getPreviousUrl('currencies.create.url')); + $redirect = redirect($this->getPreviousUrl('currencies.create.url')); if ($currency instanceof TransactionCurrency) { $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name])); diff --git a/app/Http/Controllers/TransactionCurrency/DeleteController.php b/app/Http/Controllers/TransactionCurrency/DeleteController.php index 2e4b698ebd..97ba8b8eba 100644 --- a/app/Http/Controllers/TransactionCurrency/DeleteController.php +++ b/app/Http/Controllers/TransactionCurrency/DeleteController.php @@ -55,7 +55,7 @@ class DeleteController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.currencies')); app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); return $next($request); @@ -72,7 +72,7 @@ class DeleteController extends Controller public function delete(Request $request, TransactionCurrency $currency): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->warning(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code)); diff --git a/app/Http/Controllers/TransactionCurrency/EditController.php b/app/Http/Controllers/TransactionCurrency/EditController.php index 8c79dbc887..34776a77ab 100644 --- a/app/Http/Controllers/TransactionCurrency/EditController.php +++ b/app/Http/Controllers/TransactionCurrency/EditController.php @@ -54,7 +54,7 @@ class EditController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.currencies')); app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); return $next($request); @@ -69,7 +69,7 @@ class EditController extends Controller public function edit(Request $request, TransactionCurrency $currency): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->warning(sprintf('Tried to edit currency %s but is not owner.', $currency->code)); @@ -77,20 +77,21 @@ class EditController extends Controller return redirect(route('currencies.index')); } - $subTitleIcon = 'fa-pencil'; - $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]); + $subTitleIcon = 'fa-pencil'; + $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]); $currency->symbol = htmlentities($currency->symbol); // is currently enabled (for this user?) - $userCurrencies = $this->repository + $userCurrencies = $this->repository ->get() ->pluck('id') - ->toArray(); - $enabled = in_array($currency->id, $userCurrencies, true); + ->toArray() + ; + $enabled = in_array($currency->id, $userCurrencies, true); // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $preFilled = ['enabled' => $hasOldInput ? (bool) $request->old('enabled') : $enabled]; + $hasOldInput = null !== $request->old('_token'); + $preFilled = ['enabled' => $hasOldInput ? (bool) $request->old('enabled') : $enabled]; $request->session()->flash('preFilled', $preFilled); Log::channel('audit')->info('Edit currency.', $currency->toArray()); @@ -112,8 +113,8 @@ class EditController extends Controller public function update(CurrencyFormRequest $request, TransactionCurrency $currency): Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); - $data = $request->getCurrencyData(); + $user = auth()->user(); + $data = $request->getCurrencyData(); if (false === $data['enabled'] && $this->repository->currencyInUse($currency)) { $data['enabled'] = true; diff --git a/app/Http/Controllers/TransactionCurrency/IndexController.php b/app/Http/Controllers/TransactionCurrency/IndexController.php index ffd2ff5ba4..40ee7acb68 100644 --- a/app/Http/Controllers/TransactionCurrency/IndexController.php +++ b/app/Http/Controllers/TransactionCurrency/IndexController.php @@ -52,7 +52,7 @@ class IndexController extends Controller $this->middleware(function ($request, $next) { app('view')->share('title', (string) trans('firefly.currencies')); app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); return $next($request); @@ -87,7 +87,7 @@ class IndexController extends Controller $currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page); $currencies->setPath(route('currencies.index')); - $isOwner = true; + $isOwner = true; if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')])); $isOwner = false; diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 0841c78bf7..11c4b66cb7 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -64,7 +64,7 @@ class Kernel extends HttpKernel TrimStrings::class, ConvertEmptyStringsToNull::class, TrustProxies::class, - InstallationId::class + InstallationId::class, ]; protected $middlewareAliases = [ 'auth' => Authenticate::class, @@ -72,27 +72,27 @@ class Kernel extends HttpKernel 'bindings' => Binder::class, 'can' => Authorize::class, 'guest' => RedirectIfAuthenticated::class, - 'throttle' => ThrottleRequests::class + 'throttle' => ThrottleRequests::class, ]; protected $middlewareGroups = [ // does not check login // does not check 2fa // does not check activation - 'web' => [ + 'web' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartFireflySession::class, ShareErrorsFromSession::class, VerifyCsrfToken::class, AuthenticateSession::class, - CreateFreshApiToken::class + CreateFreshApiToken::class, ], // only the basic variable binders. - 'binders-only' => [Installer::class, EncryptCookies::class, AddQueuedCookiesToResponse::class, Binder::class], + 'binders-only' => [Installer::class, EncryptCookies::class, AddQueuedCookiesToResponse::class, Binder::class], // MUST NOT be logged in. Does not care about 2FA or confirmation. - 'user-not-logged-in' => [ + 'user-not-logged-in' => [ Installer::class, EncryptCookies::class, AddQueuedCookiesToResponse::class, @@ -100,7 +100,7 @@ class Kernel extends HttpKernel ShareErrorsFromSession::class, VerifyCsrfToken::class, Binder::class, - RedirectIfAuthenticated::class + RedirectIfAuthenticated::class, ], // MUST be logged in. // MUST NOT have 2FA @@ -113,28 +113,28 @@ class Kernel extends HttpKernel ShareErrorsFromSession::class, VerifyCsrfToken::class, Binder::class, - Authenticate::class + Authenticate::class, // RedirectIfTwoFactorAuthenticated::class, ], // MUST be logged in // don't care about 2fa // don't care about confirmation. - 'user-simple-auth' => [ + 'user-simple-auth' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartFireflySession::class, ShareErrorsFromSession::class, VerifyCsrfToken::class, Binder::class, - Authenticate::class + Authenticate::class, ], // MUST be logged in // MUST have 2fa // MUST be confirmed. // (this group includes the other Firefly III middleware) - 'user-full-auth' => [ + 'user-full-auth' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartFireflySession::class, @@ -145,14 +145,14 @@ class Kernel extends HttpKernel Range::class, Binder::class, InterestingMessage::class, - CreateFreshApiToken::class + CreateFreshApiToken::class, ], // MUST be logged in // MUST have 2fa // MUST be confirmed. // MUST have owner role // (this group includes the other Firefly III middleware) - 'admin' => [ + 'admin' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartFireflySession::class, @@ -163,13 +163,13 @@ class Kernel extends HttpKernel IsAdmin::class, Range::class, Binder::class, - CreateFreshApiToken::class + CreateFreshApiToken::class, ], // full API authentication - 'api' => [AcceptHeaders::class, EnsureFrontendRequestsAreStateful::class, 'auth:api,sanctum', 'bindings'], + 'api' => [AcceptHeaders::class, EnsureFrontendRequestsAreStateful::class, 'auth:api,sanctum', 'bindings'], // do only bindings, no auth - 'api_basic' => [AcceptHeaders::class, 'bindings'] + 'api_basic' => [AcceptHeaders::class, 'bindings'], ]; protected $middlewarePriority = [StartFireflySession::class, ShareErrorsFromSession::class, Authenticate::class, Binder::class, Authorize::class]; } diff --git a/app/Http/Middleware/AcceptHeaders.php b/app/Http/Middleware/AcceptHeaders.php index e441487f21..115f8dc2ba 100644 --- a/app/Http/Middleware/AcceptHeaders.php +++ b/app/Http/Middleware/AcceptHeaders.php @@ -56,10 +56,10 @@ class AcceptHeaders // if bad 'Content-Type' header, refuse service. // some routes are exempt from this. - $exempt = ['api.v1.data.bulk.transactions', 'api.v1.attachments.upload']; + $exempt = ['api.v1.data.bulk.transactions', 'api.v1.attachments.upload']; if (('POST' === $method || 'PUT' === $method) && !$request->hasHeader('Content-Type') && !in_array($request->route()->getName(), $exempt, true)) { - $error = new BadHttpHeaderException('Content-Type header cannot be empty.'); + $error = new BadHttpHeaderException('Content-Type header cannot be empty.'); $error->statusCode = 415; throw $error; @@ -69,14 +69,14 @@ class AcceptHeaders && !$this->acceptsHeader($submitted, $contentTypes) && !in_array($request->route()->getName(), $exempt, true) ) { - $error = new BadHttpHeaderException(sprintf('Content-Type cannot be "%s"', $submitted)); + $error = new BadHttpHeaderException(sprintf('Content-Type cannot be "%s"', $submitted)); $error->statusCode = 415; throw $error; } // throw bad request if trace id is not a UUID - $uuid = $request->header('X-Trace-Id'); + $uuid = $request->header('X-Trace-Id'); if (is_string($uuid) && '' !== trim($uuid) && 1 !== preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid))) { throw new BadRequestHttpException('Bad X-Trace-Id header.'); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 346e5e1316..bedb06ab67 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -124,7 +124,7 @@ class Authenticate /** * @throws AuthenticationException */ - private function validateBlockedUser(null|User $user, array $guards): void + private function validateBlockedUser(?User $user, array $guards): void { if (!$user instanceof User) { Log::warning('User is null, throw exception?'); diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index e1b938c331..a2a7bf8d2e 100644 --- a/app/Http/Middleware/InterestingMessage.php +++ b/app/Http/Middleware/InterestingMessage.php @@ -105,20 +105,20 @@ class InterestingMessage // send message about newly created transaction group. /** @var null|TransactionGroup $group */ - $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int) $transactionGroupId); + $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int) $transactionGroupId); if (null === $group) { return; } - $count = $group->transactionJournals->count(); + $count = $group->transactionJournals->count(); /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { return; } - $title = $count > 1 ? $group->title : $journal->description; + $title = $count > 1 ? $group->title : $journal->description; if ('created' === $message) { session()->flash('success_url', route('transactions.show', [$transactionGroupId])); session()->flash('success', (string) trans('firefly.stored_journal', ['description' => $title])); @@ -151,7 +151,7 @@ class InterestingMessage $message = $request->get('message'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|UserGroup $userGroup */ $userGroup = UserGroup::find($userGroupId); @@ -197,10 +197,10 @@ class InterestingMessage $message = $request->get('message'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Account $account */ - $account = $user->accounts()->withTrashed()->find($accountId); + $account = $user->accounts()->withTrashed()->find($accountId); if (null === $account) { return; @@ -232,7 +232,7 @@ class InterestingMessage $message = $request->get('message'); /** @var null|Bill $bill */ - $bill = auth()->user()->bills()->withTrashed()->find($billId); + $bill = auth()->user()->bills()->withTrashed()->find($billId); if (null === $bill) { return; @@ -261,7 +261,7 @@ class InterestingMessage $message = $request->get('message'); /** @var null|Webhook $webhook */ - $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId); + $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId); if (null === $webhook) { return; diff --git a/app/Http/Middleware/IsAdmin.php b/app/Http/Middleware/IsAdmin.php index bda0f9ae6e..2412e607b7 100644 --- a/app/Http/Middleware/IsAdmin.php +++ b/app/Http/Middleware/IsAdmin.php @@ -52,7 +52,7 @@ class IsAdmin } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index 80d9173872..147f7d7cd8 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -42,7 +42,7 @@ class IsDemoUser public function handle(Request $request, Closure $next) { /** @var null|User $user */ - $user = $request->user(); + $user = $request->user(); if (null === $user) { return $next($request); } diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index 24bdf491c4..cfad4e219b 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -77,9 +77,9 @@ class Range $viewRange = '1M'; } - $today = today(config('app.timezone')); - $start = Navigation::updateStartDate((string) $viewRange, $today); - $end = Navigation::updateEndDate((string) $viewRange, $start); + $today = today(config('app.timezone')); + $start = Navigation::updateStartDate((string) $viewRange, $today); + $end = Navigation::updateEndDate((string) $viewRange, $start); app('session')->put('start', $start); app('session')->put('end', $end); @@ -105,15 +105,15 @@ class Range private function configureView(): void { // get locale preference: - $language = Steam::getLanguage(); - $locale = Steam::getLocale(); + $language = Steam::getLanguage(); + $locale = Steam::getLocale(); App::setLocale($language); Carbon::setLocale(substr($locale, 0, 2)); - $localeArray = Steam::getLocaleArray($locale); + $localeArray = Steam::getLocaleArray($locale); setlocale(LC_TIME, $localeArray); - $moneyResult = setlocale(LC_MONETARY, $localeArray); + $moneyResult = setlocale(LC_MONETARY, $localeArray); // send error to view, if it could not set money format if (false === $moneyResult) { @@ -127,7 +127,7 @@ class Range $primaryCurrency = Amount::getPrimaryCurrency(); // also format for moment JS: - $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); + $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); app('view')->share('madMomentJS', $madMomentJS); app('view')->share('monthAndDayFormat', $monthAndDayFormat); diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 235bb5ef9c..246a9bf4a3 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -45,16 +45,16 @@ class SecureHeaders public function handle(Request $request, Closure $next) { // generate and share nonce. - $nonce = base64_encode(random_bytes(16)); + $nonce = base64_encode(random_bytes(16)); Vite::useCspNonce($nonce); if (class_exists(Debugbar::class)) { Debugbar::getJavascriptRenderer()->setCspNonce($nonce); } app('view')->share('JS_NONCE', $nonce); - $response = $next($request); - $trackingScriptSrc = $this->getTrackingScriptSource(); - $csp = [ + $response = $next($request); + $trackingScriptSrc = $this->getTrackingScriptSource(); + $csp = [ "default-src 'none'", "object-src 'none'", sprintf("script-src 'unsafe-eval' 'strict-dynamic' 'nonce-%1s'", $nonce), @@ -63,7 +63,7 @@ class SecureHeaders "font-src 'self' data:", sprintf("connect-src 'self' %s", $trackingScriptSrc), sprintf("img-src 'self' data: 'nonce-%1s' ", $nonce), - "manifest-src 'self'" + "manifest-src 'self'", ]; // overrule in development mode @@ -77,14 +77,14 @@ class SecureHeaders "font-src 'self' data: https://10.0.0.15:5173/", sprintf("connect-src 'self' %s https://10.0.0.15:5173/ wss://10.0.0.15:5173/", $trackingScriptSrc), sprintf("img-src 'self' data: 'nonce-%1s'", $nonce), - "manifest-src 'self'" + "manifest-src 'self'", ]; } - $route = $request->route(); - $customUrl = ''; - $authGuard = (string) config('firefly.authentication_guard'); - $logoutUrl = (string) config('firefly.custom_logout_url'); + $route = $request->route(); + $customUrl = ''; + $authGuard = (string) config('firefly.authentication_guard'); + $logoutUrl = (string) config('firefly.custom_logout_url'); if ('remote_user_guard' === $authGuard && '' !== $logoutUrl) { $customUrl = $logoutUrl; } @@ -93,7 +93,7 @@ class SecureHeaders $csp[] = sprintf("form-action 'self' %s", $customUrl); } - $featurePolicies = [ + $featurePolicies = [ "geolocation 'none'", "midi 'none'", // "notifications 'none'", @@ -106,7 +106,7 @@ class SecureHeaders // "speaker 'none'", // "vibrate 'none'", "fullscreen 'self'", - "payment 'none'" + "payment 'none'", ]; $disableFrameHeader = config('firefly.disable_frame_header'); diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 86741fd95c..a973d14e83 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -32,13 +32,13 @@ use Symfony\Component\HttpFoundation\Request; class TrustProxies extends Middleware { // After... - protected $headers = - Request::HEADER_X_FORWARDED_FOR - | Request::HEADER_X_FORWARDED_HOST - | Request::HEADER_X_FORWARDED_PORT - | Request::HEADER_X_FORWARDED_PROTO - | Request::HEADER_X_FORWARDED_PREFIX - | Request::HEADER_X_FORWARDED_AWS_ELB; + protected $headers + = Request::HEADER_X_FORWARDED_FOR + | Request::HEADER_X_FORWARDED_HOST + | Request::HEADER_X_FORWARDED_PORT + | Request::HEADER_X_FORWARDED_PROTO + | Request::HEADER_X_FORWARDED_PREFIX + | Request::HEADER_X_FORWARDED_AWS_ELB; /** * TrustProxies constructor. diff --git a/app/Http/Requests/AccountFormRequest.php b/app/Http/Requests/AccountFormRequest.php index cbff7df16d..78c8a18f37 100644 --- a/app/Http/Requests/AccountFormRequest.php +++ b/app/Http/Requests/AccountFormRequest.php @@ -70,7 +70,7 @@ class AccountFormRequest extends FormRequest 'interest' => $this->convertString('interest'), 'interest_period' => $this->convertString('interest_period'), 'include_net_worth' => '1', - 'liability_direction' => $this->convertString('liability_direction') + 'liability_direction' => $this->convertString('liability_direction'), ]; $data = $this->appendLocationData($data, 'location'); @@ -85,7 +85,7 @@ class AccountFormRequest extends FormRequest // that could have been selected. if ('liabilities' === $data['account_type_name']) { $data['account_type_name'] = null; - $data['account_type_id'] = $this->convertInteger('liability_type_id'); + $data['account_type_id'] = $this->convertInteger('liability_type_id'); if ('' !== $data['opening_balance']) { // opening balance is always positive for liabilities $data['opening_balance'] = Steam::positive($data['opening_balance']); @@ -112,23 +112,23 @@ class AccountFormRequest extends FormRequest 'virtual_balance' => ['nullable', new IsValidAmount()], 'currency_id' => 'exists:transaction_currencies,id', 'account_number' => 'min:1|max:255|uniqueAccountNumberForUser|nullable', - 'account_role' => 'in:' . $accountRoles, + 'account_role' => 'in:'.$accountRoles, 'active' => 'boolean', - 'cc_type' => 'in:' . $ccPaymentTypes, + 'cc_type' => 'in:'.$ccPaymentTypes, 'amount_currency_id_opening_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_virtual_balance' => 'exists:transaction_currencies,id', - 'what' => 'in:' . $types, + 'what' => 'in:'.$types, 'interest_period' => 'in:daily,monthly,yearly', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; $rules = Location::requestRules($rules); /** @var null|Account $account */ - $account = $this->route()->parameter('account'); + $account = $this->route()->parameter('account'); if (null !== $account) { // add rules: - $rules['id'] = 'belongsToUser:accounts'; - $rules['name'] = 'required|max:1024|min:1|uniqueAccountForUser:' . $account->id; + $rules['id'] = 'belongsToUser:accounts'; + $rules['name'] = 'required|max:1024|min:1|uniqueAccountForUser:'.$account->id; $rules['iban'] = ['iban', 'nullable', new UniqueIban($account, $account->accountType->type)]; } diff --git a/app/Http/Requests/BillStoreRequest.php b/app/Http/Requests/BillStoreRequest.php index a221687c9b..78f845e7cd 100644 --- a/app/Http/Requests/BillStoreRequest.php +++ b/app/Http/Requests/BillStoreRequest.php @@ -56,7 +56,7 @@ class BillStoreRequest extends FormRequest 'skip' => $this->convertInteger('skip'), 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), - 'object_group_title' => $this->convertString('object_group') + 'object_group_title' => $this->convertString('object_group'), ]; } @@ -76,7 +76,7 @@ class BillStoreRequest extends FormRequest 'extension_date' => 'nullable|date', 'repeat_freq' => sprintf('required|in:%s', implode(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', - 'active' => 'boolean' + 'active' => 'boolean', ]; } diff --git a/app/Http/Requests/BillUpdateRequest.php b/app/Http/Requests/BillUpdateRequest.php index 8ffabe5137..aa198ebdb9 100644 --- a/app/Http/Requests/BillUpdateRequest.php +++ b/app/Http/Requests/BillUpdateRequest.php @@ -57,7 +57,7 @@ class BillUpdateRequest extends FormRequest 'skip' => $this->convertInteger('skip'), 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), - 'object_group_title' => $this->convertString('object_group') + 'object_group_title' => $this->convertString('object_group'), ]; } @@ -80,7 +80,7 @@ class BillUpdateRequest extends FormRequest 'repeat_freq' => sprintf('required|in:%s', implode(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', 'active' => 'boolean', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } diff --git a/app/Http/Requests/BudgetFormStoreRequest.php b/app/Http/Requests/BudgetFormStoreRequest.php index af3386067d..012a358859 100644 --- a/app/Http/Requests/BudgetFormStoreRequest.php +++ b/app/Http/Requests/BudgetFormStoreRequest.php @@ -51,7 +51,7 @@ class BudgetFormStoreRequest extends FormRequest 'auto_budget_type' => $this->convertInteger('auto_budget_type'), 'currency_id' => $this->convertInteger('auto_budget_currency_id'), 'auto_budget_amount' => $this->convertString('auto_budget_amount'), - 'auto_budget_period' => $this->convertString('auto_budget_period') + 'auto_budget_period' => $this->convertString('auto_budget_period'), ]; } @@ -67,7 +67,7 @@ class BudgetFormStoreRequest extends FormRequest 'auto_budget_currency_id' => 'exists:transaction_currencies,id', 'auto_budget_amount' => ['required_if:auto_budget_type,1', 'required_if:auto_budget_type,2', new IsValidPositiveAmount()], 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } diff --git a/app/Http/Requests/BudgetFormUpdateRequest.php b/app/Http/Requests/BudgetFormUpdateRequest.php index 925278f5e2..536eb78871 100644 --- a/app/Http/Requests/BudgetFormUpdateRequest.php +++ b/app/Http/Requests/BudgetFormUpdateRequest.php @@ -53,7 +53,7 @@ class BudgetFormUpdateRequest extends FormRequest 'currency_id' => $this->convertInteger('auto_budget_currency_id'), 'auto_budget_amount' => $this->convertString('auto_budget_amount'), 'auto_budget_period' => $this->convertString('auto_budget_period'), - 'notes' => $this->stringWithNewlines('notes') + 'notes' => $this->stringWithNewlines('notes'), ]; } @@ -65,10 +65,10 @@ class BudgetFormUpdateRequest extends FormRequest $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name'; /** @var null|Budget $budget */ - $budget = $this->route()->parameter('budget'); + $budget = $this->route()->parameter('budget'); if (null !== $budget) { - $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name,' . $budget->id; + $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name,'.$budget->id; } return [ @@ -78,7 +78,7 @@ class BudgetFormUpdateRequest extends FormRequest 'auto_budget_currency_id' => 'exists:transaction_currencies,id', 'auto_budget_amount' => ['required_if:auto_budget_type,1', 'required_if:auto_budget_type,2|numeric', new IsValidPositiveAmount()], 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } diff --git a/app/Http/Requests/CategoryFormRequest.php b/app/Http/Requests/CategoryFormRequest.php index 20227fb9dd..73dec9f823 100644 --- a/app/Http/Requests/CategoryFormRequest.php +++ b/app/Http/Requests/CategoryFormRequest.php @@ -57,7 +57,7 @@ class CategoryFormRequest extends FormRequest $category = $this->route()->parameter('category'); if (null !== $category) { - $nameRule = 'required|min:1|max:255|uniqueObjectForUser:categories,name,' . $category->id; + $nameRule = 'required|min:1|max:255|uniqueObjectForUser:categories,name,'.$category->id; } // fixed diff --git a/app/Http/Requests/ConfigurationRequest.php b/app/Http/Requests/ConfigurationRequest.php index 04a0f0fb40..6438fa5308 100644 --- a/app/Http/Requests/ConfigurationRequest.php +++ b/app/Http/Requests/ConfigurationRequest.php @@ -40,12 +40,12 @@ class ConfigurationRequest extends FormRequest */ public function getConfigurationData(): array { - return ['single_user_mode' => $this->boolean('single_user_mode'), + return ['single_user_mode' => $this->boolean('single_user_mode'), 'enable_exchange_rates' => $this->boolean('enable_exchange_rates'), 'use_running_balance' => $this->boolean('use_running_balance'), 'enable_external_map' => $this->boolean( 'enable_external_map' ), 'enable_external_rates' => $this->boolean('enable_external_rates'), 'allow_webhooks' => $this->boolean('allow_webhooks'), - 'valid_url_protocols' => $this->string('valid_url_protocols'), 'is_demo_site' => $this->boolean('is_demo_site')]; + 'valid_url_protocols' => $this->string('valid_url_protocols'), 'is_demo_site' => $this->boolean('is_demo_site')]; } /** @@ -54,10 +54,10 @@ class ConfigurationRequest extends FormRequest public function rules(): array { // fixed - return ['single_user_mode' => 'min:0|max:1|numeric', + return ['single_user_mode' => 'min:0|max:1|numeric', 'enable_exchange_rates' => 'min:0|max:1|numeric', 'use_running_balance' => 'min:0|max:1|numeric', 'enable_external_map' => 'min:0|max:1|numeric', 'enable_external_rates' => 'min:0|max:1|numeric', 'allow_webhooks' => 'min:0|max:1|numeric', - 'valid_url_protocols' => 'min:0|max:255', 'is_demo_site' => 'min:0|max:1|numeric']; + 'valid_url_protocols' => 'min:0|max:255', 'is_demo_site' => 'min:0|max:1|numeric']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/CurrencyFormRequest.php b/app/Http/Requests/CurrencyFormRequest.php index 82a7c3b717..2e54c80483 100644 --- a/app/Http/Requests/CurrencyFormRequest.php +++ b/app/Http/Requests/CurrencyFormRequest.php @@ -48,7 +48,7 @@ class CurrencyFormRequest extends FormRequest 'code' => $this->convertString('code'), 'symbol' => $this->convertString('symbol'), 'decimal_places' => $this->convertInteger('decimal_places'), - 'enabled' => $this->boolean('enabled') + 'enabled' => $this->boolean('enabled'), ]; } @@ -58,12 +58,12 @@ class CurrencyFormRequest extends FormRequest public function rules(): array { // fixed - $rules = [ + $rules = [ 'name' => 'required|max:48|min:1|uniqueCurrencyName', 'code' => 'required|min:3|max:51|uniqueCurrencyCode', 'symbol' => 'required|min:1|max:51|uniqueCurrencySymbol', 'decimal_places' => 'required|min:0|max:12|numeric', - 'enabled' => 'in:0,1' + 'enabled' => 'in:0,1', ]; /** @var null|TransactionCurrency $currency */ @@ -75,7 +75,7 @@ class CurrencyFormRequest extends FormRequest 'code' => 'required|min:3|max:51', 'symbol' => 'required|min:1|max:51', 'decimal_places' => 'required|min:0|max:12|numeric', - 'enabled' => 'in:0,1' + 'enabled' => 'in:0,1', ]; } diff --git a/app/Http/Requests/JournalLinkRequest.php b/app/Http/Requests/JournalLinkRequest.php index 9965393c00..f3b1bcefb9 100644 --- a/app/Http/Requests/JournalLinkRequest.php +++ b/app/Http/Requests/JournalLinkRequest.php @@ -43,13 +43,13 @@ class JournalLinkRequest extends FormRequest */ public function getLinkInfo(): array { - $return = []; - $linkType = $this->get('link_type'); - $parts = explode('_', (string) $linkType); - $return['link_type_id'] = (int) $parts[0]; + $return = []; + $linkType = $this->get('link_type'); + $parts = explode('_', (string) $linkType); + $return['link_type_id'] = (int) $parts[0]; $return['transaction_journal_id'] = $this->convertInteger('opposing'); - $return['notes'] = $this->convertString('notes'); - $return['direction'] = $parts[1]; + $return['notes'] = $this->convertString('notes'); + $return['direction'] = $parts[1]; return $return; } @@ -68,7 +68,7 @@ class JournalLinkRequest extends FormRequest $combinations[] = sprintf('%d_inward', $type->id); $combinations[] = sprintf('%d_outward', $type->id); } - $string = implode(',', $combinations); + $string = implode(',', $combinations); // fixed return ['link_type' => sprintf('required|in:%s', $string), 'opposing' => 'belongsToUser:transaction_journals']; diff --git a/app/Http/Requests/LinkTypeFormRequest.php b/app/Http/Requests/LinkTypeFormRequest.php index d865d30f47..efcf6ae810 100644 --- a/app/Http/Requests/LinkTypeFormRequest.php +++ b/app/Http/Requests/LinkTypeFormRequest.php @@ -47,7 +47,7 @@ class LinkTypeFormRequest extends FormRequest $idRule = ''; // get parameter link: - $link = $this->route()->parameter('linkType'); + $link = $this->route()->parameter('linkType'); if (null !== $link) { $idRule = 'exists:link_types,id'; @@ -58,7 +58,7 @@ class LinkTypeFormRequest extends FormRequest 'id' => $idRule, 'name' => $nameRule, 'inward' => 'required|max:255|min:1|different:outward', - 'outward' => 'required|max:255|min:1|different:inward' + 'outward' => 'required|max:255|min:1|different:inward', ]; } diff --git a/app/Http/Requests/MassEditJournalRequest.php b/app/Http/Requests/MassEditJournalRequest.php index ee758ea202..c404d6c5bc 100644 --- a/app/Http/Requests/MassEditJournalRequest.php +++ b/app/Http/Requests/MassEditJournalRequest.php @@ -48,7 +48,7 @@ class MassEditJournalRequest extends FormRequest 'destination_id.*' => 'numeric|belongsToUser:accounts,id', 'journals.*' => 'numeric|belongsToUser:transaction_journals,id', 'revenue_account' => 'max:255', - 'expense_account' => 'max:255' + 'expense_account' => 'max:255', ]; } diff --git a/app/Http/Requests/NewUserFormRequest.php b/app/Http/Requests/NewUserFormRequest.php index 96dc44f82e..6544139d81 100644 --- a/app/Http/Requests/NewUserFormRequest.php +++ b/app/Http/Requests/NewUserFormRequest.php @@ -51,7 +51,7 @@ class NewUserFormRequest extends FormRequest 'credit_card_limit' => ['nullable', new IsValidAmount()], 'amount_currency_id_bank_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_savings_balance' => 'exists:transaction_currencies,id', - 'amount_currency_id_credit_card_limit' => 'exists:transaction_currencies,id' + 'amount_currency_id_credit_card_limit' => 'exists:transaction_currencies,id', ]; } diff --git a/app/Http/Requests/NotificationRequest.php b/app/Http/Requests/NotificationRequest.php index ed34eee513..9ac3569206 100644 --- a/app/Http/Requests/NotificationRequest.php +++ b/app/Http/Requests/NotificationRequest.php @@ -36,24 +36,24 @@ class NotificationRequest extends FormRequest public function getAll(): array { - $return = []; + $return = []; foreach (config('notifications.notifications.owner') as $key => $info) { - $value = false; + $value = false; if ($this->has(sprintf('notification_%s', $key))) { $value = true; } $return[$key] = $value; } - $return['slack_webhook_url'] = $this->convertString('slack_webhook_url'); + $return['slack_webhook_url'] = $this->convertString('slack_webhook_url'); - $return['pushover_app_token'] = $this->convertString('pushover_app_token'); + $return['pushover_app_token'] = $this->convertString('pushover_app_token'); $return['pushover_user_token'] = $this->convertString('pushover_user_token'); - $return['ntfy_server'] = $this->convertString('ntfy_server'); - $return['ntfy_topic'] = $this->convertString('ntfy_topic'); - $return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth')); - $return['ntfy_user'] = $this->convertString('ntfy_user'); - $return['ntfy_pass'] = $this->convertString('ntfy_pass'); + $return['ntfy_server'] = $this->convertString('ntfy_server'); + $return['ntfy_topic'] = $this->convertString('ntfy_topic'); + $return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth')); + $return['ntfy_user'] = $this->convertString('ntfy_user'); + $return['ntfy_pass'] = $this->convertString('ntfy_pass'); return $return; } @@ -67,7 +67,7 @@ class NotificationRequest extends FormRequest 'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()], 'ntfy_server' => ['nullable', 'url', 'min:1'], 'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'], - 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'] + 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'], ]; foreach (config('notifications.notifications.owner') as $key => $info) { $rules[sprintf('notification_%s', $key)] = 'in:0,1'; diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php index cf30d262c0..96b71ee02d 100644 --- a/app/Http/Requests/PiggyBankStoreRequest.php +++ b/app/Http/Requests/PiggyBankStoreRequest.php @@ -55,7 +55,7 @@ class PiggyBankStoreRequest extends FormRequest 'transaction_currency_id' => $this->convertInteger('transaction_currency_id'), 'target_date' => $this->getCarbonDate('target_date'), 'notes' => $this->stringWithNewlines('notes'), - 'object_group_title' => $this->convertString('object_group') + 'object_group_title' => $this->convertString('object_group'), ]; if (!is_array($accounts)) { $accounts = []; @@ -81,7 +81,7 @@ class PiggyBankStoreRequest extends FormRequest 'target_date' => 'date|nullable', 'order' => 'integer|min:1', 'object_group' => 'min:0|max:255', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } @@ -106,7 +106,7 @@ class PiggyBankStoreRequest extends FormRequest if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); } - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array($type, $types, true)) { $validator->errors()->add('accounts', trans('validation.invalid_account_type')); } diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.php index 8f6755523f..6e4c3adb7f 100644 --- a/app/Http/Requests/PiggyBankUpdateRequest.php +++ b/app/Http/Requests/PiggyBankUpdateRequest.php @@ -56,7 +56,7 @@ class PiggyBankUpdateRequest extends FormRequest 'target_date' => $this->getCarbonDate('target_date'), 'transaction_currency_id' => $this->convertInteger('transaction_currency_id'), 'notes' => $this->stringWithNewlines('notes'), - 'object_group_title' => $this->convertString('object_group') + 'object_group_title' => $this->convertString('object_group'), ]; if (!is_array($accounts)) { $accounts = []; @@ -86,7 +86,7 @@ class PiggyBankUpdateRequest extends FormRequest 'target_date' => 'date|nullable', 'order' => 'integer|max:32768|min:1', 'object_group' => 'min:0|max:255', - 'notes' => 'min:1|max:32768|nullable' + 'notes' => 'min:1|max:32768|nullable', ]; } @@ -110,7 +110,7 @@ class PiggyBankUpdateRequest extends FormRequest if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); } - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array($type, $types, true)) { $validator->errors()->add('accounts', trans('validation.invalid_account_type')); } diff --git a/app/Http/Requests/PreferencesRequest.php b/app/Http/Requests/PreferencesRequest.php index 120dcc8c57..ca8236c464 100644 --- a/app/Http/Requests/PreferencesRequest.php +++ b/app/Http/Requests/PreferencesRequest.php @@ -41,7 +41,7 @@ class PreferencesRequest extends FormRequest 'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()], 'ntfy_server' => ['nullable', 'url', 'min:1'], 'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'], - 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'] + 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'], ]; foreach (config('notifications.notifications.user') as $key => $info) { $rules[sprintf('notification_%s', $key)] = 'in:0,1'; diff --git a/app/Http/Requests/ProfileFormRequest.php b/app/Http/Requests/ProfileFormRequest.php index 8531582a5f..cead9e9d56 100644 --- a/app/Http/Requests/ProfileFormRequest.php +++ b/app/Http/Requests/ProfileFormRequest.php @@ -44,7 +44,7 @@ class ProfileFormRequest extends FormRequest return [ 'current_password' => 'required', 'new_password' => 'required|confirmed|secure_password|min:16', - 'new_password_confirmation' => 'required' + 'new_password_confirmation' => 'required', ]; } diff --git a/app/Http/Requests/ReconciliationStoreRequest.php b/app/Http/Requests/ReconciliationStoreRequest.php index b106f8601c..2cc1810f05 100644 --- a/app/Http/Requests/ReconciliationStoreRequest.php +++ b/app/Http/Requests/ReconciliationStoreRequest.php @@ -49,14 +49,14 @@ class ReconciliationStoreRequest extends FormRequest if (!is_array($transactions)) { $transactions = []; } - $data = [ + $data = [ 'start' => $this->getCarbonDate('start'), 'end' => $this->getCarbonDate('end'), 'start_balance' => $this->convertString('startBalance'), 'end_balance' => $this->convertString('endBalance'), 'difference' => $this->convertString('difference'), 'journals' => $transactions, - 'reconcile' => $this->convertString('reconcile') + 'reconcile' => $this->convertString('reconcile'), ]; Log::debug('In ReconciliationStoreRequest::getAll(). Will now return data.'); @@ -75,7 +75,7 @@ class ReconciliationStoreRequest extends FormRequest 'endBalance' => ['nullable', new IsValidAmount()], 'difference' => ['required', new IsValidAmount()], 'journals' => [new ValidJournals()], - 'reconcile' => 'required|in:create,nothing' + 'reconcile' => 'required|in:create,nothing', ]; } diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php index f919c0e4b5..7670bd4cea 100644 --- a/app/Http/Requests/RecurrenceFormRequest.php +++ b/app/Http/Requests/RecurrenceFormRequest.php @@ -55,8 +55,8 @@ class RecurrenceFormRequest extends FormRequest */ public function getAll(): array { - $repetitionData = $this->parseRepetitionData(); - $return = [ + $repetitionData = $this->parseRepetitionData(); + $return = [ 'recurrence' => [ 'type' => $this->convertString('transaction_type'), 'title' => $this->convertString('title'), @@ -66,7 +66,7 @@ class RecurrenceFormRequest extends FormRequest 'nr_of_repetitions' => $this->convertInteger('repetitions'), 'apply_rules' => $this->boolean('apply_rules'), 'active' => $this->boolean('active'), - 'repetition_end' => $this->convertString('repetition_end') + 'repetition_end' => $this->convertString('repetition_end'), ], 'transactions' => [[ 'currency_id' => $this->convertInteger('transaction_currency_id'), @@ -85,41 +85,41 @@ class RecurrenceFormRequest extends FormRequest 'category_name' => $this->convertString('category'), 'tags' => '' !== $this->convertString('tags') ? explode(',', $this->convertString('tags')) : [], 'piggy_bank_id' => $this->convertInteger('piggy_bank_id'), - 'piggy_bank_name' => null + 'piggy_bank_name' => null, ]], 'repetitions' => [[ 'type' => $repetitionData['type'], 'moment' => $repetitionData['moment'], 'skip' => $this->convertInteger('skip'), - 'weekend' => $this->convertInteger('weekend') - ]] + 'weekend' => $this->convertInteger('weekend'), + ]], ]; // fill in foreign currency data if (null !== $this->convertFloat('foreign_amount')) { // intentional float, used because it defaults to null. - $return['transactions'][0]['foreign_amount'] = $this->convertString('foreign_amount'); + $return['transactions'][0]['foreign_amount'] = $this->convertString('foreign_amount'); $return['transactions'][0]['foreign_currency_id'] = $this->convertInteger('foreign_currency_id'); } // default values: - $return['transactions'][0]['source_id'] = null; - $return['transactions'][0]['source_name'] = null; - $return['transactions'][0]['destination_id'] = null; + $return['transactions'][0]['source_id'] = null; + $return['transactions'][0]['source_name'] = null; + $return['transactions'][0]['destination_id'] = null; $return['transactions'][0]['destination_name'] = null; - $throwError = true; - $type = $this->convertString('transaction_type'); + $throwError = true; + $type = $this->convertString('transaction_type'); if ('withdrawal' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('withdrawal_destination_id'); } if ('deposit' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('deposit_source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('deposit_source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id'); } if ('transfer' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id'); } if ($throwError) { @@ -127,7 +127,7 @@ class RecurrenceFormRequest extends FormRequest } // replace category name with a new category: - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser(auth()->user()); /** @@ -161,15 +161,15 @@ class RecurrenceFormRequest extends FormRequest // monthly,17 // ndom,3,7 if (in_array(substr($value, 0, 6), ['yearly', 'weekly'], true)) { - $return['type'] = substr($value, 0, 6); + $return['type'] = substr($value, 0, 6); $return['moment'] = substr($value, 7); } if (str_starts_with($value, 'monthly')) { - $return['type'] = substr($value, 0, 7); + $return['type'] = substr($value, 0, 7); $return['moment'] = substr($value, 8); } if (str_starts_with($value, 'ndom')) { - $return['type'] = substr($value, 0, 4); + $return['type'] = substr($value, 0, 4); $return['moment'] = substr($value, 5); } @@ -181,20 +181,20 @@ class RecurrenceFormRequest extends FormRequest */ public function rules(): array { - $today = today(config('app.timezone')); - $tomorrow = today(config('app.timezone'))->addDay(); - $before = today(config('app.timezone'))->addYears(25); - $rules = [ + $today = today(config('app.timezone')); + $tomorrow = today(config('app.timezone'))->addDay(); + $before = today(config('app.timezone'))->addYears(25); + $rules = [ // mandatory info for recurrence. - 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', - 'first_date' => sprintf('required|date|before:%s|after:%s', $before->format('Y-m-d'), $today->format('Y-m-d')), - 'repetition_type' => ['required', new ValidRecurrenceRepetitionValue(), new ValidRecurrenceRepetitionType(), 'min:1', 'max:32'], - 'skip' => 'required|numeric|integer|gte:0|lte:31', - 'notes' => 'min:1|max:32768|nullable', + 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', + 'first_date' => sprintf('required|date|before:%s|after:%s', $before->format('Y-m-d'), $today->format('Y-m-d')), + 'repetition_type' => ['required', new ValidRecurrenceRepetitionValue(), new ValidRecurrenceRepetitionType(), 'min:1', 'max:32'], + 'skip' => 'required|numeric|integer|gte:0|lte:31', + 'notes' => 'min:1|max:32768|nullable', // optional for recurrence: - 'recurring_description' => 'min:0|max:32768', - 'active' => 'numeric|min:0|max:1', - 'apply_rules' => 'numeric|min:0|max:1', + 'recurring_description' => 'min:0|max:32768', + 'active' => 'numeric|min:0|max:1', + 'apply_rules' => 'numeric|min:0|max:1', // mandatory for transaction: 'transaction_description' => 'required|min:1|max:255', @@ -202,19 +202,19 @@ class RecurrenceFormRequest extends FormRequest 'transaction_currency_id' => 'required|exists:transaction_currencies,id', 'amount' => ['required', new IsValidPositiveAmount()], // mandatory account info: - 'source_id' => 'numeric|belongsToUser:accounts,id|nullable', - 'source_name' => 'min:1|max:255|nullable', - 'destination_id' => 'numeric|belongsToUser:accounts,id|nullable', - 'destination_name' => 'min:1|max:255|nullable', + 'source_id' => 'numeric|belongsToUser:accounts,id|nullable', + 'source_name' => 'min:1|max:255|nullable', + 'destination_id' => 'numeric|belongsToUser:accounts,id|nullable', + 'destination_name' => 'min:1|max:255|nullable', // foreign amount data: - 'foreign_amount' => ['nullable', new IsValidPositiveAmount()], + 'foreign_amount' => ['nullable', new IsValidPositiveAmount()], // optional fields: - 'budget_id' => 'mustExist:budgets,id|belongsToUser:budgets,id|nullable', - 'bill_id' => 'mustExist:bills,id|belongsToUser:bills,id|nullable', - 'category' => 'min:1|max:255|nullable', - 'tags' => 'min:1|max:255|nullable' + 'budget_id' => 'mustExist:budgets,id|belongsToUser:budgets,id|nullable', + 'bill_id' => 'mustExist:bills,id|belongsToUser:bills,id|nullable', + 'category' => 'min:1|max:255|nullable', + 'tags' => 'min:1|max:255|nullable', ]; if ($this->convertInteger('foreign_currency_id') > 0) { $rules['foreign_currency_id'] = 'exists:transaction_currencies,id'; @@ -231,22 +231,22 @@ class RecurrenceFormRequest extends FormRequest // if ends at date X, set another rule. if ('until_date' === $this->convertString('repetition_end')) { - $rules['repeat_until'] = 'required|date|after:' . $tomorrow->format('Y-m-d'); + $rules['repeat_until'] = 'required|date|after:'.$tomorrow->format('Y-m-d'); } // switch on type to expand rules for source and destination accounts: - $type = strtolower($this->convertString('transaction_type')); + $type = strtolower($this->convertString('transaction_type')); if (strtolower(TransactionTypeEnum::WITHDRAWAL->value) === $type) { - $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; + $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; $rules['destination_name'] = 'min:1|max:255|nullable'; } if (strtolower(TransactionTypeEnum::DEPOSIT->value) === $type) { - $rules['source_name'] = 'min:1|max:255|nullable'; + $rules['source_name'] = 'min:1|max:255|nullable'; $rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; } if (strtolower(TransactionTypeEnum::TRANSFER->value) === $type) { // this may not work: - $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_id'; + $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_id'; $rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:source_id'; } @@ -254,8 +254,8 @@ class RecurrenceFormRequest extends FormRequest /** @var null|Recurrence $recurrence */ $recurrence = $this->route()->parameter('recurrence'); if ($recurrence instanceof Recurrence) { - $rules['id'] = 'required|numeric|exists:recurrences,id'; - $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:recurrences,title,' . $recurrence->id; + $rules['id'] = 'required|numeric|exists:recurrences,id'; + $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:recurrences,title,'.$recurrence->id; $rules['first_date'] = 'required|date'; } @@ -293,13 +293,13 @@ class RecurrenceFormRequest extends FormRequest $accountValidator->setTransactionType($transactionType); // default values: - $sourceId = null; - $destinationId = null; + $sourceId = null; + $destinationId = null; // TODO typeOverrule: the account validator may have another opinion the transaction type. // TODO either use 'withdrawal' or the strtolower() variant, not both. - $type = $this->convertString('transaction_type'); - $throwError = true; + $type = $this->convertString('transaction_type'); + $throwError = true; if ('withdrawal' === $type) { $throwError = false; $sourceId = (int) $data['source_id']; @@ -320,7 +320,7 @@ class RecurrenceFormRequest extends FormRequest } // validate source account. - $validSource = $accountValidator->validateSource(['id' => $sourceId]); + $validSource = $accountValidator->validateSource(['id' => $sourceId]); // do something with result: if (false === $validSource) { diff --git a/app/Http/Requests/ReportFormRequest.php b/app/Http/Requests/ReportFormRequest.php index 0ce0e165f8..7db66cb0c1 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -143,7 +143,7 @@ class ReportFormRequest extends FormRequest $range = $this->get('daterange'); $parts = explode(' - ', (string) $range); if (2 === count($parts)) { - $string = $parts[1]; + $string = $parts[1]; // validate as date // if regex for YYYY-MM-DD: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][\d]|3[01])$/'; @@ -161,7 +161,7 @@ class ReportFormRequest extends FormRequest return $date; } - $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); + $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); Log::error($error); throw new FireflyException($error, 0); @@ -182,7 +182,7 @@ class ReportFormRequest extends FormRequest $range = $this->get('daterange'); $parts = explode(' - ', (string) $range); if (2 === count($parts)) { - $string = $parts[0]; + $string = $parts[0]; // validate as date // if regex for YYYY-MM-DD: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][\d]|3[01])$/'; @@ -200,7 +200,7 @@ class ReportFormRequest extends FormRequest return $date; } - $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); + $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); Log::error($error); throw new FireflyException($error, 0); diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php index 8da4c55e8c..c44fb52243 100644 --- a/app/Http/Requests/RuleFormRequest.php +++ b/app/Http/Requests/RuleFormRequest.php @@ -56,7 +56,7 @@ class RuleFormRequest extends FormRequest 'strict' => $this->boolean('strict'), 'run_after_form' => $this->boolean('run_after_form'), 'triggers' => $this->getRuleTriggerData(), - 'actions' => $this->getRuleActionData() + 'actions' => $this->getRuleActionData(), ]; } @@ -72,10 +72,10 @@ class RuleFormRequest extends FormRequest 'type' => $trigger['type'] ?? 'invalid', 'value' => $trigger['value'] ?? '', 'stop_processing' => 1 === (int) $stopProcessing, - 'prohibited' => 1 === (int) $prohibited + 'prohibited' => 1 === (int) $prohibited, ]; $set = self::replaceAmountTrigger($set); - $return[] = $set; + $return[] = $set; } } @@ -98,7 +98,7 @@ class RuleFormRequest extends FormRequest 'foreign_amount_less', 'foreign_amount_max', 'foreign_amount_more', - 'foreign_amount_min' + 'foreign_amount_min', ]; if (in_array($array['type'], $amountFields, true) && '0' === $array['value']) { $array['value'] = '0.00'; @@ -114,10 +114,10 @@ class RuleFormRequest extends FormRequest if (is_array($actionData)) { foreach ($actionData as $action) { $stopProcessing = $action['stop_processing'] ?? '0'; - $return[] = [ + $return[] = [ 'type' => $action['type'] ?? 'invalid', 'value' => $action['value'] ?? '', - 'stop_processing' => 1 === (int) $stopProcessing + 'stop_processing' => 1 === (int) $stopProcessing, ]; } } @@ -130,35 +130,35 @@ class RuleFormRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); // some actions require text (aka context): - $contextActions = implode(',', config('firefly.context-rule-actions')); + $contextActions = implode(',', config('firefly.context-rule-actions')); // some triggers require text (aka context): $contextTriggers = implode(',', $this->getTriggersWithContext()); // initial set of rules: - $rules = [ + $rules = [ 'title' => 'required|min:1|max:255|uniqueObjectForUser:rules,title', 'description' => 'min:1|max:32768|nullable', 'stop_processing' => 'boolean', 'rule_group_id' => 'required|belongsToUser:rule_groups', 'trigger' => 'required|in:store-journal,update-journal,manual-activation', - 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), + 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), 'triggers.*.value' => sprintf('required_if:triggers.*.type,%s|max:1024|min:1|ruleTriggerValue', $contextTriggers), - 'actions.*.type' => 'required|in:' . implode(',', $validActions), + 'actions.*.type' => 'required|in:'.implode(',', $validActions), 'actions.*.value' => [sprintf('required_if:actions.*.type,%s|min:0|max:1024', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], 'strict' => 'in:0,1', - 'run_after_form' => 'in:0,1' + 'run_after_form' => 'in:0,1', ]; /** @var null|Rule $rule */ - $rule = $this->route()->parameter('rule'); + $rule = $this->route()->parameter('rule'); if (null !== $rule) { - $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:rules,title,' . $rule->id; + $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:rules,title,'.$rule->id; } return $rules; diff --git a/app/Http/Requests/RuleGroupFormRequest.php b/app/Http/Requests/RuleGroupFormRequest.php index e24c00cc19..def612b105 100644 --- a/app/Http/Requests/RuleGroupFormRequest.php +++ b/app/Http/Requests/RuleGroupFormRequest.php @@ -63,7 +63,7 @@ class RuleGroupFormRequest extends FormRequest $ruleGroup = $this->route()->parameter('ruleGroup'); if (null !== $ruleGroup) { - $titleRule = 'required|min:1|max:255|uniqueObjectForUser:rule_groups,title,' . $ruleGroup->id; + $titleRule = 'required|min:1|max:255|uniqueObjectForUser:rule_groups,title,'.$ruleGroup->id; } return ['title' => $titleRule, 'description' => 'min:1|max:32768|nullable', 'active' => [new IsBoolean()]]; diff --git a/app/Http/Requests/TagFormRequest.php b/app/Http/Requests/TagFormRequest.php index a2330e02c0..ae3230f34c 100644 --- a/app/Http/Requests/TagFormRequest.php +++ b/app/Http/Requests/TagFormRequest.php @@ -49,7 +49,7 @@ class TagFormRequest extends FormRequest $data = [ 'tag' => $this->convertString('tag'), 'date' => $this->getCarbonDate('date'), - 'description' => $this->convertString('description') + 'description' => $this->convertString('description'), ]; return $this->appendLocationData($data, 'location'); @@ -60,21 +60,21 @@ class TagFormRequest extends FormRequest */ public function rules(): array { - $idRule = ''; + $idRule = ''; /** @var null|Tag $tag */ $tag = $this->route()->parameter('tag'); $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag'; if (null !== $tag) { $idRule = 'belongsToUser:tags'; - $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag,' . $tag->id; + $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag,'.$tag->id; } - $rules = [ + $rules = [ 'tag' => $tagRule, 'id' => $idRule, 'description' => 'max:32768|min:1|nullable', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', ]; return Location::requestRules($rules); diff --git a/app/Http/Requests/TestRuleFormRequest.php b/app/Http/Requests/TestRuleFormRequest.php index 4c9125025b..0526a301b1 100644 --- a/app/Http/Requests/TestRuleFormRequest.php +++ b/app/Http/Requests/TestRuleFormRequest.php @@ -47,8 +47,8 @@ class TestRuleFormRequest extends FormRequest $validTriggers = $this->getTriggers(); return [ - 'rule-trigger.*' => 'required|max:1024|min:1|in:' . implode(',', $validTriggers), - 'rule-trigger-value.*' => 'required|max:1024|min:1|ruleTriggerValue' + 'rule-trigger.*' => 'required|max:1024|min:1|in:'.implode(',', $validTriggers), + 'rule-trigger-value.*' => 'required|max:1024|min:1|ruleTriggerValue', ]; } diff --git a/app/Http/Requests/UserFormRequest.php b/app/Http/Requests/UserFormRequest.php index 4bcde99dd4..c594a30ab7 100644 --- a/app/Http/Requests/UserFormRequest.php +++ b/app/Http/Requests/UserFormRequest.php @@ -47,7 +47,7 @@ class UserFormRequest extends FormRequest 'blocked' => 1 === $this->convertInteger('blocked'), 'blocked_code' => $this->convertString('blocked_code'), 'password' => $this->convertString('password'), - 'is_owner' => 1 === $this->convertInteger('is_owner') + 'is_owner' => 1 === $this->convertInteger('is_owner'), ]; } @@ -62,7 +62,7 @@ class UserFormRequest extends FormRequest 'password' => 'confirmed|secure_password', 'blocked_code' => 'min:0|max:32|nullable', 'blocked' => 'min:0|max:1|numeric', - 'is_owner' => 'min:0|max:1|numeric' + 'is_owner' => 'min:0|max:1|numeric', ]; } diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php index 9639082839..0def88b17f 100644 --- a/app/Jobs/CreateAutoBudgetLimits.php +++ b/app/Jobs/CreateAutoBudgetLimits.php @@ -55,10 +55,10 @@ class CreateAutoBudgetLimits implements ShouldQueue /** * Create a new job instance. */ - public function __construct(null|Carbon $date) + public function __construct(?Carbon $date) { if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; Log::debug(sprintf('Created new CreateAutoBudgetLimits("%s")', $this->date->format('Y-m-d'))); @@ -119,8 +119,8 @@ class CreateAutoBudgetLimits implements ShouldQueue )); // get date range for budget limit, based on range in auto-budget - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // find budget limit: $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end); @@ -189,7 +189,7 @@ class CreateAutoBudgetLimits implements ShouldQueue throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period)); } - private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): null|BudgetLimit + private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): ?BudgetLimit { Log::debug(sprintf( 'Going to find a budget limit for budget #%d ("%s") between %s and %s', @@ -203,20 +203,20 @@ class CreateAutoBudgetLimits implements ShouldQueue return $budget->budgetlimits()->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))->first(); } - private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, null|string $amount = null): void + private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, ?string $amount = null): void { Log::debug(sprintf('No budget limit exist. Must create one for auto-budget #%d', $autoBudget->id)); if (null !== $amount) { Log::debug(sprintf('Amount is overruled and will be set to %s', $amount)); } - $budgetLimit = new BudgetLimit(); + $budgetLimit = new BudgetLimit(); $budgetLimit->budget()->associate($autoBudget->budget); $budgetLimit->transactionCurrency()->associate($autoBudget->transactionCurrency); $budgetLimit->start_date = clone $start; - $budgetLimit->end_date = clone $end; - $budgetLimit->amount = $amount ?? $autoBudget->amount; - $budgetLimit->period = $autoBudget->period; - $budgetLimit->generated = 1; + $budgetLimit->end_date = clone $end; + $budgetLimit->amount = $amount ?? $autoBudget->amount; + $budgetLimit->period = $autoBudget->period; + $budgetLimit->generated = 1; $budgetLimit->save(); Log::debug(sprintf('Created budget limit #%d.', $budgetLimit->id)); @@ -229,8 +229,8 @@ class CreateAutoBudgetLimits implements ShouldQueue { Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id)); // current period: - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // which means previous period: $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); @@ -245,7 +245,7 @@ class CreateAutoBudgetLimits implements ShouldQueue )); // has budget limit in previous period? - $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); if (!$budgetLimit instanceof BudgetLimit) { Log::debug('No budget limit exists in previous period, so create one.'); @@ -257,23 +257,23 @@ class CreateAutoBudgetLimits implements ShouldQueue } Log::debug('Budget limit exists for previous period.'); // if has one, calculate expenses and use that as a base. - $repository = app(OperationsRepositoryInterface::class); + $repository = app(OperationsRepositoryInterface::class); $repository->setUser($autoBudget->budget->user); - $spent = $repository->sumExpenses( + $spent = $repository->sumExpenses( $previousStart, $previousEnd, null, new Collection()->push($autoBudget->budget), $autoBudget->transactionCurrency ); - $currencyId = $autoBudget->transaction_currency_id; - $spentAmount = $spent[$currencyId]['sum'] ?? '0'; + $currencyId = $autoBudget->transaction_currency_id; + $spentAmount = $spent[$currencyId]['sum'] ?? '0'; Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount)); // if you spent more in previous budget period, than whatever you had previous budget period, the amount resets // previous budget limit + spent - $budgetLeft = bcadd($budgetLimit->amount, $spentAmount); - $totalAmount = $autoBudget->amount; + $budgetLeft = bcadd($budgetLimit->amount, $spentAmount); + $totalAmount = $autoBudget->amount; Log::debug(sprintf('Total amount left for previous budget period is %s', $budgetLeft)); if (-1 !== bccomp('0', $budgetLeft)) { @@ -293,12 +293,12 @@ class CreateAutoBudgetLimits implements ShouldQueue { Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id)); // current period: - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // which means previous period: - $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); - $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period); + $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); + $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period); Log::debug(sprintf( 'Current period is %s-%s, so previous period is %s-%s', @@ -309,7 +309,7 @@ class CreateAutoBudgetLimits implements ShouldQueue )); // has budget limit in previous period? - $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); if (!$budgetLimit instanceof BudgetLimit) { Log::debug('No budget limit exists in previous period, so create one.'); @@ -321,17 +321,17 @@ class CreateAutoBudgetLimits implements ShouldQueue Log::debug('Budget limit exists for previous period.'); // if has one, calculate expenses and use that as a base. - $repository = app(OperationsRepositoryInterface::class); + $repository = app(OperationsRepositoryInterface::class); $repository->setUser($autoBudget->budget->user); - $spent = $repository->sumExpenses( + $spent = $repository->sumExpenses( $previousStart, $previousEnd, null, new Collection()->push($autoBudget->budget), $autoBudget->transactionCurrency ); - $currencyId = $autoBudget->transaction_currency_id; - $spentAmount = $spent[$currencyId]['sum'] ?? '0'; + $currencyId = $autoBudget->transaction_currency_id; + $spentAmount = $spent[$currencyId]['sum'] ?? '0'; Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount)); // what you spent in previous period PLUS the amount for the current period, @@ -361,7 +361,7 @@ class CreateAutoBudgetLimits implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 7559492c1d..628d0c278f 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -69,26 +69,26 @@ class CreateRecurringTransactions implements ShouldQueue /** * Create a new job instance. */ - public function __construct(null|Carbon $date) + public function __construct(?Carbon $date) { - $newDate = new Carbon(); + $newDate = new Carbon(); $newDate->startOfDay(); - $this->date = $newDate; + $this->date = $newDate; if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); $this->journalRepository = app(JournalRepositoryInterface::class); - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - $this->force = false; - $this->submitted = 0; - $this->executed = 0; - $this->created = 0; - $this->recurrences = new Collection(); - $this->groups = new Collection(); + $this->groupRepository = app(TransactionGroupRepositoryInterface::class); + $this->force = false; + $this->submitted = 0; + $this->executed = 0; + $this->created = 0; + $this->recurrences = new Collection(); + $this->groups = new Collection(); Log::debug(sprintf('Created new CreateRecurringTransactions("%s")', $this->date->format('Y-m-d'))); } @@ -114,13 +114,13 @@ class CreateRecurringTransactions implements ShouldQueue $this->recurrences = $this->repository->getAll(); } - $result = []; - $count = $this->recurrences->count(); + $result = []; + $count = $this->recurrences->count(); $this->submitted = $count; Log::debug(sprintf('Count of collection is %d', $count)); // filter recurrences: - $filtered = $this->filterRecurrences($this->recurrences); + $filtered = $this->filterRecurrences($this->recurrences); Log::debug(sprintf('Left after filtering is %d', $filtered->count())); /** @var Recurrence $recurrence */ @@ -136,7 +136,7 @@ class CreateRecurringTransactions implements ShouldQueue Preferences::setForUser($recurrence->user, 'lastActivity', microtime()); Log::debug(sprintf('Now at recurrence #%d of user #%d', $recurrence->id, $recurrence->user_id)); - $createdReps = $this->handleRepetitions($recurrence); + $createdReps = $this->handleRepetitions($recurrence); Log::debug(sprintf('Done with recurrence #%d', $recurrence->id)); $result[$recurrence->user_id] = $result[$recurrence->user_id]->merge($createdReps); ++$this->executed; @@ -290,12 +290,12 @@ class CreateRecurringTransactions implements ShouldQueue // add two days to $this->date, so we always include the weekend. $includeWeekend = clone $this->date; $includeWeekend->addDays(2); - $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend); + $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend); unset($includeWeekend); - $result = $this->handleOccurrences($recurrence, $repetition, $occurrences); - $collection = $collection->merge($result); + $result = $this->handleOccurrences($recurrence, $repetition, $occurrences); + $collection = $collection->merge($result); } return $collection; @@ -326,7 +326,7 @@ class CreateRecurringTransactions implements ShouldQueue * @throws DuplicateTransactionException * @throws FireflyException */ - private function handleOccurrence(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): null|TransactionGroup + private function handleOccurrence(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): ?TransactionGroup { $date->startOfDay(); if ($date->ne($this->date)) { @@ -335,7 +335,7 @@ class CreateRecurringTransactions implements ShouldQueue Log::debug(sprintf('%s IS today (%s)', $date->format('Y-m-d'), $this->date->format('Y-m-d'))); // count created journals on THIS day. - $journalCount = $this->repository->getJournalCount($recurrence, $date, $date); + $journalCount = $this->repository->getJournalCount($recurrence, $date, $date); if ($journalCount > 0 && false === $this->force) { Log::info(sprintf('Already created %d journal(s) for date %s', $journalCount, $date->format('Y-m-d'))); @@ -353,11 +353,11 @@ class CreateRecurringTransactions implements ShouldQueue } // create transaction array and send to factory. - $groupTitle = null; - $count = $recurrence->recurrenceTransactions->count(); + $groupTitle = null; + $count = $recurrence->recurrenceTransactions->count(); // #8844, if there is one recurrence transaction, use the first title as the title. // #9305, if there is one recurrence transaction, group title must be NULL. - $groupTitle = null; + $groupTitle = null; // #8844, if there are more, use the recurrence transaction itself. if ($count > 1) { @@ -370,15 +370,15 @@ class CreateRecurringTransactions implements ShouldQueue return null; } - $array = [ + $array = [ 'user' => $recurrence->user, 'user_group' => $recurrence->user->userGroup, 'group_title' => $groupTitle, - 'transactions' => $this->getTransactionData($recurrence, $repetition, $date) + 'transactions' => $this->getTransactionData($recurrence, $repetition, $date), ]; /** @var TransactionGroup $group */ - $group = $this->groupRepository->store($array); + $group = $this->groupRepository->store($array); ++$this->created; Log::info(sprintf('Created new transaction group #%d', $group->id)); @@ -387,7 +387,7 @@ class CreateRecurringTransactions implements ShouldQueue $this->groups->push($group); // update recurring thing: - $recurrence->latest_date = $date; + $recurrence->latest_date = $date; $recurrence->latest_date_tz = $date->format('e'); $recurrence->save(); @@ -405,12 +405,12 @@ class CreateRecurringTransactions implements ShouldQueue $transactions = $recurrence->recurrenceTransactions()->get(); $transactions->first(); - $return = []; + $return = []; /** @var RecurrenceTransaction $transaction */ foreach ($transactions as $index => $transaction) { - $single = [ - 'type' => null === $transaction?->transactionType?->type + $single = [ + 'type' => null === $transaction?->transactionType?->type ? strtolower((string) $recurrence->transactionType->type) : strtolower($transaction->transactionType->type), // @phpstan-ignore-line 'date' => $date, @@ -443,7 +443,7 @@ class CreateRecurringTransactions implements ShouldQueue 'bill_name' => null, 'recurrence_total' => $total, 'recurrence_count' => $count, - 'recurrence_date' => $date + 'recurrence_date' => $date, ]; $return[] = $single; } @@ -453,7 +453,7 @@ class CreateRecurringTransactions implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); Log::debug(sprintf('Overruled date to "%s', $newDate->format('Y-m-d H:i:s'))); $this->date = $newDate; diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.php index 6c86be6d82..5cb878d298 100644 --- a/app/Jobs/DownloadExchangeRates.php +++ b/app/Jobs/DownloadExchangeRates.php @@ -62,17 +62,17 @@ class DownloadExchangeRates implements ShouldQueue /** * Create a new job instance. */ - public function __construct(null|Carbon $date) + public function __construct(?Carbon $date) { $this->repository = app(CurrencyRepositoryInterface::class); // get all users: /** @var UserRepositoryInterface $userRepository */ - $userRepository = app(UserRepositoryInterface::class); - $this->users = $userRepository->all(); + $userRepository = app(UserRepositoryInterface::class); + $this->users = $userRepository->all(); if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; Log::debug(sprintf('Created new DownloadExchangeRates("%s")', $this->date->format('Y-m-d'))); @@ -100,9 +100,9 @@ class DownloadExchangeRates implements ShouldQueue private function downloadRates(TransactionCurrency $currency): void { Log::debug(sprintf('Now downloading new exchange rates for currency %s.', $currency->code)); - $base = sprintf('%s/%s/%s', (string) config('cer.url'), $this->date->year, $this->date->isoWeek); - $client = new Client(); - $url = sprintf('%s/%s.json', $base, $currency->code); + $base = sprintf('%s/%s/%s', (string) config('cer.url'), $this->date->year, $this->date->isoWeek); + $client = new Client(); + $url = sprintf('%s/%s.json', $base, $currency->code); try { $res = $client->get($url); @@ -117,14 +117,14 @@ class DownloadExchangeRates implements ShouldQueue return; } - $body = (string) $res->getBody(); - $json = json_decode($body, true); + $body = (string) $res->getBody(); + $json = json_decode($body, true); if (false === $json || null === $json) { Log::warning(sprintf('Trying to grab "%s" resulted in bad JSON.', $url)); return; } - $date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone')); + $date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone')); if (!$date instanceof Carbon) { return; } @@ -145,7 +145,7 @@ class DownloadExchangeRates implements ShouldQueue } } - private function getCurrency(string $code): null|TransactionCurrency + private function getCurrency(string $code): ?TransactionCurrency { // if we have it already, don't bother searching for it again. if (array_key_exists($code, $this->active)) { @@ -154,7 +154,7 @@ class DownloadExchangeRates implements ShouldQueue return $this->active[$code]; } // find it in the database. - $currency = $this->repository->findByCode($code); + $currency = $this->repository->findByCode($code); if (!$currency instanceof TransactionCurrency) { Log::debug(sprintf('Did not find currency %s.', $code)); $this->active[$code] = null; @@ -187,7 +187,7 @@ class DownloadExchangeRates implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index 48dd43f72f..9ea86603ff 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -68,12 +68,12 @@ class MailError extends Job implements ShouldQueue */ public function handle(): void { - $email = (string) config('firefly.site_owner'); - $args = $this->exception; + $email = (string) config('firefly.site_owner'); + $args = $this->exception; $args['loggedIn'] = $this->userData['id'] > 0; - $args['user'] = $this->userData; - $args['ip'] = $this->ipAddress; - $args['token'] = config('firefly.ipinfo_token'); + $args['user'] = $this->userData; + $args['ip'] = $this->ipAddress; + $args['token'] = config('firefly.ipinfo_token'); // limit number of error mails that can be sent. if ($this->reachedLimit()) { @@ -113,7 +113,7 @@ class MailError extends Job implements ShouldQueue $types = [ '5m' => ['limit' => 5, 'reset' => 5 * 60], '1h' => ['limit' => 15, 'reset' => 60 * 60], - '24h' => ['limit' => 15, 'reset' => 24 * 60 * 60] + '24h' => ['limit' => 15, 'reset' => 24 * 60 * 60], ]; $file = storage_path('framework/cache/error-count.json'); $directory = storage_path('framework/cache'); diff --git a/app/Jobs/WarnAboutBills.php b/app/Jobs/WarnAboutBills.php index b4bfa063bb..46a48c7afc 100644 --- a/app/Jobs/WarnAboutBills.php +++ b/app/Jobs/WarnAboutBills.php @@ -54,14 +54,14 @@ class WarnAboutBills implements ShouldQueue /** * Create a new job instance. */ - public function __construct(null|Carbon $date) + public function __construct(?Carbon $date) { - $newDate = new Carbon(); + $newDate = new Carbon(); $newDate->startOfDay(); - $this->date = $newDate; + $this->date = $newDate; if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } @@ -147,7 +147,7 @@ class WarnAboutBills implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } @@ -169,14 +169,14 @@ class WarnAboutBills implements ShouldQueue $enrichment->setEnd($end); /** @var Bill $single */ - $single = $enrichment->enrichSingle($bill); + $single = $enrichment->enrichSingle($bill); return ['pay_dates' => $single->meta['pay_dates'] ?? [], 'paid_dates' => $single->meta['paid_dates'] ?? []]; } private function needsOverdueAlert(array $dates): bool { - $count = count($dates['pay_dates']) - count($dates['paid_dates']); + $count = count($dates['pay_dates']) - count($dates['paid_dates']); if (0 === $count || 0 === count($dates['pay_dates'])) { return false; } @@ -184,7 +184,7 @@ class WarnAboutBills implements ShouldQueue $earliest = new Carbon($dates['pay_dates'][0]); $earliest->startOfDay(); Log::debug(sprintf('Earliest expected pay date is %s', $earliest->toAtomString())); - $diff = $earliest->diffInDays($this->date); + $diff = $earliest->diffInDays($this->date); Log::debug(sprintf('Difference in days is %s', $diff)); return $diff >= 6; // FIXME hard coded value. diff --git a/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php b/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php index 31ae67768c..15a856af8e 100644 --- a/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php +++ b/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php @@ -39,7 +39,7 @@ class CreatesPiggyBankEventForChangedAmount implements ShouldQueue if ($event->transactionGroup instanceof TransactionGroup) { $journal = $event->transactionGroup->transactionJournals()->first(); } - $date = $journal->date ?? today(config('app.timezone')); + $date = $journal->date ?? today(config('app.timezone')); // sanity check: event must not already exist for this journal and piggy bank. if (null !== $journal) { $exists = PiggyBankEvent::where('piggy_bank_id', $event->piggyBank->id)->where('transaction_journal_id', $journal->id)->exists(); @@ -55,7 +55,7 @@ class CreatesPiggyBankEventForChangedAmount implements ShouldQueue 'transaction_journal_id' => $journal?->id, 'date' => $date->format('Y-m-d'), 'date_tz' => $date->format('e'), - 'amount' => $event->amount + 'amount' => $event->amount, ]); } } diff --git a/app/Listeners/Model/Rule/NotifiesUserAboutFailedRuleAction.php b/app/Listeners/Model/Rule/NotifiesUserAboutFailedRuleAction.php index dc1648fbfe..ad01387162 100644 --- a/app/Listeners/Model/Rule/NotifiesUserAboutFailedRuleAction.php +++ b/app/Listeners/Model/Rule/NotifiesUserAboutFailedRuleAction.php @@ -37,21 +37,21 @@ class NotifiesUserAboutFailedRuleAction implements ShouldQueue { public function handle(RuleActionFailedOnArray|RuleActionFailedOnObject $event): void { - $ruleAction = $event->ruleAction; - $rule = $ruleAction->rule; + $ruleAction = $event->ruleAction; + $rule = $ruleAction->rule; /** @var bool $preference */ - $preference = Preferences::getForUser($rule->user, 'notification_rule_action_failures', true)->data; + $preference = Preferences::getForUser($rule->user, 'notification_rule_action_failures', true)->data; if (false === $preference) { return; } Log::debug('Now in ruleActionFailedOnArray'); - $journal = $event->journal; - $error = $event->error; - $user = $ruleAction->rule->user; + $journal = $event->journal; + $error = $event->error; + $user = $ruleAction->rule->user; - $groupId = is_array($journal) ? $journal['transaction_group_id'] : $journal->transaction_group_id; - $groupTitle = is_array($journal) ? $journal['description'] ?? '' : $journal->description ?? ''; + $groupId = is_array($journal) ? $journal['transaction_group_id'] : $journal->transaction_group_id; + $groupTitle = is_array($journal) ? $journal['description'] ?? '' : $journal->description ?? ''; $mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $groupId, 'error' => $error]); $groupLink = route('transactions.show', [$groupId]); diff --git a/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php b/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php index 74148cf9bd..83e47b250d 100644 --- a/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php +++ b/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php @@ -40,7 +40,7 @@ class NotifiesAboutExtensionOrRenewal implements ShouldQueue $subscription = $event->subscription; /** @var bool $preference */ - $preference = Preferences::getForUser($subscription->user, 'notification_bill_reminder', true)->data; + $preference = Preferences::getForUser($subscription->user, 'notification_bill_reminder', true)->data; if (true === $preference) { Log::debug('Subscription reminder is true!'); diff --git a/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php b/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php index d9f8609c96..dff98da630 100644 --- a/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php +++ b/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php @@ -39,15 +39,15 @@ class NotifiesAboutOverdueSubscriptions implements ShouldQueue { Log::debug(sprintf('Now in %s', __METHOD__)); // make sure user does not get the warning twice. - $overdue = $event->overdue; - $user = $event->user; - $toBeWarned = []; + $overdue = $event->overdue; + $user = $event->user; + $toBeWarned = []; Log::debug(sprintf('%d subscriptions to warn about.', count($overdue))); foreach ($overdue as $item) { /** @var Bill $bill */ - $bill = $item['bill']; - $key = sprintf('bill_overdue_%s_%s', $bill->id, substr(hash('sha256', json_encode($item['dates']['pay_dates'], JSON_THROW_ON_ERROR)), 0, 10)); - $pref = Preferences::getForUser($bill->user, $key, false); + $bill = $item['bill']; + $key = sprintf('bill_overdue_%s_%s', $bill->id, substr(hash('sha256', json_encode($item['dates']['pay_dates'], JSON_THROW_ON_ERROR)), 0, 10)); + $pref = Preferences::getForUser($bill->user, $key, false); if (true === $pref->data) { Log::debug(sprintf('User #%d has already been warned about overdue subscription #%d.', $bill->user->id, $bill->id)); diff --git a/app/Listeners/Security/System/HandlesNewUserRegistration.php b/app/Listeners/Security/System/HandlesNewUserRegistration.php index 8bf796522d..85c48f5ed5 100644 --- a/app/Listeners/Security/System/HandlesNewUserRegistration.php +++ b/app/Listeners/Security/System/HandlesNewUserRegistration.php @@ -69,12 +69,12 @@ class HandlesNewUserRegistration */ private function createGroupMembership(User $user): void { - $groupExists = true; - $groupTitle = $user->email; - $index = 1; + $groupExists = true; + $groupTitle = $user->email; + $index = 1; /** @var null|UserGroup $group */ - $group = null; + $group = null; // create a new group. while ($groupExists) { // @phpstan-ignore-line @@ -84,7 +84,7 @@ class HandlesNewUserRegistration break; } - $groupTitle = sprintf('%s-%d', $user->email, $index); + $groupTitle = sprintf('%s-%d', $user->email, $index); ++$index; if ($index > 99) { throw new FireflyException('Email address can no longer be used for registrations.'); @@ -92,7 +92,7 @@ class HandlesNewUserRegistration } /** @var null|UserRole $role */ - $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); + $role = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); if (null === $role) { throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); } @@ -116,6 +116,7 @@ class HandlesNewUserRegistration if (!$sendMail) { return; } + try { Notification::send($owner, new AdminRegistrationNotification($user)); } catch (Exception $e) { @@ -141,6 +142,7 @@ class HandlesNewUserRegistration if (!$sendMail) { return; } + try { Notification::send($user, new UserRegistrationNotification()); } catch (Exception $e) { diff --git a/app/Listeners/Security/User/StoresNewIpAddress.php b/app/Listeners/Security/User/StoresNewIpAddress.php index 2d31a6e020..952ab8a83e 100644 --- a/app/Listeners/Security/User/StoresNewIpAddress.php +++ b/app/Listeners/Security/User/StoresNewIpAddress.php @@ -35,13 +35,14 @@ class StoresNewIpAddress public function handle(UserSuccessfullyLoggedIn $event): void { Log::debug('Now in storeUserIPAddress'); - $user = $event->user; + $user = $event->user; if ($user->hasRole('demo')) { Log::debug('Do not log demo user logins'); return; } + /** @var array $preference */ $preference = Preferences::getForUser($user, 'login_ip_history', [])->data; $inArray = false; @@ -53,7 +54,7 @@ class StoresNewIpAddress if ($row['ip'] === $ip) { Log::debug('Found IP in array, refresh time.'); $preference[$index]['time'] = now(config('app.timezone'))->format('Y-m-d H:i:s'); - $inArray = true; + $inArray = true; } // clean up old entries (6 months) $carbon = Carbon::createFromFormat('Y-m-d H:i:s', $preference[$index]['time']); @@ -69,7 +70,7 @@ class StoresNewIpAddress $preference = array_values($preference); /** @var bool $send */ - $send = Preferences::getForUser($user, 'notification_user_login', true)->data; + $send = Preferences::getForUser($user, 'notification_user_login', true)->data; Preferences::setForUser($user, 'login_ip_history', $preference); if (false === $inArray && true === $send) { diff --git a/app/Listeners/Test/SendsTestNotification.php b/app/Listeners/Test/SendsTestNotification.php index 0a3fcc958e..21504285eb 100644 --- a/app/Listeners/Test/SendsTestNotification.php +++ b/app/Listeners/Test/SendsTestNotification.php @@ -44,25 +44,38 @@ class SendsTestNotification $type = str_contains(get_class($event), 'Owner') ? 'owner' : 'user'; $key = sprintf('%s-%s', $type, $event->channel); + switch ($key) { case 'user-email': $class = UserTestNotificationEmail::class; + break; + case 'user-slack': $class = UserTestNotificationSlack::class; + break; + case 'user-pushover': $class = UserTestNotificationPushover::class; + break; + case 'owner-email': $class = OwnerTestNotificationEmail::class; + break; + case 'owner-slack': $class = OwnerTestNotificationSlack::class; + break; + case 'owner-pushover': $class = OwnerTestNotificationPushover::class; + break; + default: Log::error(sprintf('Unknown key "%s" in sendTestNotification method.', $key)); diff --git a/app/Mail/ConfirmEmailChangeMail.php b/app/Mail/ConfirmEmailChangeMail.php index 7f5a99aa2f..df5c4381b0 100644 --- a/app/Mail/ConfirmEmailChangeMail.php +++ b/app/Mail/ConfirmEmailChangeMail.php @@ -57,6 +57,7 @@ class ConfirmEmailChangeMail extends Mailable // ->view('emails.confirm-email-change-html') // ->text('emails.confirm-email-change-text') ->markdown('emails.confirm-email-change') - ->subject((string) trans('email.email_change_subject')); + ->subject((string) trans('email.email_change_subject')) + ; } } diff --git a/app/Mail/InvitationMail.php b/app/Mail/InvitationMail.php index ca7951f301..eca3252c44 100644 --- a/app/Mail/InvitationMail.php +++ b/app/Mail/InvitationMail.php @@ -48,7 +48,7 @@ class InvitationMail extends Mailable public string $admin, public string $url ) { - $host = parse_url($this->url, PHP_URL_HOST); + $host = parse_url($this->url, PHP_URL_HOST); if (is_array($host)) { $host = ''; } diff --git a/app/Models/Account.php b/app/Models/Account.php index c6d6e30440..13e71b4f55 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -50,9 +50,9 @@ class Account extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance']; + protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; private bool $joinedAccountTypes = false; /** @@ -66,10 +66,10 @@ class Account extends Model $accountId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Account $account */ - $account = $user->accounts()->with(['accountType'])->find($accountId); + $account = $user->accounts()->with(['accountType'])->find($accountId); if (null !== $account) { return $account; } @@ -126,7 +126,7 @@ class Account extends Model public function setVirtualBalanceAttribute(mixed $value): void { - $value = (string) $value; + $value = (string) $value; if ('' === $value) { $value = null; } @@ -145,7 +145,7 @@ class Account extends Model protected function accountId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** @@ -171,7 +171,7 @@ class Account extends Model */ protected function accountTypeId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } #[Scope] @@ -195,7 +195,7 @@ class Account extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'virtual_balance' => 'string', - 'native_virtual_balance' => 'string' + 'native_virtual_balance' => 'string', ]; } @@ -213,12 +213,12 @@ class Account extends Model protected function iban(): Attribute { - return Attribute::make(get: static fn($value): null|string => null === $value ? null : trim(str_replace(' ', '', (string) $value))); + return Attribute::make(get: static fn ($value): ?string => null === $value ? null : trim(str_replace(' ', '', (string) $value))); } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** @@ -226,7 +226,7 @@ class Account extends Model */ protected function virtualBalance(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } public function primaryPeriodStatistics(): MorphMany diff --git a/app/Models/AccountMeta.php b/app/Models/AccountMeta.php index cea01fb792..a67267f204 100644 --- a/app/Models/AccountMeta.php +++ b/app/Models/AccountMeta.php @@ -51,8 +51,8 @@ class AccountMeta extends Model protected function data(): Attribute { return Attribute::make( - get: static fn(mixed $value): string => (string) json_decode((string) $value, true), - set: static fn(mixed $value): array => ['data' => json_encode($value)] + get: static fn (mixed $value): string => (string) json_decode((string) $value, true), + set: static fn (mixed $value): array => ['data' => json_encode($value)] ); } } diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php index 1d80a53546..f7d7b9bdec 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -34,39 +34,39 @@ class AccountType extends Model /** @deprecated */ #[Deprecated] - public const string ASSET = 'Asset account'; + public const string ASSET = 'Asset account'; /** @deprecated */ #[Deprecated] - public const string BENEFICIARY = 'Beneficiary account'; + public const string BENEFICIARY = 'Beneficiary account'; /** @deprecated */ #[Deprecated] - public const string CASH = 'Cash account'; + public const string CASH = 'Cash account'; /** @deprecated */ #[Deprecated] - public const string CREDITCARD = 'Credit card'; + public const string CREDITCARD = 'Credit card'; /** @deprecated */ #[Deprecated] - public const string DEBT = 'Debt'; + public const string DEBT = 'Debt'; /** @deprecated */ #[Deprecated] - public const string DEFAULT = 'Default account'; + public const string DEFAULT = 'Default account'; /** @deprecated */ #[Deprecated] - public const string EXPENSE = 'Expense account'; + public const string EXPENSE = 'Expense account'; /** @deprecated */ #[Deprecated] - public const string IMPORT = 'Import account'; + public const string IMPORT = 'Import account'; /** @deprecated */ #[Deprecated] - public const string INITIAL_BALANCE = 'Initial balance account'; + public const string INITIAL_BALANCE = 'Initial balance account'; /** @deprecated */ #[Deprecated] @@ -74,23 +74,23 @@ class AccountType extends Model /** @deprecated */ #[Deprecated] - public const string LOAN = 'Loan'; + public const string LOAN = 'Loan'; /** @deprecated */ #[Deprecated] - public const string MORTGAGE = 'Mortgage'; + public const string MORTGAGE = 'Mortgage'; /** @deprecated */ #[Deprecated] - public const string RECONCILIATION = 'Reconciliation account'; + public const string RECONCILIATION = 'Reconciliation account'; /** @deprecated */ #[Deprecated] - public const string REVENUE = 'Revenue account'; + public const string REVENUE = 'Revenue account'; - protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime']; + protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime']; - protected $fillable = ['type']; + protected $fillable = ['type']; public function accounts(): HasMany { diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php index bbb2dfa145..18431fbb77 100644 --- a/app/Models/Attachment.php +++ b/app/Models/Attachment.php @@ -54,7 +54,7 @@ class Attachment extends Model 'title', 'description', 'size', - 'uploaded' + 'uploaded', ]; /** @@ -68,10 +68,10 @@ class Attachment extends Model $attachmentId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Attachment $attachment */ - $attachment = $user->attachments()->find($attachmentId); + $attachment = $user->attachments()->find($attachmentId); if (null !== $attachment) { return $attachment; } @@ -111,7 +111,7 @@ class Attachment extends Model protected function attachableId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function casts(): array @@ -122,7 +122,7 @@ class Attachment extends Model 'deleted_at' => 'datetime', 'uploaded' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } } diff --git a/app/Models/AuditLogEntry.php b/app/Models/AuditLogEntry.php index 31019cb5bc..300c01911f 100644 --- a/app/Models/AuditLogEntry.php +++ b/app/Models/AuditLogEntry.php @@ -47,7 +47,7 @@ class AuditLogEntry extends Model protected function auditableId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function casts(): array @@ -57,6 +57,6 @@ class AuditLogEntry extends Model protected function changerId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/AutoBudget.php b/app/Models/AutoBudget.php index aa827786e9..eb01aa96d1 100644 --- a/app/Models/AutoBudget.php +++ b/app/Models/AutoBudget.php @@ -45,14 +45,14 @@ class AutoBudget extends Model /** @deprecated */ #[Deprecated] - public const int AUTO_BUDGET_RESET = 1; + public const int AUTO_BUDGET_RESET = 1; /** @deprecated */ #[Deprecated] public const int AUTO_BUDGET_ROLLOVER = 2; - protected $casts = ['amount' => 'string', 'native_amount' => 'string']; - protected $fillable = ['budget_id', 'amount', 'period', 'native_amount']; + protected $casts = ['amount' => 'string', 'native_amount' => 'string']; + protected $fillable = ['budget_id', 'amount', 'period', 'native_amount']; public function budget(): BelongsTo { @@ -66,12 +66,12 @@ class AutoBudget extends Model protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function budgetId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function casts(): array @@ -83,6 +83,6 @@ class AutoBudget extends Model protected function transactionCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/AvailableBudget.php b/app/Models/AvailableBudget.php index db06c14b7a..2428a029f5 100644 --- a/app/Models/AvailableBudget.php +++ b/app/Models/AvailableBudget.php @@ -51,7 +51,7 @@ class AvailableBudget extends Model 'end_date', 'start_date_tz', 'end_date_tz', - 'native_amount' + 'native_amount', ]; /** @@ -65,10 +65,10 @@ class AvailableBudget extends Model $availableBudgetId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $user->availableBudgets()->find($availableBudgetId); + $availableBudget = $user->availableBudgets()->find($availableBudgetId); if (null !== $availableBudget) { return $availableBudget; } @@ -89,7 +89,7 @@ class AvailableBudget extends Model protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function casts(): array @@ -104,28 +104,28 @@ class AvailableBudget extends Model 'amount' => 'string', 'native_amount' => 'string', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function endDate(): Attribute { return Attribute::make( - get: static fn(string $value): Carbon => Carbon::parse($value), - set: static fn(Carbon $value): string => $value->format('Y-m-d') + get: static fn (string $value): Carbon => Carbon::parse($value), + set: static fn (Carbon $value): string => $value->format('Y-m-d') ); } protected function startDate(): Attribute { return Attribute::make( - get: static fn(string $value): Carbon => Carbon::parse($value), - set: static fn(Carbon $value): string => $value->format('Y-m-d') + get: static fn (string $value): Carbon => Carbon::parse($value), + set: static fn (Carbon $value): string => $value->format('Y-m-d') ); } protected function transactionCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Bill.php b/app/Models/Bill.php index 5e40c718bb..4b56656755 100644 --- a/app/Models/Bill.php +++ b/app/Models/Bill.php @@ -64,10 +64,10 @@ class Bill extends Model 'end_date_tz', 'extension_date_tz', 'native_amount_min', - 'native_amount_max' + 'native_amount_max', ]; - protected $hidden = ['amount_min_encrypted', 'amount_max_encrypted', 'name_encrypted', 'match_encrypted']; + protected $hidden = ['amount_min_encrypted', 'amount_max_encrypted', 'name_encrypted', 'match_encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -80,10 +80,10 @@ class Bill extends Model $billId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Bill $bill */ - $bill = $user->bills()->find($billId); + $bill = $user->bills()->find($billId); if (null !== $bill) { return $bill; } @@ -149,7 +149,7 @@ class Bill extends Model */ protected function amountMax(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } /** @@ -157,7 +157,7 @@ class Bill extends Model */ protected function amountMin(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function casts(): array @@ -177,13 +177,13 @@ class Bill extends Model 'amount_min' => 'string', 'amount_max' => 'string', 'native_amount_min' => 'string', - 'native_amount_max' => 'string' + 'native_amount_max' => 'string', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** @@ -191,11 +191,11 @@ class Bill extends Model */ protected function skip(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function transactionCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Budget.php b/app/Models/Budget.php index f11b96c13d..c6db07669f 100644 --- a/app/Models/Budget.php +++ b/app/Models/Budget.php @@ -46,7 +46,7 @@ class Budget extends Model protected $fillable = ['user_id', 'user_group_id', 'name', 'active', 'order', 'user_group_id']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -59,10 +59,10 @@ class Budget extends Model $budgetId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Budget $budget */ - $budget = $user->budgets()->find($budgetId); + $budget = $user->budgets()->find($budgetId); if (null !== $budget) { return $budget; } @@ -118,13 +118,13 @@ class Budget extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } public function primaryPeriodStatistics(): MorphMany diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php index c76cf1b849..81acb6ce38 100644 --- a/app/Models/BudgetLimit.php +++ b/app/Models/BudgetLimit.php @@ -60,7 +60,8 @@ class BudgetLimit extends Model $budgetLimit = self::where('budget_limits.id', $budgetLimitId) ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->where('budgets.user_id', auth()->user()->id) - ->first(['budget_limits.*']); + ->first(['budget_limits.*']) + ; if (null !== $budgetLimit) { return $budgetLimit; } @@ -92,12 +93,12 @@ class BudgetLimit extends Model */ protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function budgetId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function casts(): array @@ -109,12 +110,12 @@ class BudgetLimit extends Model 'end_date' => SeparateTimezoneCaster::class, 'auto_budget' => 'boolean', 'amount' => 'string', - 'native_amount' => 'string' + 'native_amount' => 'string', ]; } protected function transactionCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Category.php b/app/Models/Category.php index 5494fb06af..7a3f13bde7 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -45,7 +45,7 @@ class Category extends Model protected $fillable = ['user_id', 'user_group_id', 'name']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -58,10 +58,10 @@ class Category extends Model $categoryId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Category $category */ - $category = $user->categories()->find($categoryId); + $category = $user->categories()->find($categoryId); if (null !== $category) { return $category; } @@ -106,7 +106,7 @@ class Category extends Model 'deleted_at' => 'datetime', 'encrypted' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php index 0ae972e12c..9495e5c5d4 100644 --- a/app/Models/Configuration.php +++ b/app/Models/Configuration.php @@ -48,6 +48,6 @@ class Configuration extends Model */ protected function data(): Attribute { - return Attribute::make(get: static fn($value): mixed => json_decode((string) $value), set: static fn($value): array => ['data' => json_encode($value)]); + return Attribute::make(get: static fn ($value): mixed => json_decode((string) $value), set: static fn ($value): array => ['data' => json_encode($value)]); } } diff --git a/app/Models/CurrencyExchangeRate.php b/app/Models/CurrencyExchangeRate.php index eb9472c533..4f79c70d03 100644 --- a/app/Models/CurrencyExchangeRate.php +++ b/app/Models/CurrencyExchangeRate.php @@ -66,27 +66,27 @@ class CurrencyExchangeRate extends Model 'to_currency_id' => 'integer', 'date' => SeparateTimezoneCaster::class, 'rate' => 'string', - 'user_rate' => 'string' + 'user_rate' => 'string', ]; } protected function fromCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function rate(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function toCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function userRate(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } } diff --git a/app/Models/GroupMembership.php b/app/Models/GroupMembership.php index 365bc28944..00e8facf45 100644 --- a/app/Models/GroupMembership.php +++ b/app/Models/GroupMembership.php @@ -60,6 +60,6 @@ class GroupMembership extends Model protected function userRoleId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/InvitedUser.php b/app/Models/InvitedUser.php index 3ee792e92c..b6641989cd 100644 --- a/app/Models/InvitedUser.php +++ b/app/Models/InvitedUser.php @@ -48,7 +48,7 @@ class InvitedUser extends Model $attemptId = (int) $value; /** @var null|InvitedUser $attempt */ - $attempt = self::find($attemptId); + $attempt = self::find($attemptId); if (null !== $attempt) { return $attempt; } diff --git a/app/Models/Location.php b/app/Models/Location.php index 4ed86a0dcb..20e5bf767e 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -41,8 +41,8 @@ class Location extends Model */ public static function requestRules(array $rules): array { - $rules['latitude'] = 'numeric|min:-90|max:90|nullable|required_with:longitude'; - $rules['longitude'] = 'numeric|min:-180|max:180|nullable|required_with:latitude'; + $rules['latitude'] = 'numeric|min:-90|max:90|nullable|required_with:longitude'; + $rules['longitude'] = 'numeric|min:-180|max:180|nullable|required_with:latitude'; $rules['zoom_level'] = 'numeric|min:0|max:80|nullable|required_with:latitude'; return $rules; @@ -74,12 +74,12 @@ class Location extends Model 'deleted_at' => 'datetime', 'zoomLevel' => 'int', 'latitude' => 'float', - 'longitude' => 'float' + 'longitude' => 'float', ]; } protected function locatableId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Note.php b/app/Models/Note.php index 8c739a4580..84e0ade67f 100644 --- a/app/Models/Note.php +++ b/app/Models/Note.php @@ -51,6 +51,6 @@ class Note extends Model protected function noteableId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/ObjectGroup.php b/app/Models/ObjectGroup.php index b7961d1e8a..be4b5f6033 100644 --- a/app/Models/ObjectGroup.php +++ b/app/Models/ObjectGroup.php @@ -51,7 +51,7 @@ class ObjectGroup extends Model $objectGroupId = (int) $value; /** @var null|ObjectGroup $objectGroup */ - $objectGroup = self::where('object_groups.id', $objectGroupId)->where('object_groups.user_id', auth()->user()->id)->first(); + $objectGroup = self::where('object_groups.id', $objectGroupId)->where('object_groups.user_id', auth()->user()->id)->first(); if (null !== $objectGroup) { return $objectGroup; } @@ -96,12 +96,12 @@ class ObjectGroup extends Model 'updated_at' => 'datetime', 'user_id' => 'integer', 'user_group_id' => 'integer', - 'deleted_at' => 'datetime' + 'deleted_at' => 'datetime', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/PeriodStatistic.php b/app/Models/PeriodStatistic.php index 145c208f82..9a9e9d158b 100644 --- a/app/Models/PeriodStatistic.php +++ b/app/Models/PeriodStatistic.php @@ -21,7 +21,7 @@ class PeriodStatistic extends Model 'created_at' => 'datetime', 'updated_at' => 'datetime', 'start' => SeparateTimezoneCaster::class, - 'end' => SeparateTimezoneCaster::class + 'end' => SeparateTimezoneCaster::class, ]; } @@ -32,7 +32,7 @@ class PeriodStatistic extends Model protected function count(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } public function primaryStatable(): MorphTo diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index c8429d5f0c..a03d61d7ca 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -52,7 +52,7 @@ class PiggyBank extends Model 'target_date_tz', 'active', 'transaction_currency_id', - 'native_target_amount' + 'native_target_amount', ]; /** @@ -68,7 +68,8 @@ class PiggyBank extends Model ->leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', auth()->user()->id) - ->first(['piggy_banks.*']); + ->first(['piggy_banks.*']) + ; if (null !== $piggyBank) { return $piggyBank; } @@ -133,7 +134,7 @@ class PiggyBank extends Model protected function accountId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function casts(): array @@ -148,13 +149,13 @@ class PiggyBank extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'target_amount' => 'string', - 'native_target_amount' => 'string' + 'native_target_amount' => 'string', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** @@ -162,6 +163,6 @@ class PiggyBank extends Model */ protected function targetAmount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } } diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index 9208d8a829..278007d2c0 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -38,7 +38,7 @@ class PiggyBankEvent extends Model protected $fillable = ['piggy_bank_id', 'transaction_journal_id', 'date', 'date_tz', 'amount', 'native_amount']; - protected $hidden = ['amount_encrypted']; + protected $hidden = ['amount_encrypted']; public function piggyBank(): BelongsTo { @@ -63,7 +63,7 @@ class PiggyBankEvent extends Model */ protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function casts(): array @@ -73,12 +73,12 @@ class PiggyBankEvent extends Model 'updated_at' => 'datetime', 'date' => SeparateTimezoneCaster::class, 'amount' => 'string', - 'native_amount' => 'string' + 'native_amount' => 'string', ]; } protected function piggyBankId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php index 20127d3d6d..e229c00096 100644 --- a/app/Models/PiggyBankRepetition.php +++ b/app/Models/PiggyBankRepetition.php @@ -58,7 +58,7 @@ class PiggyBankRepetition extends Model 'updated_at' => 'datetime', 'start_date' => SeparateTimezoneCaster::class, 'target_date' => SeparateTimezoneCaster::class, - 'virtual_balance' => 'string' + 'virtual_balance' => 'string', ]; } @@ -67,7 +67,7 @@ class PiggyBankRepetition extends Model */ protected function currentAmount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } #[Scope] @@ -78,7 +78,7 @@ class PiggyBankRepetition extends Model protected function piggyBankId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** diff --git a/app/Models/Preference.php b/app/Models/Preference.php index a7a6a5297f..0e282cf1a5 100644 --- a/app/Models/Preference.php +++ b/app/Models/Preference.php @@ -46,7 +46,7 @@ class Preference extends Model { if (auth()->check()) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // some preferences do not have an administration ID. // some need it, to make sure the correct one is selected. @@ -54,8 +54,8 @@ class Preference extends Model $userGroupId = 0 === $userGroupId ? null : $userGroupId; /** @var null|Preference $preference */ - $preference = null; - $items = config('firefly.admin_specific_prefs'); + $preference = null; + $items = config('firefly.admin_specific_prefs'); if (null !== $userGroupId && in_array($value, $items, true)) { // find a preference with a specific user_group_id $preference = $user->preferences()->where('user_group_id', $userGroupId)->where('name', $value)->first(); @@ -73,12 +73,12 @@ class Preference extends Model /** @var Preference $preference */ return $preference; } - $default = config('firefly.default_preferences'); + $default = config('firefly.default_preferences'); if (array_key_exists($value, $default)) { - $preference = new self(); - $preference->name = $value; - $preference->data = $default[$value]; - $preference->user_id = (int) $user->id; + $preference = new self(); + $preference->name = $value; + $preference->data = $default[$value]; + $preference->user_id = (int) $user->id; $preference->user_group_id = in_array($value, $items, true) ? $userGroupId : null; $preference->save(); @@ -101,7 +101,7 @@ class Preference extends Model 'updated_at' => 'datetime', 'data' => 'array', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } } diff --git a/app/Models/Recurrence.php b/app/Models/Recurrence.php index d40b2cce8e..68fc118007 100644 --- a/app/Models/Recurrence.php +++ b/app/Models/Recurrence.php @@ -64,10 +64,10 @@ class Recurrence extends Model 'latest_date_tz', 'repetitions', 'apply_rules', - 'active' + 'active', ]; - protected $table = 'recurrences'; + protected $table = 'recurrences'; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -80,10 +80,10 @@ class Recurrence extends Model $recurrenceId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Recurrence $recurrence */ - $recurrence = $user->recurrences()->find($recurrenceId); + $recurrence = $user->recurrences()->find($recurrenceId); if (null !== $recurrence) { return $recurrence; } @@ -151,12 +151,12 @@ class Recurrence extends Model 'active' => 'bool', 'apply_rules' => 'bool', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function transactionTypeId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceMeta.php b/app/Models/RecurrenceMeta.php index a1e2e1a127..c4fa3e5f28 100644 --- a/app/Models/RecurrenceMeta.php +++ b/app/Models/RecurrenceMeta.php @@ -37,7 +37,7 @@ class RecurrenceMeta extends Model protected $fillable = ['recurrence_id', 'name', 'value']; - protected $table = 'recurrences_meta'; + protected $table = 'recurrences_meta'; public function recurrence(): BelongsTo { @@ -51,6 +51,6 @@ class RecurrenceMeta extends Model protected function recurrenceId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php index e21c945de8..711eee4027 100644 --- a/app/Models/RecurrenceRepetition.php +++ b/app/Models/RecurrenceRepetition.php @@ -38,7 +38,7 @@ class RecurrenceRepetition extends Model /** @deprecated */ #[Deprecated] - public const int WEEKEND_DO_NOTHING = 1; + public const int WEEKEND_DO_NOTHING = 1; /** @deprecated */ #[Deprecated] @@ -46,25 +46,25 @@ class RecurrenceRepetition extends Model /** @deprecated */ #[Deprecated] - public const int WEEKEND_TO_FRIDAY = 3; + public const int WEEKEND_TO_FRIDAY = 3; /** @deprecated */ #[Deprecated] - public const int WEEKEND_TO_MONDAY = 4; + public const int WEEKEND_TO_MONDAY = 4; - protected $casts = [ + protected $casts = [ 'created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'repetition_type' => 'string', 'repetition_moment' => 'string', 'repetition_skip' => 'int', - 'weekend' => 'int' + 'weekend' => 'int', ]; - protected $fillable = ['recurrence_id', 'weekend', 'repetition_type', 'repetition_moment', 'repetition_skip']; + protected $fillable = ['recurrence_id', 'weekend', 'repetition_type', 'repetition_moment', 'repetition_skip']; - protected $table = 'recurrences_repetitions'; + protected $table = 'recurrences_repetitions'; public function recurrence(): BelongsTo { @@ -80,16 +80,16 @@ class RecurrenceRepetition extends Model protected function recurrenceId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function repetitionSkip(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function weekend(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceTransaction.php b/app/Models/RecurrenceTransaction.php index 8f78d9f4e2..14a211006d 100644 --- a/app/Models/RecurrenceTransaction.php +++ b/app/Models/RecurrenceTransaction.php @@ -47,10 +47,10 @@ class RecurrenceTransaction extends Model 'destination_id', 'amount', 'foreign_amount', - 'description' + 'description', ]; - protected $table = 'recurrences_transactions'; + protected $table = 'recurrences_transactions'; public function destinationAccount(): BelongsTo { @@ -89,7 +89,7 @@ class RecurrenceTransaction extends Model protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function casts(): array @@ -100,37 +100,37 @@ class RecurrenceTransaction extends Model 'deleted_at' => 'datetime', 'amount' => 'string', 'foreign_amount' => 'string', - 'description' => 'string' + 'description' => 'string', ]; } protected function destinationId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function foreignAmount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function recurrenceId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function sourceId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function transactionCurrencyId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function userId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceTransactionMeta.php b/app/Models/RecurrenceTransactionMeta.php index a70f63c8a0..d162c3b9c6 100644 --- a/app/Models/RecurrenceTransactionMeta.php +++ b/app/Models/RecurrenceTransactionMeta.php @@ -37,7 +37,7 @@ class RecurrenceTransactionMeta extends Model protected $fillable = ['rt_id', 'name', 'value']; - protected $table = 'rt_meta'; + protected $table = 'rt_meta'; public function recurrenceTransaction(): BelongsTo { @@ -51,6 +51,6 @@ class RecurrenceTransactionMeta extends Model protected function rtId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Rule.php b/app/Models/Rule.php index 3a45389db3..86fdee9aed 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -58,10 +58,10 @@ class Rule extends Model $ruleId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Rule $rule */ - $rule = $user->rules()->find($ruleId); + $rule = $user->rules()->find($ruleId); if (null !== $rule) { return $rule; } @@ -107,22 +107,22 @@ class Rule extends Model 'id' => 'int', 'strict' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function description(): Attribute { - return Attribute::make(set: static fn($value): array => ['description' => e($value)]); + return Attribute::make(set: static fn ($value): array => ['description' => e($value)]); } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function ruleGroupId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RuleAction.php b/app/Models/RuleAction.php index 7406b2d1b3..28245d8410 100644 --- a/app/Models/RuleAction.php +++ b/app/Models/RuleAction.php @@ -73,17 +73,17 @@ class RuleAction extends Model 'updated_at' => 'datetime', 'active' => 'boolean', 'order' => 'int', - 'stop_processing' => 'boolean' + 'stop_processing' => 'boolean', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function ruleId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php index a1781758e1..f0a85a78e1 100644 --- a/app/Models/RuleGroup.php +++ b/app/Models/RuleGroup.php @@ -60,10 +60,10 @@ class RuleGroup extends Model $ruleGroupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|RuleGroup $ruleGroup */ - $ruleGroup = $user->ruleGroups()->find($ruleGroupId); + $ruleGroup = $user->ruleGroups()->find($ruleGroupId); if (null !== $ruleGroup) { return $ruleGroup; } @@ -92,12 +92,12 @@ class RuleGroup extends Model 'stop_processing' => 'boolean', 'order' => 'int', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/RuleTrigger.php b/app/Models/RuleTrigger.php index 228b305f00..e8eefe1ba5 100644 --- a/app/Models/RuleTrigger.php +++ b/app/Models/RuleTrigger.php @@ -46,17 +46,17 @@ class RuleTrigger extends Model 'updated_at' => 'datetime', 'active' => 'boolean', 'order' => 'int', - 'stop_processing' => 'boolean' + 'stop_processing' => 'boolean', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function ruleId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/Tag.php b/app/Models/Tag.php index 1d0f3cce50..15f1489d9e 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -45,7 +45,7 @@ class Tag extends Model protected $fillable = ['user_id', 'user_group_id', 'tag', 'date', 'date_tz', 'description', 'tag_mode']; - protected $hidden = ['zoomLevel', 'zoom_level', 'latitude', 'longitude']; + protected $hidden = ['zoomLevel', 'zoom_level', 'latitude', 'longitude']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -58,10 +58,10 @@ class Tag extends Model $tagId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Tag $tag */ - $tag = $user->tags()->find($tagId); + $tag = $user->tags()->find($tagId); if (null !== $tag) { return $tag; } @@ -101,7 +101,7 @@ class Tag extends Model 'latitude' => 'float', 'longitude' => 'float', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index e026ca456f..5a20bf7492 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -54,10 +54,10 @@ class Transaction extends Model 'transaction_currency_id', 'foreign_currency_id', 'foreign_amount', - 'reconciled' + 'reconciled', ]; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Get the account this object belongs to. @@ -111,7 +111,7 @@ class Transaction extends Model protected function accountId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } /** @@ -147,12 +147,12 @@ class Transaction extends Model */ protected function amount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function balanceDirty(): Attribute { - return Attribute::make(get: static fn($value): bool => 1 === (int) $value); + return Attribute::make(get: static fn ($value): bool => 1 === (int) $value); } /** @@ -170,11 +170,11 @@ class Transaction extends Model protected function casts(): array { return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'identifier' => 'int', - 'encrypted' => 'boolean', // model does not have these fields though + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + 'deleted_at' => 'datetime', + 'identifier' => 'int', + 'encrypted' => 'boolean', // model does not have these fields though 'bill_name_encrypted' => 'boolean', 'reconciled' => 'boolean', 'balance_dirty' => 'boolean', @@ -184,7 +184,7 @@ class Transaction extends Model 'amount' => 'string', 'foreign_amount' => 'string', 'native_amount' => 'string', - 'native_foreign_amount' => 'string' + 'native_foreign_amount' => 'string', ]; } @@ -193,12 +193,12 @@ class Transaction extends Model */ protected function foreignAmount(): Attribute { - return Attribute::make(get: static fn($value): string => (string) $value); + return Attribute::make(get: static fn ($value): string => (string) $value); } protected function transactionJournalId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } #[Scope] diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php index 6a1e92adbf..942b9ef1fd 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -38,10 +38,10 @@ class TransactionCurrency extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - public null|bool $userGroupEnabled = null; - public null|bool $userGroupNative = null; + public ?bool $userGroupEnabled = null; + public ?bool $userGroupNative = null; - protected $fillable = ['name', 'code', 'symbol', 'decimal_places', 'enabled']; + protected $fillable = ['name', 'code', 'symbol', 'decimal_places', 'enabled']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -65,9 +65,9 @@ class TransactionCurrency extends Model public function refreshForUser(User $user): void { - $current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first(); - $native = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); - $this->userGroupNative = $native->id === $this->id; + $current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first(); + $native = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $this->userGroupNative = $native->id === $this->id; $this->userGroupEnabled = null !== $current; } @@ -109,12 +109,12 @@ class TransactionCurrency extends Model 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'decimal_places' => 'int', - 'enabled' => 'bool' + 'enabled' => 'bool', ]; } protected function decimalPlaces(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/TransactionGroup.php b/app/Models/TransactionGroup.php index 5315593ae9..7c55c1f2fa 100644 --- a/app/Models/TransactionGroup.php +++ b/app/Models/TransactionGroup.php @@ -62,15 +62,16 @@ class TransactionGroup extends Model $groupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug(sprintf('User authenticated as %s', $user->email)); /** @var null|TransactionGroup $group */ - $group = $user + $group = $user ->transactionGroups() ->with(['transactionJournals', 'transactionJournals.transactions']) ->where('transaction_groups.id', $groupId) - ->first(['transaction_groups.*']); + ->first(['transaction_groups.*']) + ; if (null !== $group) { Log::debug(sprintf('Found group #%d.', $group->id)); @@ -107,7 +108,7 @@ class TransactionGroup extends Model 'title' => 'string', 'date' => 'datetime', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } } diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index f4ff88e26f..aee0f75ade 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -69,10 +69,10 @@ class TransactionJournal extends Model 'completed', 'order', 'date', - 'date_tz' + 'date_tz', ]; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -85,10 +85,10 @@ class TransactionJournal extends Model $journalId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|TransactionJournal $journal */ - $journal = $user->transactionJournals()->where('transaction_journals.id', $journalId)->first(['transaction_journals.*']); + $journal = $user->transactionJournals()->where('transaction_journals.id', $journalId)->first(['transaction_journals.*']); if (null !== $journal) { return $journal; } @@ -224,18 +224,18 @@ class TransactionJournal extends Model 'encrypted' => 'boolean', 'completed' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; } protected function order(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function transactionTypeId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } #[Scope] diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index 9babd6649f..b06dd28dc0 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -50,7 +50,8 @@ class TransactionJournalLink extends Model ->leftJoin('transaction_journals as t_b', 't_b.id', '=', 'destination_id') ->where('t_a.user_id', auth()->user()->id) ->where('t_b.user_id', auth()->user()->id) - ->first(['journal_links.*']); + ->first(['journal_links.*']) + ; if (null !== $link) { return $link; } @@ -89,16 +90,16 @@ class TransactionJournalLink extends Model protected function destinationId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function linkTypeId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function sourceId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 71e29259c5..9c2f03ea2b 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -39,7 +39,7 @@ class TransactionJournalMeta extends Model protected $fillable = ['transaction_journal_id', 'name', 'data', 'hash']; - protected $table = 'journal_meta'; + protected $table = 'journal_meta'; public function transactionJournal(): BelongsTo { @@ -53,7 +53,7 @@ class TransactionJournalMeta extends Model protected function data(): Attribute { - return Attribute::make(get: static fn($value): mixed => json_decode((string) $value, false), set: static function ($value): array { + return Attribute::make(get: static fn ($value): mixed => json_decode((string) $value, false), set: static function ($value): array { $data = json_encode($value); return ['data' => $data, 'hash' => hash('sha256', $data)]; @@ -62,6 +62,6 @@ class TransactionJournalMeta extends Model protected function transactionJournalId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/TransactionType.php b/app/Models/TransactionType.php index 247eb22de8..ec47b0584a 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -38,11 +38,11 @@ class TransactionType extends Model /** @deprecated */ #[Deprecated] - public const string DEPOSIT = 'Deposit'; + public const string DEPOSIT = 'Deposit'; /** @deprecated */ #[Deprecated] - public const string INVALID = 'Invalid'; + public const string INVALID = 'Invalid'; /** @deprecated */ #[Deprecated] @@ -50,22 +50,22 @@ class TransactionType extends Model /** @deprecated */ #[Deprecated] - public const string OPENING_BALANCE = 'Opening balance'; + public const string OPENING_BALANCE = 'Opening balance'; /** @deprecated */ #[Deprecated] - public const string RECONCILIATION = 'Reconciliation'; + public const string RECONCILIATION = 'Reconciliation'; /** @deprecated */ #[Deprecated] - public const string TRANSFER = 'Transfer'; + public const string TRANSFER = 'Transfer'; /** @deprecated */ #[Deprecated] - public const string WITHDRAWAL = 'Withdrawal'; + public const string WITHDRAWAL = 'Withdrawal'; - protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; - protected $fillable = ['type']; + protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; + protected $fillable = ['type']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). diff --git a/app/Models/UserGroup.php b/app/Models/UserGroup.php index 31242c3d94..e234113474 100644 --- a/app/Models/UserGroup.php +++ b/app/Models/UserGroup.php @@ -50,16 +50,16 @@ class UserGroup extends Model $userGroupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|UserGroup $userGroup */ - $userGroup = self::find($userGroupId); + $userGroup = self::find($userGroupId); if (null === $userGroup) { throw new NotFoundHttpException(); } // need at least ready only to be aware of the user group's existence, // but owner/full role (in the group) or global owner role may overrule this. - $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::READ_ONLY) || $user->hasRole('owner'); + $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::READ_ONLY) || $user->hasRole('owner'); if ($access) { return $userGroup; } diff --git a/app/Models/Webhook.php b/app/Models/Webhook.php index 1120318754..f2447994d2 100644 --- a/app/Models/Webhook.php +++ b/app/Models/Webhook.php @@ -52,7 +52,7 @@ class Webhook extends Model 'response' => 'integer', 'delivery' => 'integer', 'user_id' => 'integer', - 'user_group_id' => 'integer' + 'user_group_id' => 'integer', ]; protected $fillable = ['active', 'trigger', 'response', 'delivery', 'user_id', 'user_group_id', 'url', 'title', 'secret']; @@ -72,7 +72,7 @@ class Webhook extends Model $array = []; $set = WebhookDeliveryEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -95,7 +95,7 @@ class Webhook extends Model $array = []; $set = WebhookResponseEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -118,7 +118,7 @@ class Webhook extends Model $array = []; $set = WebhookTriggerEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -136,10 +136,10 @@ class Webhook extends Model $webhookId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Webhook $webhook */ - $webhook = $user->webhooks()->find($webhookId); + $webhook = $user->webhooks()->find($webhookId); if (null !== $webhook) { return $webhook; } diff --git a/app/Models/WebhookAttempt.php b/app/Models/WebhookAttempt.php index 6263b48306..f3678a22b5 100644 --- a/app/Models/WebhookAttempt.php +++ b/app/Models/WebhookAttempt.php @@ -48,10 +48,10 @@ class WebhookAttempt extends Model $attemptId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|WebhookAttempt $attempt */ - $attempt = self::find($attemptId); + $attempt = self::find($attemptId); if (null !== $attempt && $attempt->webhookMessage->webhook->user_id === $user->id) { return $attempt; } @@ -67,6 +67,6 @@ class WebhookAttempt extends Model protected function webhookMessageId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/WebhookDelivery.php b/app/Models/WebhookDelivery.php index bde7589abb..069d1e7891 100644 --- a/app/Models/WebhookDelivery.php +++ b/app/Models/WebhookDelivery.php @@ -39,6 +39,6 @@ class WebhookDelivery extends Model */ protected function key(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/WebhookMessage.php b/app/Models/WebhookMessage.php index f052219b7d..3a896fcada 100644 --- a/app/Models/WebhookMessage.php +++ b/app/Models/WebhookMessage.php @@ -50,10 +50,10 @@ class WebhookMessage extends Model $messageId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|WebhookMessage $message */ - $message = self::find($messageId); + $message = self::find($messageId); if (null !== $message && $message->webhook->user_id === $user->id) { return $message; } @@ -82,11 +82,11 @@ class WebhookMessage extends Model */ protected function sent(): Attribute { - return Attribute::make(get: static fn($value): bool => (bool) $value); + return Attribute::make(get: static fn ($value): bool => (bool) $value); } protected function webhookId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/WebhookResponse.php b/app/Models/WebhookResponse.php index 0d5aed1146..d769d61dca 100644 --- a/app/Models/WebhookResponse.php +++ b/app/Models/WebhookResponse.php @@ -39,6 +39,6 @@ class WebhookResponse extends Model */ protected function key(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Models/WebhookTrigger.php b/app/Models/WebhookTrigger.php index 2b6a09282a..da474ab37c 100644 --- a/app/Models/WebhookTrigger.php +++ b/app/Models/WebhookTrigger.php @@ -39,6 +39,6 @@ class WebhookTrigger extends Model */ protected function key(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Notifications/Admin/UnknownUserLoginAttempt.php b/app/Notifications/Admin/UnknownUserLoginAttempt.php index d9963a3a2f..29dfeb6a12 100644 --- a/app/Notifications/Admin/UnknownUserLoginAttempt.php +++ b/app/Notifications/Admin/UnknownUserLoginAttempt.php @@ -67,9 +67,10 @@ class UnknownUserLoginAttempt extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject((string) trans('email.unknown_user_subject')); + ->subject((string) trans('email.unknown_user_subject')) + ; } // /** diff --git a/app/Notifications/Admin/UserInvitation.php b/app/Notifications/Admin/UserInvitation.php index ad29a9d75a..1049e3baf8 100644 --- a/app/Notifications/Admin/UserInvitation.php +++ b/app/Notifications/Admin/UserInvitation.php @@ -72,9 +72,10 @@ class UserInvitation extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject((string) trans('email.invitation_created_subject')); + ->subject((string) trans('email.invitation_created_subject')) + ; } // /** @@ -101,7 +102,7 @@ class UserInvitation extends Notification return PushoverMessage::create((string) trans('email.invitation_created_body', [ 'email' => $this->invitee->user->email, - 'invitee' => $this->invitee->email + 'invitee' => $this->invitee->email, ]))->title((string) trans('email.invitation_created_subject')); } @@ -112,7 +113,7 @@ class UserInvitation extends Notification { return new SlackMessage()->content((string) trans('email.invitation_created_body', [ 'email' => $this->invitee->user->email, - 'invitee' => $this->invitee->email + 'invitee' => $this->invitee->email, ])); } diff --git a/app/Notifications/Admin/UserRegistration.php b/app/Notifications/Admin/UserRegistration.php index 17e6875812..55881a2261 100644 --- a/app/Notifications/Admin/UserRegistration.php +++ b/app/Notifications/Admin/UserRegistration.php @@ -72,9 +72,10 @@ class UserRegistration extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject((string) trans('email.registered_subject_admin')); + ->subject((string) trans('email.registered_subject_admin')) + ; } // /** @@ -101,7 +102,7 @@ class UserRegistration extends Notification return PushoverMessage::create((string) trans('email.admin_new_user_registered', [ 'email' => $this->user->email, - 'invitee' => $this->user->email + 'invitee' => $this->user->email, ]))->title((string) trans('email.registered_subject_admin')); } diff --git a/app/Notifications/Admin/VersionCheckResult.php b/app/Notifications/Admin/VersionCheckResult.php index 76ed284d2e..76ff3aff0c 100644 --- a/app/Notifications/Admin/VersionCheckResult.php +++ b/app/Notifications/Admin/VersionCheckResult.php @@ -59,7 +59,8 @@ class VersionCheckResult extends Notification { return new MailMessage() ->markdown('emails.new-version', ['message' => $this->message]) - ->subject((string) trans('email.new_version_email_subject')); + ->subject((string) trans('email.new_version_email_subject')) + ; } // /** @@ -96,7 +97,8 @@ class VersionCheckResult extends Notification ->content($this->message) ->attachment(static function ($attachment): void { $attachment->title('Firefly III @ GitHub', 'https://github.com/firefly-iii/firefly-iii/releases'); - }); + }) + ; } /** diff --git a/app/Notifications/Notifiables/OwnerNotifiable.php b/app/Notifications/Notifiables/OwnerNotifiable.php index a32cf10cff..7a1c7799e1 100644 --- a/app/Notifications/Notifiables/OwnerNotifiable.php +++ b/app/Notifications/Notifiables/OwnerNotifiable.php @@ -42,7 +42,7 @@ class OwnerNotifiable */ public function routeNotificationFor($driver, $notification = null) { - $method = 'routeNotificationFor' . Str::studly($driver); + $method = 'routeNotificationFor'.Str::studly($driver); if (method_exists($this, $method)) { Log::debug(sprintf('Redirect for settings to "%s".', $method)); @@ -51,7 +51,7 @@ class OwnerNotifiable Log::debug(sprintf('No method "%s" found, return generic settings.', $method)); return match ($driver) { - 'mail' => (string) config('firefly.site_owner'), + 'mail' => (string) config('firefly.site_owner'), default => null }; } diff --git a/app/Notifications/ReturnsAvailableChannels.php b/app/Notifications/ReturnsAvailableChannels.php index f2f5876f82..e6a9306df3 100644 --- a/app/Notifications/ReturnsAvailableChannels.php +++ b/app/Notifications/ReturnsAvailableChannels.php @@ -35,7 +35,7 @@ use NotificationChannels\Pushover\PushoverChannel; class ReturnsAvailableChannels { - public static function returnChannels(string $type, null|User $user = null): array + public static function returnChannels(string $type, ?User $user = null): array { $channels = ['mail']; diff --git a/app/Notifications/ReturnsSettings.php b/app/Notifications/ReturnsSettings.php index b7d6f69c08..a6b7cdc96b 100644 --- a/app/Notifications/ReturnsSettings.php +++ b/app/Notifications/ReturnsSettings.php @@ -32,7 +32,7 @@ use Illuminate\Support\Facades\Log; class ReturnsSettings { - public static function getSettings(string $channel, string $type, null|User $user): array + public static function getSettings(string $channel, string $type, ?User $user): array { if ('ntfy' === $channel) { return self::getNtfySettings($type, $user); @@ -41,24 +41,24 @@ class ReturnsSettings throw new FireflyException(sprintf('Cannot handle channel "%s"', $channel)); } - private static function getNtfySettings(string $type, null|User $user): array + private static function getNtfySettings(string $type, ?User $user): array { Log::debug(sprintf('Getting Ntfy settings for %s and user #%d', $type, $user?->id)); $settings = ['ntfy_server' => 'https://ntfy.sh', 'ntfy_topic' => '', 'ntfy_auth' => false, 'ntfy_user' => '', 'ntfy_pass' => '']; if ('user' === $type && $user instanceof User) { $settings['ntfy_server'] = Preferences::getEncryptedForUser($user, 'ntfy_server', 'https://ntfy.sh')->data; - $settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data; - $settings['ntfy_auth'] = '1' === Preferences::getForUser($user, 'ntfy_auth', false)->data; - $settings['ntfy_user'] = Preferences::getEncryptedForUser($user, 'ntfy_user', '')->data; - $settings['ntfy_pass'] = Preferences::getEncryptedForUser($user, 'ntfy_pass', '')->data; + $settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data; + $settings['ntfy_auth'] = '1' === Preferences::getForUser($user, 'ntfy_auth', false)->data; + $settings['ntfy_user'] = Preferences::getEncryptedForUser($user, 'ntfy_user', '')->data; + $settings['ntfy_pass'] = Preferences::getEncryptedForUser($user, 'ntfy_pass', '')->data; Log::debug(sprintf('Auth is %s, user = "%s"', var_export($settings['ntfy_auth'], true), $settings['ntfy_user'])); } if ('owner' === $type) { $settings['ntfy_server'] = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $settings['ntfy_topic'] = FireflyConfig::getEncrypted('ntfy_topic', '')->data; - $settings['ntfy_auth'] = FireflyConfig::get('ntfy_auth', false)->data; - $settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data; - $settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data; + $settings['ntfy_topic'] = FireflyConfig::getEncrypted('ntfy_topic', '')->data; + $settings['ntfy_auth'] = FireflyConfig::get('ntfy_auth', false)->data; + $settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data; + $settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data; Log::debug(sprintf('Auth is %s, user = "%s"', var_export($settings['ntfy_auth'], true), $settings['ntfy_user'])); } diff --git a/app/Notifications/Security/DisabledMFANotification.php b/app/Notifications/Security/DisabledMFANotification.php index 60835c5a51..5af175ff97 100644 --- a/app/Notifications/Security/DisabledMFANotification.php +++ b/app/Notifications/Security/DisabledMFANotification.php @@ -67,9 +67,10 @@ class DisabledMFANotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Security/EnabledMFANotification.php b/app/Notifications/Security/EnabledMFANotification.php index 280d8b2ace..5d54bc30cd 100644 --- a/app/Notifications/Security/EnabledMFANotification.php +++ b/app/Notifications/Security/EnabledMFANotification.php @@ -67,9 +67,10 @@ class EnabledMFANotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Security/MFABackupFewLeftNotification.php b/app/Notifications/Security/MFABackupFewLeftNotification.php index f432ccdd7e..ee5b3f64cd 100644 --- a/app/Notifications/Security/MFABackupFewLeftNotification.php +++ b/app/Notifications/Security/MFABackupFewLeftNotification.php @@ -69,9 +69,10 @@ class MFABackupFewLeftNotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message @@ -92,7 +93,7 @@ class MFABackupFewLeftNotification extends Notification { return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', [ 'email' => $this->user->email, - 'count' => $this->count + 'count' => $this->count, ]))->title((string) trans('email.mfa_few_backups_left_subject')); } diff --git a/app/Notifications/Security/MFABackupNoLeftNotification.php b/app/Notifications/Security/MFABackupNoLeftNotification.php index 1015fd5a15..ab2819f365 100644 --- a/app/Notifications/Security/MFABackupNoLeftNotification.php +++ b/app/Notifications/Security/MFABackupNoLeftNotification.php @@ -67,9 +67,10 @@ class MFABackupNoLeftNotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Security/MFAManyFailedAttemptsNotification.php b/app/Notifications/Security/MFAManyFailedAttemptsNotification.php index aa669ea758..cca7bde974 100644 --- a/app/Notifications/Security/MFAManyFailedAttemptsNotification.php +++ b/app/Notifications/Security/MFAManyFailedAttemptsNotification.php @@ -66,9 +66,10 @@ class MFAManyFailedAttemptsNotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message @@ -89,7 +90,7 @@ class MFAManyFailedAttemptsNotification extends Notification { return PushoverMessage::create((string) trans('email.mfa_many_failed_slack', [ 'email' => $this->user->email, - 'count' => $this->count + 'count' => $this->count, ]))->title((string) trans('email.mfa_many_failed_subject')); } diff --git a/app/Notifications/Security/MFAUsedBackupCodeNotification.php b/app/Notifications/Security/MFAUsedBackupCodeNotification.php index aadaa3c122..950ebbedd5 100644 --- a/app/Notifications/Security/MFAUsedBackupCodeNotification.php +++ b/app/Notifications/Security/MFAUsedBackupCodeNotification.php @@ -67,9 +67,10 @@ class MFAUsedBackupCodeNotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Security/NewBackupCodesNotification.php b/app/Notifications/Security/NewBackupCodesNotification.php index 717f4ff22e..680276b7aa 100644 --- a/app/Notifications/Security/NewBackupCodesNotification.php +++ b/app/Notifications/Security/NewBackupCodesNotification.php @@ -67,9 +67,10 @@ class NewBackupCodesNotification extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Security/UserFailedLoginAttempt.php b/app/Notifications/Security/UserFailedLoginAttempt.php index 69f626db1b..29048fcb58 100644 --- a/app/Notifications/Security/UserFailedLoginAttempt.php +++ b/app/Notifications/Security/UserFailedLoginAttempt.php @@ -65,9 +65,10 @@ class UserFailedLoginAttempt extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject($subject); + ->subject($subject) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/Test/OwnerTestNotificationEmail.php b/app/Notifications/Test/OwnerTestNotificationEmail.php index 859850261b..261d84ebcc 100644 --- a/app/Notifications/Test/OwnerTestNotificationEmail.php +++ b/app/Notifications/Test/OwnerTestNotificationEmail.php @@ -54,7 +54,8 @@ class OwnerTestNotificationEmail extends Notification return new MailMessage() ->markdown('emails.admin-test', ['email' => $address]) - ->subject((string) trans('email.admin_test_subject')); + ->subject((string) trans('email.admin_test_subject')) + ; } /** diff --git a/app/Notifications/Test/UserTestNotificationEmail.php b/app/Notifications/Test/UserTestNotificationEmail.php index dc8eeaeb9c..20cb0c81ca 100644 --- a/app/Notifications/Test/UserTestNotificationEmail.php +++ b/app/Notifications/Test/UserTestNotificationEmail.php @@ -51,7 +51,8 @@ class UserTestNotificationEmail extends Notification return new MailMessage() ->markdown('emails.admin-test', ['email' => $address]) - ->subject((string) trans('email.admin_test_subject')); + ->subject((string) trans('email.admin_test_subject')) + ; } /** diff --git a/app/Notifications/User/BillReminder.php b/app/Notifications/User/BillReminder.php index 35154270f6..c0e6cea97d 100644 --- a/app/Notifications/User/BillReminder.php +++ b/app/Notifications/User/BillReminder.php @@ -61,7 +61,8 @@ class BillReminder extends Notification { return new MailMessage() ->markdown('emails.bill-warning', ['field' => $this->field, 'diff' => $this->diff, 'bill' => $this->bill]) - ->subject($this->getSubject()); + ->subject($this->getSubject()) + ; } private function getSubject(): string @@ -105,7 +106,8 @@ class BillReminder extends Notification ->attachment(static function ($attachment) use ($bill, $url): void { $attachment->title((string) trans('firefly.visit_bill', ['name' => $bill->name]), $url); }) - ->content($this->getSubject()); + ->content($this->getSubject()) + ; } /** diff --git a/app/Notifications/User/NewAccessToken.php b/app/Notifications/User/NewAccessToken.php index b0d5f2a373..cf3a7fbfc2 100644 --- a/app/Notifications/User/NewAccessToken.php +++ b/app/Notifications/User/NewAccessToken.php @@ -59,7 +59,8 @@ class NewAccessToken extends Notification return new MailMessage() ->markdown('emails.token-created', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.access_token_created_subject')); + ->subject((string) trans('email.access_token_created_subject')) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/User/RuleActionFailed.php b/app/Notifications/User/RuleActionFailed.php index 186b207c7d..41a24eb8ff 100644 --- a/app/Notifications/User/RuleActionFailed.php +++ b/app/Notifications/User/RuleActionFailed.php @@ -47,11 +47,11 @@ class RuleActionFailed extends Notification public function __construct(array $params) { [$mainMessage, $groupTitle, $groupLink, $ruleTitle, $ruleLink] = $params; - $this->message = $mainMessage; - $this->groupTitle = $groupTitle; - $this->groupLink = $groupLink; - $this->ruleTitle = $ruleTitle; - $this->ruleLink = $ruleLink; + $this->message = $mainMessage; + $this->groupTitle = $groupTitle; + $this->groupLink = $groupLink; + $this->ruleTitle = $ruleTitle; + $this->ruleLink = $ruleLink; } /** @@ -97,7 +97,8 @@ class RuleActionFailed extends Notification }) ->attachment(static function ($attachment) use ($ruleTitle, $ruleLink): void { $attachment->title((string) trans('rules.inspect_rule', ['title' => $ruleTitle]), $ruleLink); - }); + }) + ; } /** diff --git a/app/Notifications/User/SubscriptionsOverdueReminder.php b/app/Notifications/User/SubscriptionsOverdueReminder.php index f73af0b480..11c4ebbcbd 100644 --- a/app/Notifications/User/SubscriptionsOverdueReminder.php +++ b/app/Notifications/User/SubscriptionsOverdueReminder.php @@ -58,17 +58,18 @@ class SubscriptionsOverdueReminder extends Notification $info = []; $count = 0; foreach ($this->overdue as $item) { - $current = ['bill' => $item['bill']]; - $current['pay_dates'] = array_map(static fn(string $date): string => new Carbon($date)->isoFormat((string) trans( + $current = ['bill' => $item['bill']]; + $current['pay_dates'] = array_map(static fn (string $date): string => new Carbon($date)->isoFormat((string) trans( 'config.month_and_day_moment_js' )), $item['dates']['pay_dates']); - $info[] = $current; + $info[] = $current; ++$count; } return new MailMessage() ->markdown('emails.subscriptions-overdue-warning', ['info' => $info, 'count' => $count]) - ->subject($this->getSubject()); + ->subject($this->getSubject()) + ; } private function getSubject(): string @@ -111,7 +112,8 @@ class SubscriptionsOverdueReminder extends Notification ->attachment(static function ($attachment) use ($url): void { $attachment->title((string) trans('firefly.visit_bills'), $url); }) - ->content($this->getSubject()); + ->content($this->getSubject()) + ; } /** diff --git a/app/Notifications/User/TransactionCreation.php b/app/Notifications/User/TransactionCreation.php index 20d180ffb1..729708b910 100644 --- a/app/Notifications/User/TransactionCreation.php +++ b/app/Notifications/User/TransactionCreation.php @@ -55,7 +55,8 @@ class TransactionCreation extends Notification { return new MailMessage() ->markdown('emails.report-new-journals', ['transformed' => $this->collection]) - ->subject(trans_choice('email.new_journals_subject', count($this->collection))); + ->subject(trans_choice('email.new_journals_subject', count($this->collection))) + ; } /** diff --git a/app/Notifications/User/UserLogin.php b/app/Notifications/User/UserLogin.php index ed975a6cb9..57bd1fe15f 100644 --- a/app/Notifications/User/UserLogin.php +++ b/app/Notifications/User/UserLogin.php @@ -58,7 +58,8 @@ class UserLogin extends Notification return new MailMessage() ->markdown('emails.new-ip', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.login_from_new_ip')); + ->subject((string) trans('email.login_from_new_ip')) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/User/UserNewPassword.php b/app/Notifications/User/UserNewPassword.php index 9bc77baa5e..b7f3b9183d 100644 --- a/app/Notifications/User/UserNewPassword.php +++ b/app/Notifications/User/UserNewPassword.php @@ -69,9 +69,10 @@ class UserNewPassword extends Notification 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, - 'time' => $time + 'time' => $time, ]) - ->subject((string) trans('email.reset_pw_subject')); + ->subject((string) trans('email.reset_pw_subject')) + ; } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/User/UserRegistration.php b/app/Notifications/User/UserRegistration.php index 4c8c66ae01..f642c986f7 100644 --- a/app/Notifications/User/UserRegistration.php +++ b/app/Notifications/User/UserRegistration.php @@ -51,7 +51,8 @@ class UserRegistration extends Notification { return new MailMessage() ->markdown('emails.registered', ['address' => route('index')]) - ->subject((string) trans('email.registered_subject')); + ->subject((string) trans('email.registered_subject')) + ; } /** diff --git a/app/Providers/AccountServiceProvider.php b/app/Providers/AccountServiceProvider.php index bc03120c1d..bdff7d1eee 100644 --- a/app/Providers/AccountServiceProvider.php +++ b/app/Providers/AccountServiceProvider.php @@ -41,9 +41,7 @@ class AccountServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/AdminServiceProvider.php b/app/Providers/AdminServiceProvider.php index 00e176e52e..3333bd65bf 100644 --- a/app/Providers/AdminServiceProvider.php +++ b/app/Providers/AdminServiceProvider.php @@ -37,9 +37,7 @@ class AdminServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 4242dbea51..c94ae94283 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -65,14 +65,14 @@ class AppServiceProvider extends ServiceProvider return ''; }); Blade::if('partialroute', function (string $route, string $firstParam = ''): bool { - $name = Route::getCurrentRoute()->getName() ?? ''; + $name = Route::getCurrentRoute()->getName() ?? ''; if ('' === $firstParam && str_contains($name, $route)) { return true; } /** @var null|array $params */ $params = Route::getCurrentRoute()->parameters(); - $params ??= []; + $params ??= []; $objectType = $params['objectType'] ?? ''; return $objectType === $firstParam && str_contains($name, $route); diff --git a/app/Providers/AttachmentServiceProvider.php b/app/Providers/AttachmentServiceProvider.php index 4c50ac41b9..f6a649c7ec 100644 --- a/app/Providers/AttachmentServiceProvider.php +++ b/app/Providers/AttachmentServiceProvider.php @@ -37,9 +37,7 @@ class AttachmentServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 35ea287f73..b714f7c0fd 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -45,11 +45,11 @@ class AuthServiceProvider extends ServiceProvider */ public function boot(): void { - Auth::provider('remote_user_provider', static fn($app, array $config): RemoteUserProvider => new RemoteUserProvider()); + Auth::provider('remote_user_provider', static fn ($app, array $config): RemoteUserProvider => new RemoteUserProvider()); Auth::extend( 'remote_user_guard', - static fn($app, string $name, array $config): RemoteUserGuard => 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/BillServiceProvider.php b/app/Providers/BillServiceProvider.php index b268d28b6d..13c9320201 100644 --- a/app/Providers/BillServiceProvider.php +++ b/app/Providers/BillServiceProvider.php @@ -37,9 +37,7 @@ class BillServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/BudgetServiceProvider.php b/app/Providers/BudgetServiceProvider.php index d2c94bf659..d62f7282f7 100644 --- a/app/Providers/BudgetServiceProvider.php +++ b/app/Providers/BudgetServiceProvider.php @@ -45,9 +45,7 @@ class BudgetServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/CategoryServiceProvider.php b/app/Providers/CategoryServiceProvider.php index 6c1c1f9495..6cebd465fd 100644 --- a/app/Providers/CategoryServiceProvider.php +++ b/app/Providers/CategoryServiceProvider.php @@ -41,9 +41,7 @@ class CategoryServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/CurrencyServiceProvider.php b/app/Providers/CurrencyServiceProvider.php index 5eeb52269c..053978b2ee 100644 --- a/app/Providers/CurrencyServiceProvider.php +++ b/app/Providers/CurrencyServiceProvider.php @@ -40,9 +40,7 @@ class CurrencyServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 721cc0456e..51fbb307af 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -56,37 +56,37 @@ class EventServiceProvider extends ServiceProvider // 'FireflyIII\Handlers\Events\UserEventHandler@sendLoginAttemptNotification', // ], // is a User related event. - Login::class => [ + Login::class => [ 'FireflyIII\Handlers\Events\UserEventHandler@checkSingleUserIsAdmin', - 'FireflyIII\Handlers\Events\UserEventHandler@demoUserBackToEnglish' + 'FireflyIII\Handlers\Events\UserEventHandler@demoUserBackToEnglish', ], // DetectedNewIPAddress::class => [ // 'FireflyIII\Handlers\Events\UserEventHandler@notifyNewIPAddress', // ], - RequestedVersionCheckStatus::class => ['FireflyIII\Handlers\Events\VersionCheckEventHandler@checkForUpdates'], - RequestedReportOnJournals::class => ['FireflyIII\Handlers\Events\AutomationHandler@reportJournals'], + RequestedVersionCheckStatus::class => ['FireflyIII\Handlers\Events\VersionCheckEventHandler@checkForUpdates'], + RequestedReportOnJournals::class => ['FireflyIII\Handlers\Events\AutomationHandler@reportJournals'], // is a User related event. - InvitationCreated::class => [ + InvitationCreated::class => [ 'FireflyIII\Handlers\Events\AdminEventHandler@sendInvitationNotification', - 'FireflyIII\Handlers\Events\UserEventHandler@sendRegistrationInvite' + 'FireflyIII\Handlers\Events\UserEventHandler@sendRegistrationInvite', ], // is a Transaction Journal related event. StoredTransactionGroup::class => ['FireflyIII\Handlers\Events\StoredGroupEventHandler@runAllHandlers'], TriggeredStoredTransactionGroup::class => ['FireflyIII\Handlers\Events\StoredGroupEventHandler@triggerRulesManually'], // is a Transaction Journal related event. - UpdatedTransactionGroup::class => ['FireflyIII\Handlers\Events\UpdatedGroupEventHandler@runAllHandlers'], - DestroyedTransactionGroup::class => ['FireflyIII\Handlers\Events\DestroyedGroupEventHandler@runAllHandlers'], + UpdatedTransactionGroup::class => ['FireflyIII\Handlers\Events\UpdatedGroupEventHandler@runAllHandlers'], + DestroyedTransactionGroup::class => ['FireflyIII\Handlers\Events\DestroyedGroupEventHandler@runAllHandlers'], // API related events: - AccessTokenCreated::class => ['FireflyIII\Handlers\Events\APIEventHandler@accessTokenCreated'], + AccessTokenCreated::class => ['FireflyIII\Handlers\Events\APIEventHandler@accessTokenCreated'], // Webhook related event: - RequestedSendWebhookMessages::class => ['FireflyIII\Handlers\Events\WebhookEventHandler@sendWebhookMessages'], + RequestedSendWebhookMessages::class => ['FireflyIII\Handlers\Events\WebhookEventHandler@sendWebhookMessages'], // account related events: - StoredAccount::class => ['FireflyIII\Handlers\Events\StoredAccountEventHandler@recalculateCredit'], - UpdatedAccount::class => ['FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit'], + StoredAccount::class => ['FireflyIII\Handlers\Events\StoredAccountEventHandler@recalculateCredit'], + UpdatedAccount::class => ['FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit'], // subscription related events: // SubscriptionNeedsExtensionOrRenewal::class => [ @@ -97,7 +97,7 @@ class EventServiceProvider extends ServiceProvider // ], // audit log events: - TriggeredAuditLog::class => ['FireflyIII\Handlers\Events\AuditEventHandler@storeAuditEvent'], + TriggeredAuditLog::class => ['FireflyIII\Handlers\Events\AuditEventHandler@storeAuditEvent'], // piggy bank related events: // PiggyBankAmountIsChanged::class => [ // 'FireflyIII\Handlers\Events\Model\PiggyBankEventHandler@changePiggyAmount', @@ -137,14 +137,12 @@ class EventServiceProvider extends ServiceProvider // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFAFailedAttemptsMail', // ], // preferences - UserGroupChangedPrimaryCurrency::class => ['FireflyIII\Handlers\Events\PreferencesEventHandler@resetPrimaryCurrencyAmounts'] + UserGroupChangedPrimaryCurrency::class => ['FireflyIII\Handlers\Events\PreferencesEventHandler@resetPrimaryCurrencyAmounts'], ]; /** * Register any events for your application. */ #[Override] - public function boot(): void - { - } + public function boot(): void {} } diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index 7d73f997b2..90038ffb64 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -92,7 +92,7 @@ class FireflyServiceProvider extends ServiceProvider */ public function boot(): void { - Validator::resolver(static fn($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages)); + Validator::resolver(static fn ($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages)); } /** @@ -103,22 +103,22 @@ class FireflyServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind('preferences', static fn(): Preferences => new Preferences()); + $this->app->bind('preferences', static fn (): Preferences => new Preferences()); - $this->app->bind('fireflyconfig', static fn(): FireflyConfig => new FireflyConfig()); - $this->app->bind('navigation', static fn(): Navigation => new Navigation()); - $this->app->bind('amount', static fn(): Amount => new Amount()); + $this->app->bind('fireflyconfig', static fn (): FireflyConfig => new FireflyConfig()); + $this->app->bind('navigation', static fn (): Navigation => new Navigation()); + $this->app->bind('amount', static fn (): Amount => new Amount()); - $this->app->bind('steam', static fn(): Steam => new Steam()); - $this->app->bind('balance', static fn(): Balance => new Balance()); - $this->app->bind('expandedform', static fn(): ExpandedForm => new ExpandedForm()); + $this->app->bind('steam', static fn (): Steam => new Steam()); + $this->app->bind('balance', static fn (): Balance => new Balance()); + $this->app->bind('expandedform', static fn (): ExpandedForm => new ExpandedForm()); - $this->app->bind('accountform', static fn(): AccountForm => new AccountForm()); - $this->app->bind('currencyform', static fn(): CurrencyForm => new CurrencyForm()); + $this->app->bind('accountform', static fn (): AccountForm => new AccountForm()); + $this->app->bind('currencyform', static fn (): CurrencyForm => new CurrencyForm()); - $this->app->bind('piggybankform', static fn(): PiggyBankForm => new PiggyBankForm()); + $this->app->bind('piggybankform', static fn (): PiggyBankForm => new PiggyBankForm()); - $this->app->bind('ruleform', static fn(): RuleForm => new RuleForm()); + $this->app->bind('ruleform', static fn (): RuleForm => new RuleForm()); // chart generator: $this->app->bind(GeneratorInterface::class, ChartJsGenerator::class); diff --git a/app/Providers/FireflySessionProvider.php b/app/Providers/FireflySessionProvider.php index d25f068068..9cdc725c67 100644 --- a/app/Providers/FireflySessionProvider.php +++ b/app/Providers/FireflySessionProvider.php @@ -51,7 +51,7 @@ class FireflySessionProvider extends ServiceProvider */ protected function registerSessionManager(): void { - $this->app->singleton('session', static fn($app): SessionManager => new SessionManager($app)); + $this->app->singleton('session', static fn ($app): SessionManager => new SessionManager($app)); } /** @@ -59,11 +59,11 @@ class FireflySessionProvider extends ServiceProvider */ protected function registerSessionDriver(): void { - $this->app->singleton('session.store', static fn($app) => ( + $this->app->singleton('session.store', static fn ($app) // First, we will create the session manager which is responsible for the // creation of the various session drivers when they are needed by the // application instance, and will resolve them on a lazy load basis. - $app->make('session')->driver() - )); + => $app->make('session')->driver() + ); } } diff --git a/app/Providers/JournalServiceProvider.php b/app/Providers/JournalServiceProvider.php index b6044e13ff..6305ada76b 100644 --- a/app/Providers/JournalServiceProvider.php +++ b/app/Providers/JournalServiceProvider.php @@ -45,9 +45,7 @@ class JournalServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/PiggyBankServiceProvider.php b/app/Providers/PiggyBankServiceProvider.php index 21b3ffcad6..c2c3c16ba6 100644 --- a/app/Providers/PiggyBankServiceProvider.php +++ b/app/Providers/PiggyBankServiceProvider.php @@ -37,9 +37,7 @@ class PiggyBankServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/RecurringServiceProvider.php b/app/Providers/RecurringServiceProvider.php index 157d56dc35..b4f4e49070 100644 --- a/app/Providers/RecurringServiceProvider.php +++ b/app/Providers/RecurringServiceProvider.php @@ -37,9 +37,7 @@ class RecurringServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 2002ff2302..f9147a91b0 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -34,7 +34,7 @@ class RouteServiceProvider extends ServiceProvider { public const string HOME = '/'; - protected $namespace = ''; + protected $namespace = ''; /** * Define the routes for the application. @@ -46,12 +46,14 @@ class RouteServiceProvider extends ServiceProvider Route::prefix('api') ->middleware('api') ->namespace($this->namespace) - ->group(base_path('routes/api.php')); + ->group(base_path('routes/api.php')) + ; Route::prefix('api/v1/cron') ->middleware('api_basic') ->namespace($this->namespace) - ->group(base_path('routes/api-noauth.php')); + ->group(base_path('routes/api-noauth.php')) + ; Route::middleware('web')->namespace($this->namespace)->group(base_path('routes/web.php')); }); diff --git a/app/Providers/RuleGroupServiceProvider.php b/app/Providers/RuleGroupServiceProvider.php index 634ffc0630..021d6c1c62 100644 --- a/app/Providers/RuleGroupServiceProvider.php +++ b/app/Providers/RuleGroupServiceProvider.php @@ -37,9 +37,7 @@ class RuleGroupServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/RuleServiceProvider.php b/app/Providers/RuleServiceProvider.php index 9e913340e4..d5e5943e77 100644 --- a/app/Providers/RuleServiceProvider.php +++ b/app/Providers/RuleServiceProvider.php @@ -37,9 +37,7 @@ class RuleServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Providers/SearchServiceProvider.php b/app/Providers/SearchServiceProvider.php index 8afeefa9de..0d7bc43853 100644 --- a/app/Providers/SearchServiceProvider.php +++ b/app/Providers/SearchServiceProvider.php @@ -39,9 +39,7 @@ class SearchServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. @@ -49,7 +47,7 @@ class SearchServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind(static fn(): QueryParserInterface => app(QueryParser::class)); + $this->app->bind(static fn (): QueryParserInterface => app(QueryParser::class)); $this->app->bind(static function (Application $app): SearchInterface { /** @var OperatorQuerySearch $search */ diff --git a/app/Providers/TagServiceProvider.php b/app/Providers/TagServiceProvider.php index 843a801e9b..2ac65fabd4 100644 --- a/app/Providers/TagServiceProvider.php +++ b/app/Providers/TagServiceProvider.php @@ -39,9 +39,7 @@ class TagServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void - { - } + public function boot(): void {} /** * Register the application services. diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 228df9b904..63dfcbfe56 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -61,7 +61,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Moved here from account CRUD. */ - public function destroy(Account $account, null|Account $moveTo): bool + public function destroy(Account $account, ?Account $moveTo): bool { /** @var AccountDestroyService $service */ $service = app(AccountDestroyService::class); @@ -83,7 +83,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->accounts() ->where('name', $account->name) ->where('id', '!=', $account->id) - ->first(); + ->first() + ; if (null !== $byName) { $result->push($account); $result->push($byName); @@ -95,7 +96,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->accounts() ->where('iban', $account->iban) ->where('id', '!=', $account->id) - ->first(); + ->first() + ; if (null !== $byIban) { $result->push($account); $result->push($byIban); @@ -109,7 +111,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $result; } - public function findByAccountNumber(string $number, array $types): null|Account + public function findByAccountNumber(string $number, array $types): ?Account { $dbQuery = $this->user ->accounts() @@ -119,7 +121,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac $json = json_encode($number); $q1->where('account_meta.name', '=', 'account_number'); $q1->where('account_meta.data', '=', $json); - }); + }) + ; if (0 !== count($types)) { $dbQuery->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -130,13 +133,14 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $dbQuery->first(['accounts.*']); } - public function findByIbanNull(string $iban, array $types): null|Account + public function findByIbanNull(string $iban, array $types): ?Account { $iban = Steam::filterSpaces($iban); $query = $this->user ->accounts() ->where('iban', '!=', '') - ->whereNotNull('iban'); + ->whereNotNull('iban') + ; if (0 !== count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -147,9 +151,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $query->where('iban', $iban)->first(['accounts.*']); } - public function findByName(string $name, array $types): null|Account + public function findByName(string $name, array $types): ?Account { - $query = $this->user->accounts(); + $query = $this->user->accounts(); if (0 !== count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -174,7 +178,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return account type or null if not found. */ - public function getAccountTypeByType(string $type): null|AccountType + public function getAccountTypeByType(string $type): ?AccountType { return AccountType::whereType(ucfirst($type))->first(); } @@ -201,8 +205,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac 'accountmeta' => static function (HasMany $query): void { $query->where('name', 'account_role'); }, - 'attachments' - ]); + 'attachments', + ]) + ; if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -216,15 +221,15 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getAttachments(Account $account): Collection { - $set = $account->attachments()->get(); + $set = $account->attachments()->get(); /** @var Storage $disk */ $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + $attachment->notes_text = null !== $notes ? $notes->text : ''; return $attachment; }); @@ -236,7 +241,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getCashAccount(): Account { /** @var AccountType $type */ - $type = AccountType::where('type', AccountTypeEnum::CASH->value)->first(); + $type = AccountType::where('type', AccountTypeEnum::CASH->value)->first(); /** @var AccountFactory $factory */ $factory = app(AccountFactory::class); @@ -245,12 +250,13 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $factory->findOrCreate('Cash account', $type->type); } - public function getCreditTransactionGroup(Account $account): null|TransactionGroup + public function getCreditTransactionGroup(Account $account): ?TransactionGroup { $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::LIABILITY_CREDIT->value]) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; return $journal?->transactionGroup; } @@ -261,7 +267,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->accounts() ->with(['accountmeta' => static function (HasMany $query): void { // @phpstan-ignore-line $query->where('name', 'account_role'); - }]); + }]) + ; if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -273,7 +280,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $query->get(['accounts.*']); } - public function getLocation(Account $account): null|Location + public function getLocation(Account $account): ?Location { /** @var null|Location */ return $account->locations()->first(); @@ -282,7 +289,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Get note text or null. */ - public function getNoteText(Account $account): null|string + public function getNoteText(Account $account): ?string { return $account->notes()->first()?->text; } @@ -290,12 +297,13 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): null|string + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string { - $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::LIABILITY_CREDIT->value]) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; if (null === $journal) { return null; } @@ -313,28 +321,30 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return date of opening balance as string or null. */ - public function getOpeningBalanceDate(Account $account): null|string + public function getOpeningBalanceDate(Account $account): ?string { return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::LIABILITY_CREDIT->value]) ->first(['transaction_journals.*']) - ?->date->format('Y-m-d H:i:s'); + ?->date->format('Y-m-d H:i:s') + ; } - public function getOpeningBalanceGroup(Account $account): null|TransactionGroup + public function getOpeningBalanceGroup(Account $account): ?TransactionGroup { $journal = $this->getOpeningBalance($account); return $journal?->transactionGroup; } - public function getOpeningBalance(Account $account): null|TransactionJournal + public function getOpeningBalance(Account $account): ?TransactionJournal { return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value]) - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; } public function getPiggyBanks(Account $account): Collection @@ -345,7 +355,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * @throws FireflyException */ - public function getReconciliation(Account $account): null|Account + public function getReconciliation(Account $account): ?Account { if (AccountTypeEnum::ASSET->value !== $account->accountType->type) { throw new FireflyException(sprintf('%s is not an asset account.', $account->name)); @@ -354,39 +364,40 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac $name = trans('firefly.reconciliation_account_name', ['name' => $account->name, 'currency' => $currency->code]); /** @var AccountType $type */ - $type = AccountType::where('type', AccountTypeEnum::RECONCILIATION->value)->first(); + $type = AccountType::where('type', AccountTypeEnum::RECONCILIATION->value)->first(); /** @var null|Account $current */ - $current = $this->user + $current = $this->user ->accounts() ->where('account_type_id', $type->id) ->where('name', $name) - ->first(); + ->first() + ; if (null !== $current) { return $current; } - $data = [ + $data = [ 'account_type_id' => null, 'account_type_name' => AccountTypeEnum::RECONCILIATION->value, 'active' => true, 'name' => $name, 'currency_id' => $currency->id, - 'currency_code' => $currency->code + 'currency_code' => $currency->code, ]; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($account->user); return $factory->create($data); } - public function getAccountCurrency(Account $account): null|TransactionCurrency + public function getAccountCurrency(Account $account): ?TransactionCurrency { - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); // return null if not in this list. if (!in_array($type, $list, true)) { @@ -403,9 +414,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return meta value for account. Null if not found. */ - public function getMetaValue(Account $account, string $field): null|string + public function getMetaValue(Account $account, string $field): ?string { - $result = $account->accountMeta->filter(static fn(AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field)); + $result = $account->accountMeta->filter(static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field)); if (0 === $result->count()) { return null; } @@ -421,10 +432,11 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $this->user ->accounts() ->accountTypeIn($types) - ->count(); + ->count() + ; } - public function find(int $accountId): null|Account + public function find(int $accountId): ?Account { /** @var null|Account */ return $this->user->accounts()->find($accountId); @@ -453,7 +465,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function maxOrder(string $type): int { - $sets = [ + $sets = [ AccountTypeEnum::ASSET->value => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], AccountTypeEnum::EXPENSE->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], AccountTypeEnum::REVENUE->value => [AccountTypeEnum::REVENUE->value], @@ -461,20 +473,20 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ], AccountTypeEnum::DEBT->value => [ AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ], AccountTypeEnum::MORTGAGE->value => [ AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, - AccountTypeEnum::MORTGAGE->value - ] + AccountTypeEnum::MORTGAGE->value, + ], ]; if (array_key_exists(ucfirst($type), $sets)) { $order = (int) $this->getAccountsByType($sets[ucfirst($type)])->max('order'); @@ -486,24 +498,24 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, - AccountTypeEnum::RECONCILIATION->value + AccountTypeEnum::RECONCILIATION->value, ]; - $order = (int) $this->getAccountsByType($specials)->max('order'); + $order = (int) $this->getAccountsByType($specials)->max('order'); Log::debug(sprintf('Return max order of "%s" set (specials!): %d', $type, $order)); return $order; } - public function getAccountsByType(array $types, null|array $sort = []): Collection + public function getAccountsByType(array $types, ?array $sort = []): Collection { - $res = array_intersect([ + $res = array_intersect([ AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, - AccountTypeEnum::DEBT->value + AccountTypeEnum::DEBT->value, ], $types); - $query = $this->user->accounts(); + $query = $this->user->accounts(); if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -536,7 +548,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the date of the very first transaction in this account. */ - public function oldestJournalDate(Account $account): null|Carbon + public function oldestJournalDate(Account $account): ?Carbon { $journal = $this->oldestJournal($account); @@ -546,7 +558,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the date of the very first transaction in this account. */ - public function oldestJournal(Account $account): null|TransactionJournal + public function oldestJournal(Account $account): ?TransactionJournal { /** @var null|TransactionJournal $first */ $first = $account @@ -556,7 +568,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->orderBy('transaction_journals.order', 'DESC') ->where('transaction_journals.user_id', $this->user->id) ->orderBy('transaction_journals.id', 'ASC') - ->first(['transaction_journals.id']); + ->first(['transaction_journals.id']) + ; if (null !== $first) { /** @var null|TransactionJournal */ return TransactionJournal::find($first->id); @@ -599,9 +612,10 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount' + 'transactions.foreign_amount', ]) - ->toArray(); + ->toArray() + ; } public function resetAccountOrder(): void @@ -610,7 +624,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], // [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], // [AccountTypeEnum::REVENUE->value], - [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value] + [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value], // [AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, AccountTypeEnum::RECONCILIATION->value], ]; foreach ($sets as $set) { @@ -631,19 +645,20 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac } } // reset the rest to zero. - $all = [ + $all = [ AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]; $this->user ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereNotIn('account_types.type', $all) - ->update(['order' => 0]); + ->update(['order' => 0]) + ; } /** @@ -665,7 +680,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->orderBy('accounts.order', 'ASC') ->orderBy('accounts.account_type_id', 'ASC') ->orderBy('accounts.name', 'ASC') - ->with(['accountType']); + ->with(['accountType']) + ; if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); @@ -692,7 +708,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->orderBy('accounts.order', 'ASC') ->orderBy('accounts.account_type_id', 'ASC') ->orderBy('accounts.name', 'ASC') - ->with(['accountType', 'accountMeta']); + ->with(['accountType', 'accountMeta']) + ; if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php index 262e583b82..43b3334f15 100644 --- a/app/Repositories/Account/AccountRepositoryInterface.php +++ b/app/Repositories/Account/AccountRepositoryInterface.php @@ -56,34 +56,34 @@ interface AccountRepositoryInterface /** * Moved here from account CRUD. */ - public function destroy(Account $account, null|Account $moveTo): bool; + public function destroy(Account $account, ?Account $moveTo): bool; /** * Find account with same name OR same IBAN or both, but not the same type or ID. */ public function expandWithDoubles(Collection $accounts): Collection; - public function find(int $accountId): null|Account; + public function find(int $accountId): ?Account; - public function findByAccountNumber(string $number, array $types): null|Account; + public function findByAccountNumber(string $number, array $types): ?Account; - public function findByIbanNull(string $iban, array $types): null|Account; + public function findByIbanNull(string $iban, array $types): ?Account; - public function findByName(string $name, array $types): null|Account; + public function findByName(string $name, array $types): ?Account; - public function getAccountCurrency(Account $account): null|TransactionCurrency; + public function getAccountCurrency(Account $account): ?TransactionCurrency; /** * Return account type or null if not found. */ - public function getAccountTypeByType(string $type): null|AccountType; + public function getAccountTypeByType(string $type): ?AccountType; public function getAccountsById(array $accountIds): Collection; /** * @param array $types */ - public function getAccountsByType(array $types, null|array $sort = []): Collection; + public function getAccountsByType(array $types, ?array $sort = []): Collection; public function getActiveAccountsByType(array $types): Collection; @@ -91,45 +91,45 @@ interface AccountRepositoryInterface public function getCashAccount(): Account; - public function getCreditTransactionGroup(Account $account): null|TransactionGroup; + public function getCreditTransactionGroup(Account $account): ?TransactionGroup; public function getInactiveAccountsByType(array $types): Collection; /** * Get account location, if any. */ - public function getLocation(Account $account): null|Location; + public function getLocation(Account $account): ?Location; /** * Return meta value for account. Null if not found. */ - public function getMetaValue(Account $account, string $field): null|string; + public function getMetaValue(Account $account, string $field): ?string; /** * Get note text or null. */ - public function getNoteText(Account $account): null|string; + public function getNoteText(Account $account): ?string; - public function getOpeningBalance(Account $account): null|TransactionJournal; + public function getOpeningBalance(Account $account): ?TransactionJournal; /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): null|string; + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string; /** * Return date of opening balance as string or null. */ - public function getOpeningBalanceDate(Account $account): null|string; + public function getOpeningBalanceDate(Account $account): ?string; - public function getOpeningBalanceGroup(Account $account): null|TransactionGroup; + public function getOpeningBalanceGroup(Account $account): ?TransactionGroup; public function getPiggyBanks(Account $account): Collection; /** * Find or create the opposing reconciliation account. */ - public function getReconciliation(Account $account): null|Account; + public function getReconciliation(Account $account): ?Account; public function getUsedCurrencies(Account $account): Collection; @@ -140,12 +140,12 @@ interface AccountRepositoryInterface /** * Returns the date of the very first transaction in this account. */ - public function oldestJournal(Account $account): null|TransactionJournal; + public function oldestJournal(Account $account): ?TransactionJournal; /** * Returns the date of the very first transaction in this account. */ - public function oldestJournalDate(Account $account): null|Carbon; + public function oldestJournalDate(Account $account): ?Carbon; public function periodCollection(Account $account, Carbon $start, Carbon $end): array; diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php index 9461468db2..d5e8d011eb 100644 --- a/app/Repositories/Account/AccountTasker.php +++ b/app/Repositories/Account/AccountTasker.php @@ -48,7 +48,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface */ public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array { - $yesterday = clone $start; + $yesterday = clone $start; $yesterday->subDay()->endOfDay(); // exactly up until $start but NOT including. $end->endOfDay(); // needs to be end of day to be correct. Log::debug(sprintf('getAccountReport: accountsBalancesInRange("%s", "%s")', $yesterday->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); @@ -56,15 +56,15 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface Log::debug('Start of accountreport'); /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $repository = app(AccountRepositoryInterface::class); + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); - $return = ['accounts' => [], 'sums' => []]; + $return = ['accounts' => [], 'sums' => []]; /** @var Account $account */ foreach ($accounts as $account) { - $id = $account->id; - $currency = $repository->getAccountCurrency($account) ?? $primaryCurrency; + $id = $account->id; + $currency = $repository->getAccountCurrency($account) ?? $primaryCurrency; $return['sums'][$currency->id] ??= [ 'start' => '0', 'end' => '0', @@ -73,22 +73,22 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; - $entry = [ + $entry = [ 'name' => $account->name, 'id' => $account->id, 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; // get first journal date: - $first = $repository->oldestJournal($account); - $entry['start_balance'] = $startSet[$account->id]['balance'] ?? '0'; - $entry['end_balance'] = $endSet[$account->id]['balance'] ?? '0'; + $first = $repository->oldestJournal($account); + $entry['start_balance'] = $startSet[$account->id]['balance'] ?? '0'; + $entry['end_balance'] = $endSet[$account->id]['balance'] ?? '0'; // first journal exists, and is on start, then this is the actual opening balance: if (null !== $first && $first->date->isSameDay($yesterday) && TransactionTypeEnum::OPENING_BALANCE->value === $first->transactionType->type) { @@ -102,8 +102,8 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface )); } $return['sums'][$currency->id]['start'] = bcadd($return['sums'][$currency->id]['start'], (string) $entry['start_balance']); - $return['sums'][$currency->id]['end'] = bcadd($return['sums'][$currency->id]['end'], $entry['end_balance']); - $return['accounts'][$id] = $entry; + $return['sums'][$currency->id]['end'] = bcadd($return['sums'][$currency->id]['end'], $entry['end_balance']); + $return['accounts'][$id] = $entry; } foreach (array_keys($return['sums']) as $index) { @@ -128,13 +128,13 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $collector->setSourceAccounts($accounts)->setRange($start, $end); $collector->excludeDestinationAccounts($accounts); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation(); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); - $report = $this->groupExpenseByDestination($journals); + $report = $this->groupExpenseByDestination($journals); // sort the result // Obtain a list of columns - $sum = []; + $sum = []; foreach ($report['accounts'] as $accountId => $row) { $sum[$accountId] = (float) $row['sum']; // intentional float } @@ -149,16 +149,16 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ - $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$primaryCurrency->id => $primaryCurrency]; - $report = ['accounts' => [], 'sums' => []]; + $currencyRepos = app(CurrencyRepositoryInterface::class); + $currencies = [$primaryCurrency->id => $primaryCurrency]; + $report = ['accounts' => [], 'sums' => []]; /** @var array $journal */ foreach ($array as $journal) { - $sourceId = (int) $journal['destination_account_id']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%s-%s', $sourceId, $currencyId); - $currencies[$currencyId] ??= $currencyRepos->find($currencyId); + $sourceId = (int) $journal['destination_account_id']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%s-%s', $sourceId, $currencyId); + $currencies[$currencyId] ??= $currencyRepos->find($currencyId); $report['accounts'][$key] ??= [ 'id' => $sourceId, 'name' => $journal['destination_account_name'], @@ -169,7 +169,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_name' => $currencies[$currencyId]->name, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code, - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places + 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, ]; $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], (string) $journal['amount']); @@ -183,14 +183,14 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface if ($report['accounts'][$key]['count'] > 1) { $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); } - $currencyId = $report['accounts'][$key]['currency_id']; + $currencyId = $report['accounts'][$key]['currency_id']; $report['sums'][$currencyId] ??= [ 'sum' => '0', 'currency_id' => $report['accounts'][$key]['currency_id'], 'currency_name' => $report['accounts'][$key]['currency_name'], 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], 'currency_code' => $report['accounts'][$key]['currency_code'], - 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'] + 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], ]; $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); } @@ -212,11 +212,11 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $collector->setDestinationAccounts($accounts)->setRange($start, $end); $collector->excludeSourceAccounts($accounts); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation(); - $report = $this->groupIncomeBySource($collector->getExtractedJournals()); + $report = $this->groupIncomeBySource($collector->getExtractedJournals()); // sort the result // Obtain a list of columns - $sum = []; + $sum = []; foreach ($report['accounts'] as $accountId => $row) { $sum[$accountId] = (float) $row['sum']; // intentional float } @@ -231,15 +231,15 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ - $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$primaryCurrency->id => $primaryCurrency]; - $report = ['accounts' => [], 'sums' => []]; + $currencyRepos = app(CurrencyRepositoryInterface::class); + $currencies = [$primaryCurrency->id => $primaryCurrency]; + $report = ['accounts' => [], 'sums' => []]; /** @var array $journal */ foreach ($array as $journal) { - $sourceId = (int) $journal['source_account_id']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%s-%s', $sourceId, $currencyId); + $sourceId = (int) $journal['source_account_id']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%s-%s', $sourceId, $currencyId); if (!array_key_exists($key, $report['accounts'])) { $currencies[$currencyId] ??= $currencyRepos->find($currencyId); $report['accounts'][$key] = [ @@ -252,7 +252,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_name' => $currencies[$currencyId]->name, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code, - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places + 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, ]; } $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], bcmul((string) $journal['amount'], '-1')); @@ -264,14 +264,14 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface if ($report['accounts'][$key]['count'] > 1) { $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); } - $currencyId = $report['accounts'][$key]['currency_id']; + $currencyId = $report['accounts'][$key]['currency_id']; $report['sums'][$currencyId] ??= [ 'sum' => '0', 'currency_id' => $report['accounts'][$key]['currency_id'], 'currency_name' => $report['accounts'][$key]['currency_name'], 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], 'currency_code' => $report['accounts'][$key]['currency_code'], - 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'] + 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], ]; $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); } diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php index e1e6814042..a81863f50b 100644 --- a/app/Repositories/Account/OperationsRepository.php +++ b/app/Repositories/Account/OperationsRepository.php @@ -71,19 +71,19 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn { $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $journalId = (int) $journal['transaction_journal_id']; + $currencyId = (int) $journal['currency_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId] ??= [ 'currency_id' => $journal['currency_id'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'transaction_journals' => [] + 'transaction_journals' => [], ]; $array[$currencyId]['transaction_journals'][$journalId] = [ - 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line + 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line 'date' => $journal['date'], 'transaction_journal_id' => $journalId, 'budget_name' => $journal['budget_name'], @@ -96,7 +96,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_iban' => $journal['destination_account_iban'], 'tags' => $journal['tags'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'] + 'transaction_group_id' => $journal['transaction_group_id'], ]; } @@ -108,7 +108,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified accounts. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array { $journals = $this->getTransactions($start, $end, $accounts, TransactionTypeEnum::DEPOSIT->value); @@ -121,9 +121,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -138,9 +138,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn string $type, Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $opposing = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $opposing = null, + ?TransactionCurrency $currency = null ): array { $start->startOfDay(); $end->endOfDay(); @@ -174,7 +174,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if ($currency instanceof TransactionCurrency) { $collector->setCurrency($currency); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // same but for foreign currencies: if ($currency instanceof TransactionCurrency) { @@ -198,10 +198,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } } - $result = $collector->getExtractedJournals(); + $result = $collector->getExtractedJournals(); // do not use array_merge because you want keys to overwrite (otherwise you get double results): - $journals = $result + $journals; + $journals = $result + $journals; } return $journals; @@ -220,9 +220,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumExpensesByDestination( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -242,9 +242,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumExpensesBySource( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -257,9 +257,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumIncome( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); @@ -272,9 +272,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumIncomeByDestination( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); @@ -287,16 +287,16 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumIncomeBySource( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); return $this->groupByDirection($journals, 'source', 'positive'); } - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::TRANSFER->value, $start, $end, $accounts, null, $currency); @@ -311,12 +311,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn foreach ($journals as $journal) { $return = $this->groupByEitherJournal($return, $journal); } - $final = []; + $final = []; foreach ($return as $array) { $array['difference_float'] = (float) $array['difference']; - $array['in_float'] = (float) $array['in']; - $array['out_float'] = (float) $array['out']; - $final[] = $array; + $array['in_float'] = (float) $array['in']; + $array['out_float'] = (float) $array['out']; + $final[] = $array; } return $final; @@ -324,12 +324,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn private function groupByEitherJournal(array $return, array $journal): array { - $sourceId = $journal['source_account_id']; - $destinationId = $journal['destination_account_id']; - $currencyId = $journal['currency_id']; - $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); - $destKey = sprintf('%d-%d', $currencyId, $destinationId); - $amount = Steam::positive($journal['amount']); + $sourceId = $journal['source_account_id']; + $destinationId = $journal['destination_account_id']; + $currencyId = $journal['currency_id']; + $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); + $destKey = sprintf('%d-%d', $currencyId, $destinationId); + $amount = Steam::positive($journal['amount']); // source first $return[$sourceKey] ??= [ @@ -342,11 +342,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'] + 'currency_code' => $journal['currency_code'], ]; // dest next: - $return[$destKey] ??= [ + $return[$destKey] ??= [ 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', @@ -356,23 +356,23 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'] + 'currency_code' => $journal['currency_code'], ]; // source account? money goes out! - $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); + $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); $return[$sourceKey]['difference'] = bcadd($return[$sourceKey]['out'], (string) $return[$sourceKey]['in']); // destination account? money comes in: - $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); - $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); + $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); + $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); // foreign currency if (null !== $journal['foreign_currency_id'] && null !== $journal['foreign_amount']) { - $currencyId = $journal['foreign_currency_id']; - $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); - $destKey = sprintf('%d-%d', $currencyId, $destinationId); - $amount = Steam::positive($journal['foreign_amount']); + $currencyId = $journal['foreign_currency_id']; + $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); + $destKey = sprintf('%d-%d', $currencyId, $destinationId); + $amount = Steam::positive($journal['foreign_amount']); // same as above: // source first @@ -386,11 +386,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['foreign_currency_code'] + 'currency_code' => $journal['foreign_currency_code'], ]; // dest next: - $return[$destKey] ??= [ + $return[$destKey] ??= [ 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', @@ -400,15 +400,15 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['foreign_currency_code'] + 'currency_code' => $journal['foreign_currency_code'], ]; // source account? money goes out! (same as above) - $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); + $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); $return[$sourceKey]['difference'] = bcadd($return[$sourceKey]['out'], (string) $return[$sourceKey]['in']); // destination account? money comes in: - $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); - $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); + $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); + $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); } return $return; diff --git a/app/Repositories/Account/OperationsRepositoryInterface.php b/app/Repositories/Account/OperationsRepositoryInterface.php index 3989e2c659..c778b0e2dd 100644 --- a/app/Repositories/Account/OperationsRepositoryInterface.php +++ b/app/Repositories/Account/OperationsRepositoryInterface.php @@ -56,7 +56,7 @@ interface OperationsRepositoryInterface * which have the specified accounts. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; /** * Sum of withdrawal journals in period for a set of accounts, grouped per currency. Amounts are always negative. @@ -66,9 +66,9 @@ interface OperationsRepositoryInterface public function sumExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array; /** @@ -80,9 +80,9 @@ interface OperationsRepositoryInterface public function sumExpensesByDestination( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array; /** @@ -94,9 +94,9 @@ interface OperationsRepositoryInterface public function sumExpensesBySource( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $expense = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $expense = null, + ?TransactionCurrency $currency = null ): array; /** @@ -107,9 +107,9 @@ interface OperationsRepositoryInterface public function sumIncome( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array; /** @@ -121,9 +121,9 @@ interface OperationsRepositoryInterface public function sumIncomeByDestination( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array; /** @@ -135,13 +135,13 @@ interface OperationsRepositoryInterface public function sumIncomeBySource( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $revenue = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $revenue = null, + ?TransactionCurrency $currency = null ): array; /** * Sum of transfers in period for a set of accounts, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; } diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index 08241fe624..baef97884d 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -54,7 +54,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** @var AttachmentHelperInterface $helper */ $helper = app(AttachmentHelperInterface::class); - $path = $helper->getAttachmentLocation($attachment); + $path = $helper->getAttachmentLocation($attachment); try { Storage::disk('upload')->delete($path); @@ -103,7 +103,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** * Get attachment note text or empty string. */ - public function getNoteText(Attachment $attachment): null|string + public function getNoteText(Attachment $attachment): ?string { $note = $attachment->notes()->first(); if (null !== $note) { @@ -121,7 +121,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** @var AttachmentFactory $factory */ $factory = app(AttachmentFactory::class); $factory->setUser($this->user); - $result = $factory->create($data); + $result = $factory->create($data); if (null === $result) { throw new FireflyException('Could not store attachment.'); } @@ -141,7 +141,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn // update model (move attachment) // should be validated already: if (array_key_exists('attachable_type', $data) && array_key_exists('attachable_id', $data)) { - $attachment->attachable_id = (int) $data['attachable_id']; + $attachment->attachable_id = (int) $data['attachable_id']; $attachment->attachable_type = sprintf('FireflyIII\Models\%s', $data['attachable_type']); } @@ -168,7 +168,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn return true; } - $dbNote = $attachment->notes()->first(); + $dbNote = $attachment->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($attachment); diff --git a/app/Repositories/Attachment/AttachmentRepositoryInterface.php b/app/Repositories/Attachment/AttachmentRepositoryInterface.php index df4635811d..56078984e2 100644 --- a/app/Repositories/Attachment/AttachmentRepositoryInterface.php +++ b/app/Repositories/Attachment/AttachmentRepositoryInterface.php @@ -51,7 +51,7 @@ interface AttachmentRepositoryInterface /** * Get attachment note text or empty string. */ - public function getNoteText(Attachment $attachment): null|string; + public function getNoteText(Attachment $attachment): ?string; /** * @throws FireflyException diff --git a/app/Repositories/AuditLogEntry/ALERepository.php b/app/Repositories/AuditLogEntry/ALERepository.php index e5e804ac41..50e4adaf08 100644 --- a/app/Repositories/AuditLogEntry/ALERepository.php +++ b/app/Repositories/AuditLogEntry/ALERepository.php @@ -41,13 +41,13 @@ class ALERepository implements ALERepositoryInterface public function store(array $data): AuditLogEntry { - $auditLogEntry = new AuditLogEntry(); + $auditLogEntry = new AuditLogEntry(); $auditLogEntry->auditable()->associate($data['auditable']); $auditLogEntry->changer()->associate($data['changer']); $auditLogEntry->action = $data['action']; $auditLogEntry->before = $data['before']; - $auditLogEntry->after = $data['after']; + $auditLogEntry->after = $data['after']; $auditLogEntry->save(); return $auditLogEntry; diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 2904143f52..7bcc0a78fe 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -90,7 +90,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $set = $this->user ->bills() ->orderBy('order', 'ASC') - ->get(); + ->get() + ; $current = 1; foreach ($set as $bill) { if ($bill->order !== $current) { @@ -119,7 +120,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find bill by parameters. */ - public function findBill(null|int $billId, null|string $billName): null|Bill + public function findBill(?int $billId, ?string $billName): ?Bill { if (null !== $billId) { $searchResult = $this->find($billId); @@ -145,7 +146,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find a bill by ID. */ - public function find(int $billId): null|Bill + public function find(int $billId): ?Bill { /** @var null|Bill */ return $this->user->bills()->find($billId); @@ -154,13 +155,14 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find a bill by name. */ - public function findByName(string $name): null|Bill + public function findByName(string $name): ?Bill { /** @var null|Bill */ return $this->user ->bills() ->where('name', $name) - ->first(['bills.*']); + ->first(['bills.*']) + ; } /** @@ -172,9 +174,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + $attachment->notes_text = null !== $notes ? $notes->text : ''; return $attachment; }); @@ -187,7 +189,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->orderBy('order', 'ASC') ->orderBy('active', 'DESC') ->orderBy('name', 'ASC') - ->get(); + ->get() + ; } public function getBillsForAccounts(Collection $accounts): Collection @@ -206,7 +209,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'bills.repeat_freq', 'bills.skip', 'bills.automatch', - 'bills.active' + 'bills.active', ]; $ids = $accounts->pluck('id')->toArray(); @@ -223,7 +226,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->orderBy('bills.active', 'DESC') ->orderBy('bills.name', 'ASC') ->groupBy($fields) - ->get($fields); + ->get($fields) + ; } /** @@ -234,7 +238,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface return $this->user ->bills() ->whereIn('id', $billIds) - ->get(); + ->get() + ; } /** @@ -251,7 +256,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function getOverallAverage(Bill $bill): array { /** @var JournalRepositoryInterface $repos */ - $repos = app(JournalRepositoryInterface::class); + $repos = app(JournalRepositoryInterface::class); $repos->setUser($this->user); // get and sort on currency @@ -261,9 +266,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var TransactionJournal $journal */ foreach ($journals as $journal) { /** @var Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', '<', 0)->first(); - $currencyId = (int) $journal->transaction_currency_id; - $currency = $journal->transactionCurrency; + $transaction = $journal->transactions()->where('amount', '<', 0)->first(); + $currencyId = (int) $journal->transaction_currency_id; + $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', 'pc_sum' => '0', @@ -273,9 +278,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; - $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); + $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); @@ -289,7 +294,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); + $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } @@ -302,7 +307,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->bills() ->orderBy('active', 'DESC') ->orderBy('name', 'ASC') - ->paginate($size); + ->paginate($size) + ; } /** @@ -333,8 +339,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'foreign_currency.code AS foreign_currency_code', 'foreign_currency.decimal_places AS foreign_currency_decimal_places', 'transactions.amount', - 'transactions.foreign_amount' - ]); + 'transactions.foreign_amount', + ]) + ; } /** @@ -347,7 +354,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id') ->where('rule_actions.action_type', 'link_to_bill') ->where('rule_actions.action_value', $bill->name) - ->get(['rules.*']); + ->get(['rules.*']) + ; } /** @@ -358,12 +366,13 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function getRulesForBills(Collection $collection): array { - $rules = $this->user + $rules = $this->user ->rules() ->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id') ->where('rule_actions.action_type', 'link_to_bill') - ->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']); - $array = []; + ->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']) + ; + $array = []; /** @var Rule $rule */ foreach ($rules as $rule) { @@ -381,27 +390,28 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function getYearAverage(Bill $bill, Carbon $date): array { /** @var JournalRepositoryInterface $repos */ - $repos = app(JournalRepositoryInterface::class); + $repos = app(JournalRepositoryInterface::class); $repos->setUser($this->user); // get and sort on currency - $result = []; + $result = []; $journals = $bill ->transactionJournals() - ->where('date', '>=', $date->year . '-01-01 00:00:00') - ->where('date', '<=', $date->year . '-12-31 23:59:59') - ->get(); + ->where('date', '>=', $date->year.'-01-01 00:00:00') + ->where('date', '<=', $date->year.'-12-31 23:59:59') + ->get() + ; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { /** @var null|Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', '<', 0)->first(); + $transaction = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $transaction) { continue; } - $currencyId = (int) $journal->transaction_currency_id; - $currency = $journal->transactionCurrency; + $currencyId = (int) $journal->transaction_currency_id; + $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', 'pc_sum' => '0', @@ -410,9 +420,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; - $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); + $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); @@ -426,7 +436,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); + $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } @@ -440,7 +450,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface { /** @var Transaction $transaction */ foreach ($transactions as $transaction) { - $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); + $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); $journal->bill_id = $bill->id; $journal->save(); Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); @@ -452,7 +462,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function nextExpectedMatch(Bill $bill, Carbon $date): Carbon { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($bill->id); $cache->addProperty('nextExpectedMatch'); $cache->addProperty($date); @@ -460,17 +470,17 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface return $cache->get(); } // find the most recent date for this bill NOT in the future. Cache this date: - $start = clone $bill->date; + $start = clone $bill->date; $start->startOfDay(); - Log::debug('nextExpectedMatch: Start is ' . $start->format('Y-m-d')); + Log::debug('nextExpectedMatch: Start is '.$start->format('Y-m-d')); while ($start < $date) { Log::debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s'))); $start = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); - 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 = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); + $end = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); $end->endOfDay(); // see if the bill was paid in this period. @@ -482,8 +492,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $start = clone $end; $end = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); } - Log::debug('nextExpectedMatch: Final start is ' . $start->format('Y-m-d')); - 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); @@ -518,7 +528,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->orderBy('name', 'ASC') ->whereLike('name', $query) ->take($limit) - ->get(); + ->get() + ; } public function setObjectGroup(Bill $bill, string $objectGroupTitle): Bill @@ -548,29 +559,29 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var Bill $bill */ foreach ($bills as $bill) { /** @var Collection $set */ - $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); - $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; + $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; $return[(int) $currency->id] ??= [ 'id' => (string) $currency->id, 'name' => $currency->name, 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]; $setAmount = '0'; /** @var TransactionJournal $transactionJournal */ foreach ($set as $transactionJournal) { // grab currency from transaction. - $transactionCurrency = $transactionJournal->transactionCurrency; + $transactionCurrency = $transactionJournal->transactionCurrency; $return[(int) $transactionCurrency->id] ??= [ 'id' => (string) $transactionCurrency->id, 'name' => $transactionCurrency->name, 'symbol' => $transactionCurrency->symbol, 'code' => $transactionCurrency->code, 'decimal_places' => $transactionCurrency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]; // get currency from transaction as well. @@ -587,7 +598,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // Log::debug(sprintf('Total sum is now %s', $return[$currency->id]['sum'])); } // remove empty sets - $final = []; + $final = []; foreach ($return as $entry) { if (0 === bccomp($entry['sum'], '0')) { continue; @@ -604,7 +615,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->bills() ->where('active', true) ->orderBy('bills.name', 'ASC') - ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]); // @phpstan-ignore-line + ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]) // @phpstan-ignore-line + ; } public function sumUnpaidInRange(Carbon $start, Carbon $end): array @@ -618,9 +630,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var Bill $bill */ foreach ($bills as $bill) { // \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; + $dates = $this->getPayDatesInRange($bill, $start, $end); + $count = $bill->transactionJournals()->after($start)->before($end)->count(); + $total = $dates->count() - $count; // \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()); @@ -629,8 +641,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // Log::debug(sprintf('min field is %s, max field is %s', $minField, $maxField)); if ($total > 0) { - $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; - $average = bcdiv(bcadd($bill->{$maxField} ?? '0', $bill->{$minField} ?? '0'), '2'); + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; + $average = bcdiv(bcadd($bill->{$maxField} ?? '0', $bill->{$minField} ?? '0'), '2'); Log::debug(sprintf('Amount to pay is %s %s (%d times)', $currency->code, $average, $total)); $return[$currency->id] ??= [ 'id' => (string) $currency->id, @@ -638,7 +650,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]; $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], bcmul($average, (string) $total)); } @@ -671,7 +683,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); - $currentStart = clone $nextExpectedMatch; + $currentStart = clone $nextExpectedMatch; } return $set; @@ -706,7 +718,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $this->user ->transactionJournals() ->where('bill_id', $bill->id) - ->update(['bill_id' => null]); + ->update(['bill_id' => null]) + ; } /** diff --git a/app/Repositories/Bill/BillRepositoryInterface.php b/app/Repositories/Bill/BillRepositoryInterface.php index f6b1f287f5..4c021b9684 100644 --- a/app/Repositories/Bill/BillRepositoryInterface.php +++ b/app/Repositories/Bill/BillRepositoryInterface.php @@ -63,17 +63,17 @@ interface BillRepositoryInterface /** * Find a bill by ID. */ - public function find(int $billId): null|Bill; + public function find(int $billId): ?Bill; /** * Find bill by parameters. */ - public function findBill(null|int $billId, null|string $billName): null|Bill; + public function findBill(?int $billId, ?string $billName): ?Bill; /** * Find a bill by name. */ - public function findByName(string $name): null|Bill; + public function findByName(string $name): ?Bill; public function getActiveBills(): Collection; diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index d0a751b5f4..7cffc377b9 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -49,9 +49,9 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** @var AvailableBudget $availableBudget */ foreach ($availableBudgets as $availableBudget) { - $start = $availableBudget->start_date->format('Y-m-d'); - $end = $availableBudget->end_date->format('Y-m-d'); - $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end); + $start = $availableBudget->start_date->format('Y-m-d'); + $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)) { Log::debug(sprintf( 'Found duplicate AB: %s %s, %s-%s. Has been deleted', @@ -69,9 +69,9 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** * Return a list of all available budgets (in all currencies) (for the selected period). */ - public function get(null|Carbon $start = null, null|Carbon $end = null): Collection + public function get(?Carbon $start = null, ?Carbon $end = null): Collection { - $query = $this->user->availableBudgets()->with(['transactionCurrency']); + $query = $this->user->availableBudgets()->with(['transactionCurrency']); if ($start instanceof Carbon && $end instanceof Carbon) { $query->where(static function (Builder $q1) use ($start, $end): void { $q1->where('start_date', '=', $start->format('Y-m-d')); @@ -98,7 +98,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U $availableBudget->delete(); } - public function findById(int $id): null|AvailableBudget + public function findById(int $id): ?AvailableBudget { return $this->user->availableBudgets->find($id); } @@ -106,7 +106,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** * Find existing AB. */ - public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): null|AvailableBudget + public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): ?AvailableBudget { /** @var null|AvailableBudget */ return $this->user @@ -114,13 +114,14 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first(); + ->first() + ; } #[Deprecated] public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string { - $amount = '0'; + $amount = '0'; /** @var null|AvailableBudget $availableBudget */ $availableBudget = $this->user @@ -128,7 +129,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first(); + ->first() + ; if (null !== $availableBudget) { return $availableBudget->amount; } @@ -144,7 +146,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->availableBudgets() ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->get(); + ->get() + ; Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count())); @@ -154,12 +157,12 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** @var AvailableBudget $availableBudget */ foreach ($availableBudgets as $availableBudget) { - $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id + $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? $primary->id : $availableBudget->transaction_currency_id; - $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount'; + $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount'; $return[$currencyId] ??= '0'; - $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field}; + $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field}; $return[$currencyId] = bcadd($return[$currencyId], $amount); Log::debug(sprintf('Add #%d %s (%s) for a total of %s', $currencyId, $amount, $field, $return[$currencyId])); } @@ -175,13 +178,14 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U return $this->user ->availableBudgets() ->where('transaction_currency_id', $currency->id) - ->get(); + ->get() + ; } /** * Returns all available budget objects. */ - public function getAvailableBudgetsByDate(null|Carbon $start, null|Carbon $end): Collection + public function getAvailableBudgetsByDate(?Carbon $start, ?Carbon $end): Collection { $query = $this->user->availableBudgets(); @@ -204,10 +208,11 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->availableBudgets() ->where('start_date', '=', $start->format('Y-m-d')) ->where('end_date', '=', $end->format('Y-m-d')) - ->get(); + ->get() + ; } - public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): null|AvailableBudget + public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget { /** @var null|AvailableBudget */ return $this->user @@ -215,27 +220,29 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first(); + ->first() + ; } #[Deprecated] public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget { /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $this->user + $availableBudget = $this->user ->availableBudgets() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first(); + ->first() + ; if (null === $availableBudget) { - $availableBudget = new AvailableBudget(); + $availableBudget = new AvailableBudget(); $availableBudget->user()->associate($this->user); $availableBudget->transactionCurrency()->associate($currency); - $availableBudget->start_date = $start->startOfDay(); + $availableBudget->start_date = $start->startOfDay(); $availableBudget->start_date_tz = $start->format('e'); - $availableBudget->end_date = $end->endOfDay(); - $availableBudget->end_date_tz = $end->format('e'); + $availableBudget->end_date = $end->endOfDay(); + $availableBudget->end_date_tz = $end->format('e'); } $availableBudget->amount = $amount; $availableBudget->save(); @@ -243,13 +250,13 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U return $availableBudget; } - public function store(array $data): null|AvailableBudget + public function store(array $data): ?AvailableBudget { $start = $data['start']; if ($start instanceof Carbon) { $start = $data['start']->startOfDay(); } - $end = $data['end']; + $end = $data['end']; if ($end instanceof Carbon) { $end = $data['end']->endOfDay(); } @@ -262,7 +269,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U 'start_date' => $start, 'start_date_tz' => $start->format('e'), 'end_date' => $end, - 'end_date_tz' => $end->format('e') + 'end_date_tz' => $end->format('e'), ]); } @@ -281,8 +288,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U if (array_key_exists('start', $data)) { $start = $data['start']; if ($start instanceof Carbon) { - $start = $data['start']->startOfDay(); - $availableBudget->start_date = $start; + $start = $data['start']->startOfDay(); + $availableBudget->start_date = $start; $availableBudget->start_date_tz = $start->format('e'); $availableBudget->save(); } @@ -291,8 +298,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U if (array_key_exists('end', $data)) { $end = $data['end']; if ($end instanceof Carbon) { - $end = $data['end']->endOfDay(); - $availableBudget->end_date = $end; + $end = $data['end']->endOfDay(); + $availableBudget->end_date = $end; $availableBudget->end_date_tz = $end->format('e'); $availableBudget->save(); } diff --git a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php index a356b88509..46251e79d2 100644 --- a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php +++ b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php @@ -58,14 +58,14 @@ interface AvailableBudgetRepositoryInterface /** * Find existing AB. */ - public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): null|AvailableBudget; + public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): ?AvailableBudget; - public function findById(int $id): null|AvailableBudget; + public function findById(int $id): ?AvailableBudget; /** * Return a list of all available budgets (in all currencies) (for the selected period). */ - public function get(null|Carbon $start = null, null|Carbon $end = null): Collection; + public function get(?Carbon $start = null, ?Carbon $end = null): Collection; #[Deprecated] public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string; @@ -80,19 +80,19 @@ interface AvailableBudgetRepositoryInterface /** * Returns all available budget objects. */ - public function getAvailableBudgetsByDate(null|Carbon $start, null|Carbon $end): Collection; + public function getAvailableBudgetsByDate(?Carbon $start, ?Carbon $end): Collection; public function getAvailableBudgetsByExactDate(Carbon $start, Carbon $end): Collection; /** * Get by transaction currency and date. Should always result in one entry or NULL. */ - public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): null|AvailableBudget; + public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget; #[Deprecated] public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget; - public function store(array $data): null|AvailableBudget; + public function store(array $data): ?AvailableBudget; public function update(AvailableBudget $availableBudget, array $data): AvailableBudget; diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index edb4825514..3d776cdaee 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -51,9 +51,9 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup * Tells you which amount has been budgeted (for the given budgets) * in the selected query. Returns a positive amount as a string. */ - public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, null|Collection $budgets = null): string + public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string { - $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') + $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') // same complex where query as below. ->where(static function (Builder $q5) use ($start, $end): void { $q5->where(static function (Builder $q1) use ($start, $end): void { @@ -73,7 +73,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->where('budget_limits.transaction_currency_id', $currency->id) ->whereNull('budgets.deleted_at') ->where('budgets.active', true) - ->where('budgets.user_id', $this->user->id); + ->where('budgets.user_id', $this->user->id) + ; if ($budgets instanceof Collection && $budgets->count() > 0) { $query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray()); } @@ -111,14 +112,14 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup $budgetLimit->delete(); } - public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, null|Carbon $start = null, null|Carbon $end = null): Collection + public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection { return $this->getAllBudgetLimits($start, $end)->filter( - static fn(BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id + static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id ); } - public function getAllBudgetLimits(null|Carbon $start = null, null|Carbon $end = null): Collection + public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection { // both are NULL: if (!$start instanceof Carbon && !$end instanceof Carbon) { @@ -126,14 +127,16 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->with(['budget']) ->where('budgets.user_id', $this->user->id) ->whereNull('budgets.deleted_at') - ->get(['budget_limits.*']); + ->get(['budget_limits.*']) + ; } // one of the two is NULL. if (!$start instanceof Carbon xor !$end instanceof Carbon) { $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->with(['budget']) ->whereNull('budgets.deleted_at') - ->where('budgets.user_id', $this->user->id); + ->where('budgets.user_id', $this->user->id) + ; if ($end instanceof Carbon) { // end date must be before $end. $query->where('end_date', '<=', $end->format('Y-m-d 00:00:00')); @@ -166,10 +169,11 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); }); }) - ->get(['budget_limits.*']); + ->get(['budget_limits.*']) + ; } - public function getBudgetLimits(Budget $budget, null|Carbon $start = null, null|Carbon $end = null): Collection + public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection { if (!$end instanceof Carbon && !$start instanceof Carbon) { return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']); @@ -204,7 +208,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->orWhere(static function (Builder $q3) use ($start, $end): void { $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00')); $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59')); - }); + }) + ; })->orWhere(static function (Builder $q4) use ($start, $end): void { // or start is before start AND end is after end. $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59')); @@ -212,7 +217,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup }); }) ->orderBy('budget_limits.start_date', 'DESC') - ->get(['budget_limits.*']); + ->get(['budget_limits.*']) + ; } #[Override] @@ -228,47 +234,48 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup { // if no currency has been provided, use the user's default currency: /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $currency->enabled = true; + $currency->enabled = true; $currency->save(); // find the budget: /** @var null|Budget $budget */ - $budget = $this->user->budgets()->find((int) $data['budget_id']); + $budget = $this->user->budgets()->find((int) $data['budget_id']); if (null === $budget) { throw new FireflyException('200004: Budget does not exist.'); } // find limit with same date range and currency. - $limit = $budget + $limit = $budget ->budgetlimits() ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d')) ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d')) ->where('budget_limits.transaction_currency_id', $currency->id) - ->first(['budget_limits.*']); + ->first(['budget_limits.*']) + ; if (null !== $limit) { throw new FireflyException('200027: Budget limit already exists.'); } Log::debug('No existing budget limit, create a new one'); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_bl_store', $data['fire_webhooks'] ?? true); // or create one and return it. - $limit = new BudgetLimit(); + $limit = new BudgetLimit(); $limit->budget()->associate($budget); - $limit->start_date = $data['start_date']->format('Y-m-d'); - $limit->end_date = $data['end_date']->format('Y-m-d'); - $limit->amount = $data['amount']; + $limit->start_date = $data['start_date']->format('Y-m-d'); + $limit->end_date = $data['end_date']->format('Y-m-d'); + $limit->amount = $data['amount']; $limit->transaction_currency_id = $currency->id; $limit->save(); - $noteText = (string) ($data['notes'] ?? ''); + $noteText = (string) ($data['notes'] ?? ''); if ('' !== $noteText) { $this->setNoteText($limit, $noteText); } @@ -278,7 +285,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup return $limit; } - public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): null|BudgetLimit + public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit { /** @var null|BudgetLimit */ return $budget @@ -286,7 +293,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first(); + ->first() + ; } #[Override] @@ -311,20 +319,20 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup */ public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit { - $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount; - $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id; + $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount; + $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id; if (array_key_exists('start', $data)) { - $budgetLimit->start_date = $data['start']->startOfDay(); + $budgetLimit->start_date = $data['start']->startOfDay(); $budgetLimit->start_date_tz = $data['start']->format('e'); } if (array_key_exists('end', $data)) { - $budgetLimit->end_date = $data['end']->endOfDay(); + $budgetLimit->end_date = $data['end']->endOfDay(); $budgetLimit->end_date_tz = $data['end']->format('e'); } // if no currency has been provided, use the user's default currency: - $currency = null; + $currency = null; // update if relevant: if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { @@ -336,11 +344,11 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup if (null === $currency) { $currency = $budgetLimit->transactionCurrency ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $currency->enabled = true; + $currency->enabled = true; $currency->save(); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_bl_update', $data['fire_webhooks'] ?? true); $budgetLimit->transaction_currency_id = $currency->id; diff --git a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php index 8592254128..defb1c7d49 100644 --- a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php @@ -50,7 +50,7 @@ interface BudgetLimitRepositoryInterface * Tells you which amount has been budgeted (for the given budgets) * in the selected query. Returns a positive amount as a string. */ - public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, null|Collection $budgets = null): string; + public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string; /** * Destroy all budget limits. @@ -62,16 +62,16 @@ interface BudgetLimitRepositoryInterface */ public function destroyBudgetLimit(BudgetLimit $budgetLimit): void; - public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): null|BudgetLimit; + public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit; /** * TODO this method is not multi currency aware. */ - public function getAllBudgetLimits(null|Carbon $start = null, null|Carbon $end = null): Collection; + public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection; - public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, null|Carbon $start = null, null|Carbon $end = null): Collection; + public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection; - public function getBudgetLimits(Budget $budget, null|Carbon $start = null, null|Carbon $end = null): Collection; + public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection; public function getNoteText(BudgetLimit $budgetLimit): string; diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 984aca4251..2870d51aa0 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -85,7 +85,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function budgetedInPeriod(Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in budgetedInPeriod("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); - $return = []; + $return = []; /** @var BudgetLimitRepository $limitRepository */ $limitRepository = app(BudgetLimitRepository::class); @@ -102,9 +102,9 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface /** @var BudgetLimit $limit */ foreach ($limits as $limit) { Log::debug(sprintf('Budget limit #%d', $limit->id)); - $currency = $limit->transactionCurrency; - $rate = $converter->getCurrencyRate($currency, $primaryCurrency, $end); - $currencyCode = $currency->code; + $currency = $limit->transactionCurrency; + $rate = $converter->getCurrencyRate($currency, $primaryCurrency, $end); + $currencyCode = $currency->code; $return[$currencyCode] ??= [ 'currency_id' => (string) $currency->id, 'currency_name' => $currency->name, @@ -117,11 +117,11 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'primary_currency_code' => $primaryCurrency->code, 'primary_currency_decimal_places' => $primaryCurrency->decimal_places, 'sum' => '0', - 'pc_sum' => '0' + 'pc_sum' => '0', ]; // same period if ($limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); Log::debug(sprintf('Add full amount [1]: %s', $limit->amount)); @@ -129,16 +129,16 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } // limit is inside of date range if ($start->lte($limit->start_date) && $end->gte($limit->end_date)) { - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); Log::debug(sprintf('Add full amount [2]: %s', $limit->amount)); continue; } - $total = $limit->start_date->diffInDays($limit->end_date, true) + 1; // include the day itself. - $days = $this->daysInOverlap($limit, $start, $end); - $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], $amount); + $total = $limit->start_date->diffInDays($limit->end_date, true) + 1; // include the day itself. + $days = $this->daysInOverlap($limit, $start, $end); + $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], $amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); Log::debug(sprintf( 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', @@ -161,7 +161,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->where('active', true) ->orderBy('order', 'ASC') ->orderBy('name', 'ASC') - ->get(); + ->get() + ; } /** @@ -201,26 +202,26 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function budgetedInPeriodForBudget(Budget $budget, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in budgetedInPeriod(#%d, "%s", "%s")', $budget->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - $return = []; + $return = []; /** @var BudgetLimitRepository $limitRepository */ $limitRepository = app(BudgetLimitRepository::class); $limitRepository->setUser($this->user); Log::debug(sprintf('Budget #%d: "%s"', $budget->id, $budget->name)); - $limits = $limitRepository->getBudgetLimits($budget, $start, $end); + $limits = $limitRepository->getBudgetLimits($budget, $start, $end); /** @var BudgetLimit $limit */ foreach ($limits as $limit) { Log::debug(sprintf('Budget limit #%d', $limit->id)); - $currency = $limit->transactionCurrency; + $currency = $limit->transactionCurrency; $return[$currency->id] ??= [ 'id' => (string) $currency->id, 'name' => $currency->name, 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0' + 'sum' => '0', ]; // same period if ($limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { @@ -236,9 +237,9 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface continue; } - $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. - $days = $this->daysInOverlap($limit, $start, $end); - $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); + $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. + $days = $this->daysInOverlap($limit, $start, $end); + $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount); Log::debug(sprintf( 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', @@ -271,7 +272,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $this->user ->budgets() ->where('active', 0) - ->update(['order' => 0]); + ->update(['order' => 0]) + ; return true; } @@ -284,10 +286,10 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface Log::debug('Now in update()'); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_budget_update', $data['fire_webhooks'] ?? true); - $oldName = $budget->name; + $oldName = $budget->name; if (array_key_exists('name', $data)) { $budget->name = $data['name']; $this->updateRuleActions($oldName, $budget->name); @@ -302,7 +304,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $budget->save(); // update or create auto-budget: - $autoBudget = $this->getAutoBudget($budget); + $autoBudget = $this->getAutoBudget($budget); // first things first: delete when no longer required: $autoBudgetType = $data['auto_budget_type'] ?? null; @@ -331,7 +333,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->where('rules.user_id', $this->user->id) ->whereIn('rule_actions.action_type', $types) ->where('rule_actions.action_value', $oldName) - ->get(['rule_actions.*']); + ->get(['rule_actions.*']) + ; Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ @@ -349,7 +352,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->where('rules.user_id', $this->user->id) ->whereIn('rule_triggers.trigger_type', $types) ->where('rule_triggers.trigger_value', $oldName) - ->get(['rule_triggers.*']); + ->get(['rule_triggers.*']) + ; Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ @@ -376,7 +380,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $dbNote?->delete(); } - public function getAutoBudget(Budget $budget): null|AutoBudget + public function getAutoBudget(Budget $budget): ?AutoBudget { /** @var null|AutoBudget */ return $budget->autoBudgets()->first(); @@ -388,13 +392,13 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $autoBudget = $this->getAutoBudget($budget); // grab default currency: - $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if (!$autoBudget instanceof AutoBudget) { // at this point it's a blind assumption auto_budget_type is 1 or 2. - $autoBudget = new AutoBudget(); - $autoBudget->auto_budget_type = $data['auto_budget_type']; - $autoBudget->budget_id = $budget->id; + $autoBudget = new AutoBudget(); + $autoBudget->auto_budget_type = $data['auto_budget_type']; + $autoBudget->budget_id = $budget->id; $autoBudget->transaction_currency_id = $currency->id; } @@ -432,7 +436,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface * * @param null|int $budgetId |null */ - public function find(null|int $budgetId = null): null|Budget + public function find(?int $budgetId = null): ?Budget { /** @var null|Budget */ return $this->user->budgets()->find($budgetId); @@ -471,7 +475,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->budgets() ->orderBy('order', 'ASC') ->orderBy('name', 'ASC') - ->get(); + ->get() + ; } public function destroyAutoBudget(Budget $budget): void @@ -482,7 +487,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } } - public function findBudget(null|int $budgetId, null|string $budgetName): null|Budget + public function findBudget(?int $budgetId, ?string $budgetName): ?Budget { Log::debug('Now in findBudget()'); Log::debug(sprintf('Searching for budget with ID #%d...', $budgetId)); @@ -502,7 +507,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface /** * Find budget by name. */ - public function findByName(null|string $name): null|Budget + public function findByName(?string $name): ?Budget { if (null === $name) { return null; @@ -513,14 +518,15 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface return $this->user ->budgets() ->whereLike('name', $query) - ->first(); + ->first() + ; } /** * This method returns the oldest journal or transaction date known to this budget. * Will cache result. */ - public function firstUseDate(Budget $budget): null|Carbon + public function firstUseDate(Budget $budget): ?Carbon { $journal = $budget->transactionJournals()->orderBy('date', 'ASC')->first(); @@ -529,14 +535,14 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function getAttachments(Budget $budget): Collection { - $set = $budget->attachments()->get(); + $set = $budget->attachments()->get(); $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + $attachment->notes_text = null !== $notes ? $notes->text : ''; return $attachment; }); @@ -550,7 +556,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface return $this->user ->budgets() ->whereIn('id', $budgetIds) - ->get(); + ->get() + ; } public function getInactiveBudgets(): Collection @@ -560,10 +567,11 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->orderBy('order', 'ASC') ->orderBy('name', 'ASC') ->where('active', 0) - ->get(); + ->get() + ; } - public function getNoteText(Budget $budget): null|string + public function getNoteText(Budget $budget): ?string { $note = $budget->notes()->first(); @@ -596,8 +604,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // exclude specific liabilities $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -608,31 +616,32 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // start collecting: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($this->user) ->setRange($start, $end) ->excludeDestinationAccounts($selection) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->setBudgets($this->getActiveBudgets()); + ->setBudgets($this->getActiveBudgets()) + ; - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'id' => (string) $currencyId, 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], 'code' => $journal['currency_code'], 'decimal_places' => $journal['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::negative($journal['amount'])); // also do foreign amount: - $foreignId = (int) $journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] ??= [ 'id' => (string) $foreignId, @@ -640,7 +649,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'symbol' => $journal['foreign_currency_symbol'], 'code' => $journal['foreign_currency_code'], 'decimal_places' => $journal['foreign_currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $array[$foreignId]['sum'] = bcadd($array[$foreignId]['sum'], Steam::negative($journal['foreign_amount'])); } @@ -658,8 +667,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // exclude specific liabilities $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -670,31 +679,32 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // start collecting: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($this->user) ->setRange($start, $end) ->excludeDestinationAccounts($selection) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->setBudget($budget); + ->setBudget($budget) + ; - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'id' => (string) $currencyId, 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], 'code' => $journal['currency_code'], 'decimal_places' => $journal['currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::negative($journal['amount'])); // also do foreign amount: - $foreignId = (int) $journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] ??= [ 'id' => (string) $foreignId, @@ -702,7 +712,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'symbol' => $journal['foreign_currency_symbol'], 'code' => $journal['foreign_currency_code'], 'decimal_places' => $journal['foreign_currency_decimal_places'], - 'sum' => '0' + 'sum' => '0', ]; $array[$foreignId]['sum'] = bcadd($array[$foreignId]['sum'], Steam::negative($journal['foreign_amount'])); } @@ -718,10 +728,10 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface */ public function store(array $data): Budget { - $order = $this->getMaxOrder(); + $order = $this->getMaxOrder(); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_budget_create', $data['fire_webhooks'] ?? true); try { @@ -730,7 +740,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'user_group_id' => $this->user->user_group_id, 'name' => $data['name'], 'order' => $order + 1, - 'active' => array_key_exists('active', $data) ? $data['active'] : true + 'active' => array_key_exists('active', $data) ? $data['active'] : true, ]); } catch (QueryException $e) { Log::error($e->getMessage()); @@ -747,7 +757,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface if (!array_key_exists('auto_budget_type', $data) || !array_key_exists('auto_budget_amount', $data) || !array_key_exists('auto_budget_period', $data)) { return $newBudget; } - $type = $data['auto_budget_type']; + $type = $data['auto_budget_type']; if ('none' === $type) { return $newBudget; } @@ -766,8 +776,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } /** @var CurrencyRepositoryInterface $repos */ - $repos = app(CurrencyRepositoryInterface::class); - $currency = null; + $repos = app(CurrencyRepositoryInterface::class); + $currency = null; if (array_key_exists('currency_id', $data)) { $currency = $repos->find((int) $data['currency_id']); } @@ -778,27 +788,27 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $autoBudget = new AutoBudget(); + $autoBudget = new AutoBudget(); $autoBudget->budget()->associate($newBudget); $autoBudget->transaction_currency_id = $currency->id; - $autoBudget->auto_budget_type = $type; - $autoBudget->amount = $data['auto_budget_amount'] ?? '1'; - $autoBudget->period = $data['auto_budget_period'] ?? 'monthly'; + $autoBudget->auto_budget_type = $type; + $autoBudget->amount = $data['auto_budget_amount'] ?? '1'; + $autoBudget->period = $data['auto_budget_period'] ?? 'monthly'; $autoBudget->save(); // create initial budget limit. - $today = today(config('app.timezone')); - $start = Navigation::startOfPeriod($today, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $today = today(config('app.timezone')); + $start = Navigation::startOfPeriod($today, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); - $limitRepos = app(BudgetLimitRepositoryInterface::class); + $limitRepos = app(BudgetLimitRepositoryInterface::class); $limitRepos->setUser($this->user); $limitRepos->store([ 'budget_id' => $newBudget->id, 'currency_id' => $autoBudget->transaction_currency_id, 'start_date' => $start, 'end_date' => $end, - 'amount' => $autoBudget->amount + 'amount' => $autoBudget->amount, ]); return $newBudget; diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index 767691eebd..b12aed2796 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -70,26 +70,26 @@ interface BudgetRepositoryInterface public function destroyAutoBudget(Budget $budget): void; - public function find(null|int $budgetId = null): null|Budget; + public function find(?int $budgetId = null): ?Budget; - public function findBudget(null|int $budgetId, null|string $budgetName): null|Budget; + public function findBudget(?int $budgetId, ?string $budgetName): ?Budget; /** * Find budget by name. */ - public function findByName(null|string $name): null|Budget; + public function findByName(?string $name): ?Budget; /** * This method returns the oldest journal or transaction date known to this budget. * Will cache result. */ - public function firstUseDate(Budget $budget): null|Carbon; + public function firstUseDate(Budget $budget): ?Carbon; public function getActiveBudgets(): Collection; public function getAttachments(Budget $budget): Collection; - public function getAutoBudget(Budget $budget): null|AutoBudget; + public function getAutoBudget(Budget $budget): ?AutoBudget; public function getBudgets(): Collection; @@ -102,7 +102,7 @@ interface BudgetRepositoryInterface public function getMaxOrder(): int; - public function getNoteText(Budget $budget): null|string; + public function getNoteText(Budget $budget): ?string; public function searchBudget(string $query, int $limit): Collection; diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php index ef5e8e6e60..3a48f7e469 100644 --- a/app/Repositories/Budget/NoBudgetRepository.php +++ b/app/Repositories/Budget/NoBudgetRepository.php @@ -49,17 +49,17 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf $carbonFormat = Navigation::preferredCarbonFormat($start, $end); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); $collector->withoutBudget(); - $journals = $collector->getExtractedJournals(); - $data = []; + $journals = $collector->getExtractedJournals(); + $data = []; /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $data[$currencyId] ??= [ 'id' => 0, @@ -70,9 +70,9 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'entries' => [] + 'entries' => [], ]; - $date = $journal['date']->format($carbonFormat); + $date = $journal['date']->format($carbonFormat); if (!array_key_exists($date, $data[$currencyId]['entries'])) { $data[$currencyId]['entries'][$date] = '0'; @@ -83,10 +83,10 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf return $data; } - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -104,7 +104,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf } #[Override] - public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array + public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); diff --git a/app/Repositories/Budget/NoBudgetRepositoryInterface.php b/app/Repositories/Budget/NoBudgetRepositoryInterface.php index af2a734b00..13d12a1122 100644 --- a/app/Repositories/Budget/NoBudgetRepositoryInterface.php +++ b/app/Repositories/Budget/NoBudgetRepositoryInterface.php @@ -48,7 +48,7 @@ interface NoBudgetRepositoryInterface #[Deprecated] public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array; - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; - public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; + public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; } diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index c178926027..d7ca57ed36 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -68,7 +68,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ++$count; Log::debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); } - $avg = $total; + $avg = $total; if ($count > 0) { $avg = bcdiv($total, (string) $count); } @@ -89,19 +89,19 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn // get all transactions: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end); $collector->setBudgets($budgets); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // loop transactions: /** @var array $journal */ foreach ($journals as $journal) { // prep data array for currency: - $budgetId = (int) $journal['budget_id']; - $budgetName = $journal['budget_name']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%d-%d', $budgetId, $currencyId); + $budgetId = (int) $journal['budget_id']; + $budgetName = $journal['budget_name']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%d-%d', $budgetId, $currencyId); $data[$key] ??= [ 'id' => $budgetId, @@ -112,9 +112,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'entries' => [] + 'entries' => [], ]; - $date = $journal['date']->format($carbonFormat); + $date = $journal['date']->format($carbonFormat); $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date] ?? '0', (string) $journal['amount']); } @@ -126,10 +126,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified budget set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $budgets = null): array + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -141,8 +141,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setBudgets($this->getBudgets()); } $collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; // if needs conversion to primary. $convertToPrimary = Amount::convertToPrimary($this->user); @@ -156,8 +156,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $currencies = [$currencyId => $primaryCurrency]; foreach ($journals as $journal) { - $amount = Steam::negative($journal['amount']); - $journalCurrencyId = (int) $journal['currency_id']; + $amount = Steam::negative($journal['amount']); + $journalCurrencyId = (int) $journal['currency_id']; if (false === $convertToPrimary) { $currencyId = $journalCurrencyId; $currencyName = $journal['currency_name']; @@ -170,8 +170,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $amount = $converter->convert($currencies[$journalCurrencyId], $primaryCurrency, $journal['date'], $amount); } - $budgetId = (int) $journal['budget_id']; - $budgetName = (string) $journal['budget_name']; + $budgetId = (int) $journal['budget_id']; + $budgetName = (string) $journal['budget_name']; // catch "no budget" entries. if (0 === $budgetId) { @@ -179,25 +179,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'budgets' => [], 'currency_id' => $currencyId, 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces + 'currency_decimal_places' => $currencyDecimalPlaces, ]; // info about the categories: $array[$currencyId]['budgets'][$budgetId] ??= [ 'id' => $budgetId, 'name' => $budgetName, - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['budgets'][$budgetId]['transaction_journals'][$journalId] = [ 'amount' => $amount, 'destination_account_id' => $journal['destination_account_id'], @@ -210,7 +210,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'category_name' => $journal['category_name'], 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'date' => $journal['date'] + 'date' => $journal['date'], ]; } @@ -231,9 +231,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function sumExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $budgets = null, - null|TransactionCurrency $currency = null, + ?Collection $accounts = null, + ?Collection $budgets = null, + ?TransactionCurrency $currency = null, bool $convertToPrimary = false ): array { Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToPrimary, true))); @@ -243,8 +243,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -254,12 +254,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($this->user) ->setRange($start, $end) // ->excludeDestinationAccounts($selection) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) + ; if ($accounts instanceof Collection) { $collector->setAccounts($accounts); @@ -274,7 +275,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if ($budgets->count() > 0) { $collector->setBudgets($budgets); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // same but for transactions in the foreign currency: if ($currency instanceof TransactionCurrency) { @@ -299,9 +300,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter( + $expenses = array_filter( $expenses, - static fn(array $expense): bool => $expense['date']->between($start, $end) && $expense['currency_id'] === $transactionCurrency->id + static fn (array $expense): bool => $expense['date']->between($start, $end) && $expense['currency_id'] === $transactionCurrency->id ); return $summarizer->groupByCurrencyId($expenses, 'negative', false); @@ -314,7 +315,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter($expenses, static fn(array $expense): bool => $expense['budget_id'] === $budget->id); + $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['budget_id'] === $budget->id); return $summarizer->groupByCurrencyId($expenses, 'negative', false); } @@ -323,9 +324,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn public function collectExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $budgets = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $budgets = null, + ?TransactionCurrency $currency = null ): array { Log::debug(sprintf('Start of %s(%s, %s, array, array, "%s").', __METHOD__, $start->toW3cString(), $end->toW3cString(), $currency?->code)); // this collector excludes all transfers TO liabilities (which are also withdrawals) @@ -334,8 +335,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -345,12 +346,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($this->user) ->setRange($start, $end) // ->excludeDestinationAccounts($selection) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) + ; if ($accounts instanceof Collection) { $collector->setAccounts($accounts); diff --git a/app/Repositories/Budget/OperationsRepositoryInterface.php b/app/Repositories/Budget/OperationsRepositoryInterface.php index d3bf640541..d2f41f8f00 100644 --- a/app/Repositories/Budget/OperationsRepositoryInterface.php +++ b/app/Repositories/Budget/OperationsRepositoryInterface.php @@ -60,7 +60,7 @@ interface OperationsRepositoryInterface * which have the specified budget set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $budgets = null): array; + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null): array; /** * @SuppressWarnings("PHPMD.ExcessiveParameterList") @@ -68,9 +68,9 @@ interface OperationsRepositoryInterface public function sumExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $budgets = null, - null|TransactionCurrency $currency = null, + ?Collection $accounts = null, + ?Collection $budgets = null, + ?TransactionCurrency $currency = null, bool $convertToPrimary = false ): array; @@ -87,8 +87,8 @@ interface OperationsRepositoryInterface public function collectExpenses( Carbon $start, Carbon $end, - null|Collection $accounts = null, - null|Collection $budgets = null, - null|TransactionCurrency $currency = null + ?Collection $accounts = null, + ?Collection $budgets = null, + ?TransactionCurrency $currency = null ): array; } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index b5cf291396..8fd410c4e9 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -104,13 +104,14 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf ->categories() ->with(['attachments']) ->orderBy('name', 'ASC') - ->get(); + ->get() + ; } /** * @throws FireflyException */ - public function findCategory(null|int $categoryId, null|string $categoryName): null|Category + public function findCategory(?int $categoryId, ?string $categoryName): ?Category { Log::debug('Now in findCategory()'); Log::debug(sprintf('Searching for category with ID #%d...', $categoryId)); @@ -134,7 +135,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * Find a category or return NULL */ - public function find(int $categoryId): null|Category + public function find(int $categoryId): ?Category { /** @var null|Category */ return $this->user->categories()->find($categoryId); @@ -143,13 +144,14 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * Find a category. */ - public function findByName(string $name): null|Category + public function findByName(string $name): ?Category { /** @var null|Category */ return $this->user ->categories() ->where('name', $name) - ->first(['categories.*']); + ->first(['categories.*']) + ; } /** @@ -158,7 +160,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function store(array $data): Category { /** @var CategoryFactory $factory */ - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser($this->user); $category = $factory->findOrCreate(null, $data['name']); @@ -184,7 +186,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function updateNotes(Category $category, string $notes): void { - $dbNote = $category->notes()->first(); + $dbNote = $category->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($category); @@ -193,7 +195,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $dbNote->save(); } - public function firstUseDate(Category $category): null|Carbon + public function firstUseDate(Category $category): ?Carbon { $firstJournalDate = $this->getFirstJournalDate($category); $firstTransactionDate = $this->getFirstTransactionDate($category); @@ -215,7 +217,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $firstJournalDate; } - private function getFirstJournalDate(Category $category): null|Carbon + private function getFirstJournalDate(Category $category): ?Carbon { $query = $category->transactionJournals()->orderBy('date', 'ASC'); $result = $query->first(['transaction_journals.*']); @@ -223,13 +225,14 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $result?->date; } - private function getFirstTransactionDate(Category $category): null|Carbon + private function getFirstTransactionDate(Category $category): ?Carbon { // check transactions: - $query = $category + $query = $category ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->orderBy('transaction_journals.date', 'ASC'); + ->orderBy('transaction_journals.date', 'ASC') + ; $lastTransaction = $query->first(['transaction_journals.*']); if (null !== $lastTransaction) { @@ -241,14 +244,14 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function getAttachments(Category $category): Collection { - $set = $category->attachments()->get(); + $set = $category->attachments()->get(); $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + $attachment->notes_text = null !== $notes ? $notes->text : ''; return $attachment; }); @@ -262,10 +265,11 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $this->user ->categories() ->whereIn('id', $categoryIds) - ->get(); + ->get() + ; } - public function getNoteText(Category $category): null|string + public function getNoteText(Category $category): ?string { $dbNote = $category->notes()->first(); @@ -275,7 +279,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * @throws Exception */ - public function lastUseDate(Category $category, Collection $accounts): null|Carbon + public function lastUseDate(Category $category, Collection $accounts): ?Carbon { $lastJournalDate = $this->getLastJournalDate($category, $accounts); $lastTransactionDate = $this->getLastTransactionDate($category, $accounts); @@ -297,9 +301,9 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $lastJournalDate; } - private function getLastJournalDate(Category $category, Collection $accounts): null|Carbon + private function getLastJournalDate(Category $category, Collection $accounts): ?Carbon { - $query = $category->transactionJournals()->orderBy('date', 'DESC'); + $query = $category->transactionJournals()->orderBy('date', 'DESC'); if ($accounts->count() > 0) { $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id'); @@ -314,13 +318,14 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * @throws Exception */ - private function getLastTransactionDate(Category $category, Collection $accounts): null|Carbon + private function getLastTransactionDate(Category $category, Collection $accounts): ?Carbon { // check transactions: - $query = $category + $query = $category ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->orderBy('transaction_journals.date', 'DESC'); + ->orderBy('transaction_journals.date', 'DESC') + ; if ($accounts->count() > 0) { // filter journals: $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()); @@ -390,7 +395,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount' + 'transactions.foreign_amount', ]) ->toArray(); } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index c411df7b5c..cef58d2d17 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -60,16 +60,16 @@ interface CategoryRepositoryInterface /** * Find a category or return NULL */ - public function find(int $categoryId): null|Category; + public function find(int $categoryId): ?Category; /** * Find a category. */ - public function findByName(string $name): null|Category; + public function findByName(string $name): ?Category; - public function findCategory(null|int $categoryId, null|string $categoryName): null|Category; + public function findCategory(?int $categoryId, ?string $categoryName): ?Category; - public function firstUseDate(Category $category): null|Carbon; + public function firstUseDate(Category $category): ?Carbon; public function getAttachments(Category $category): Collection; @@ -83,12 +83,12 @@ interface CategoryRepositoryInterface */ public function getCategories(): Collection; - public function getNoteText(Category $category): null|string; + public function getNoteText(Category $category): ?string; /** * Return most recent transaction(journal) date or null when never used before. */ - public function lastUseDate(Category $category, Collection $accounts): null|Carbon; + public function lastUseDate(Category $category, Collection $accounts): ?Carbon; /** * Remove notes. diff --git a/app/Repositories/Category/NoCategoryRepository.php b/app/Repositories/Category/NoCategoryRepository.php index 64b7b5fee7..020862fb5a 100644 --- a/app/Repositories/Category/NoCategoryRepository.php +++ b/app/Repositories/Category/NoCategoryRepository.php @@ -45,7 +45,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -53,32 +53,32 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $array[$currencyId] ??= [ + $currencyId = (int) $journal['currency_id']; + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the non-existent category: $array[$currencyId]['categories'][0] ??= [ 'id' => 0, 'name' => (string) trans('firefly.noCategory'), - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), - 'date' => $journal['date'] + 'date' => $journal['date'], ]; } @@ -90,7 +90,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -98,32 +98,32 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $array[$currencyId] ??= [ + $currencyId = (int) $journal['currency_id']; + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the non-existent category: $array[$currencyId]['categories'][0] ??= [ 'id' => 0, 'name' => (string) trans('firefly.noCategory'), - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), - 'date' => $journal['date'] + 'date' => $journal['date'], ]; } @@ -133,10 +133,10 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory(); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -151,7 +151,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** * Sum of income journals in period without a category, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -160,18 +160,18 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } @@ -179,7 +179,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn return $array; } - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null): array + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -188,18 +188,18 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } diff --git a/app/Repositories/Category/NoCategoryRepositoryInterface.php b/app/Repositories/Category/NoCategoryRepositoryInterface.php index e2e37d94a6..58b25504f8 100644 --- a/app/Repositories/Category/NoCategoryRepositoryInterface.php +++ b/app/Repositories/Category/NoCategoryRepositoryInterface.php @@ -48,27 +48,27 @@ interface NoCategoryRepositoryInterface * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; /** * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array; /** * Sum of income journals in period without a category, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; /** * Sum of transfers in period without a category, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null): array; + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null): array; } diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php index a9af7df3a1..518615b6de 100644 --- a/app/Repositories/Category/OperationsRepository.php +++ b/app/Repositories/Category/OperationsRepository.php @@ -50,7 +50,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * First currency, then categories. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -66,13 +66,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -80,25 +80,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), 'date' => $journal['date'], @@ -108,7 +108,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'] + 'transaction_group_id' => (string) $journal['transaction_group_id'], ]; } @@ -128,7 +128,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -144,13 +144,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -158,25 +158,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -185,14 +185,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'source_account_name' => $journal['source_account_name'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'] + 'transaction_group_id' => (string) $journal['transaction_group_id'], ]; } return $array; } - public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array + public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -201,7 +201,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ->setRange($start, $end) ->setTypes([TransactionTypeEnum::TRANSFER->value]) ->setDestinationAccounts($accounts) - ->excludeSourceAccounts($accounts); + ->excludeSourceAccounts($accounts) + ; if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } @@ -209,13 +210,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -223,25 +224,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -251,14 +252,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'] + 'transaction_group_id' => (string) $journal['transaction_group_id'], ]; } return $array; } - public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array + public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -267,7 +268,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ->setRange($start, $end) ->setTypes([TransactionTypeEnum::TRANSFER->value]) ->setSourceAccounts($accounts) - ->excludeDestinationAccounts($accounts); + ->excludeDestinationAccounts($accounts) + ; if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } @@ -275,13 +277,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -289,25 +291,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [] + 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), 'date' => $journal['date'], @@ -317,7 +319,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'] + 'transaction_group_id' => (string) $journal['transaction_group_id'], ]; } @@ -327,10 +329,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -350,10 +352,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -370,12 +372,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn foreach ($journals as $journal) { // Almost the same as in \FireflyIII\Repositories\Budget\OperationsRepository::sumExpenses - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyCode = $journal['currency_code']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyCode = $journal['currency_code']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -406,7 +408,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces + 'currency_decimal_places' => $currencyDecimalPlaces, ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($amount)); } @@ -417,7 +419,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -430,18 +432,18 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $categories = $this->getCategories(); } $collector->setCategories($categories); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } @@ -449,7 +451,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $array; } - public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -467,7 +469,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $collector->getExtractedJournals(); } - public function collectIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -484,7 +486,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $collector->getExtractedJournals(); } - public function collectTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array + public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -508,7 +510,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter($expenses, static fn(array $expense): bool => $expense['category_id'] === $category->id); + $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['category_id'] === $category->id); return $summarizer->groupByCurrencyId($expenses, $method, false); } diff --git a/app/Repositories/Category/OperationsRepositoryInterface.php b/app/Repositories/Category/OperationsRepositoryInterface.php index 89db4b2ff9..e8fcdab41b 100644 --- a/app/Repositories/Category/OperationsRepositoryInterface.php +++ b/app/Repositories/Category/OperationsRepositoryInterface.php @@ -49,14 +49,14 @@ interface OperationsRepositoryInterface * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; /** * This method returns a list of all the transfer transaction journals (as arrays) set in that period @@ -64,7 +64,7 @@ interface OperationsRepositoryInterface * It excludes any transfers between the listed accounts. * It's grouped per currency, with as few details in the array as possible. Amounts are always negative. */ - public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array; + public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array; /** * This method returns a list of all the transfer transaction journals (as arrays) set in that period @@ -72,28 +72,28 @@ interface OperationsRepositoryInterface * It excludes any transfers between the listed accounts. * It's grouped per currency, with as few details in the array as possible. Amounts are always negative. */ - public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array; + public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array; /** * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; - public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; - public function collectIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; - public function collectTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array; /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; /** * Sum of transfers in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; } diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index e321ae0731..74e8958f64 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -68,10 +68,10 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * @throws JsonException */ - public function currencyInUseAt(TransactionCurrency $currency): null|string + public function currencyInUseAt(TransactionCurrency $currency): ?string { Log::debug(sprintf('Now in currencyInUse() for #%d ("%s")', $currency->id, $currency->code)); - $countJournals = $this->countJournals($currency); + $countJournals = $this->countJournals($currency); if ($countJournals > 0) { Log::info(sprintf('Count journals is %d, return true.', $countJournals)); @@ -86,7 +86,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in accounts: - $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count(); + $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -94,7 +94,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // second search using integer check. - $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int) $currency->id))->count(); + $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -102,7 +102,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in bills: - $bills = Bill::where('transaction_currency_id', $currency->id)->count(); + $bills = Bill::where('transaction_currency_id', $currency->id)->count(); if ($bills > 0) { Log::info(sprintf('Used in %d bills as currency, return true. ', $bills)); @@ -120,11 +120,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in accounts (as integer) - $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') ->where('account_meta.name', 'currency_id') ->where('account_meta.data', json_encode($currency->id)) - ->count(); + ->count() + ; if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -140,7 +141,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in budget limits - $budgetLimit = BudgetLimit::where('transaction_currency_id', $currency->id)->count(); + $budgetLimit = BudgetLimit::where('transaction_currency_id', $currency->id)->count(); if ($budgetLimit > 0) { Log::info(sprintf('Used in %d budget limits as currency, return true. ', $budgetLimit)); @@ -148,11 +149,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is the default currency for the user or the system - $count = $this->userGroup + $count = $this->userGroup ->currencies() ->where('transaction_currencies.id', $currency->id) ->wherePivot('group_default', 1) - ->count(); + ->count() + ; if ($count > 0) { Log::info('Is the default currency of the user, return true.'); @@ -160,11 +162,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is the default currency for the user or the system - $count = $this->userGroup + $count = $this->userGroup ->currencies() ->where('transaction_currencies.id', $currency->id) ->wherePivot('group_default', 1) - ->count(); + ->count() + ; if ($count > 0) { Log::info('Is the default currency of the user group, return true.'); @@ -193,12 +196,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $local = $this->get(); 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 + $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; + $current->userGroupNative = $isPrimary; return $current; }); @@ -210,10 +213,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf ->currencies() ->orderBy('code', 'ASC') ->withPivot(['group_default']) - ->get(); + ->get() + ; $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line $current->userGroupEnabled = true; - $current->userGroupNative = 1 === (int) $current->pivot->group_default; + $current->userGroupNative = 1 === (int) $current->pivot->group_default; return $current; }); @@ -241,7 +245,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $currency->save(); } - public function findByName(string $name): null|TransactionCurrency + public function findByName(string $name): ?TransactionCurrency { return TransactionCurrency::where('name', $name)->first(); } @@ -249,7 +253,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by object, ID or code. Returns user default or system default. */ - public function findCurrency(null|int $currencyId, null|string $currencyCode): TransactionCurrency + public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency { $result = $this->findCurrencyNull($currencyId, $currencyCode); @@ -272,7 +276,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by object, ID or code. Returns NULL if nothing found. */ - public function findCurrencyNull(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency + public function findCurrencyNull(?int $currencyId, ?string $currencyCode): ?TransactionCurrency { Log::debug(sprintf('Now in findCurrencyNull(%s, "%s")', var_export($currencyId, true), $currencyCode)); if (null !== $currencyId && 0 !== $currencyId) { @@ -300,7 +304,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } #[Override] - public function find(int $currencyId): null|TransactionCurrency + public function find(int $currencyId): ?TransactionCurrency { try { $result = Amount::getTransactionCurrencyById($currencyId); @@ -314,7 +318,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by currency code, return NULL if unfound. */ - public function findByCode(string $currencyCode): null|TransactionCurrency + public function findByCode(string $currencyCode): ?TransactionCurrency { try { $result = Amount::getTransactionCurrencyByCode($currencyCode); @@ -344,12 +348,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Get currency exchange rate. */ - public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): null|CurrencyExchangeRate + public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate { if ($fromCurrency->id === $toCurrency->id) { - $rate = new CurrencyExchangeRate(); + $rate = new CurrencyExchangeRate(); $rate->rate = '1'; - $rate->id = 0; + $rate->id = 0; return $rate; } @@ -360,7 +364,8 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf ->where('from_currency_id', $fromCurrency->id) ->where('to_currency_id', $toCurrency->id) ->where('date', $date->format('Y-m-d')) - ->first(); + ->first() + ; if (null !== $rate) { Log::debug(sprintf('Found cached exchange rate in database for %s to %s on %s', $fromCurrency->code, $toCurrency->code, $date->format('Y-m-d'))); @@ -397,7 +402,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf 'to_currency_id' => $toCurrency->id, 'date' => $date, 'date_tz' => $date->format('e'), - 'rate' => $rate + 'rate' => $rate, ]); } diff --git a/app/Repositories/Currency/CurrencyRepositoryInterface.php b/app/Repositories/Currency/CurrencyRepositoryInterface.php index fdcfc91705..820b57c73c 100644 --- a/app/Repositories/Currency/CurrencyRepositoryInterface.php +++ b/app/Repositories/Currency/CurrencyRepositoryInterface.php @@ -53,7 +53,7 @@ interface CurrencyRepositoryInterface /** * @throws FireflyException */ - public function currencyInUseAt(TransactionCurrency $currency): null|string; + public function currencyInUseAt(TransactionCurrency $currency): ?string; public function destroy(TransactionCurrency $currency): bool; @@ -61,20 +61,20 @@ interface CurrencyRepositoryInterface public function enable(TransactionCurrency $currency): void; - public function find(int $currencyId): null|TransactionCurrency; + public function find(int $currencyId): ?TransactionCurrency; /** * Find by currency code, return NULL if unfound. * * Used in the download exchange rates cron job. Does not require user object. */ - public function findByCode(string $currencyCode): null|TransactionCurrency; + public function findByCode(string $currencyCode): ?TransactionCurrency; - public function findByName(string $name): null|TransactionCurrency; + public function findByName(string $name): ?TransactionCurrency; - public function findCurrency(null|int $currencyId, null|string $currencyCode): TransactionCurrency; + public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency; - public function findCurrencyNull(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency; + public function findCurrencyNull(?int $currencyId, ?string $currencyCode): ?TransactionCurrency; /** * Get the user group's currencies. @@ -98,7 +98,7 @@ interface CurrencyRepositoryInterface * * Used in the download exchange rate cron job. Needs the user object! */ - public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): null|CurrencyExchangeRate; + public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate; public function isFallbackCurrency(TransactionCurrency $currency): bool; diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/ExchangeRate/ExchangeRateRepository.php index 5ae8c4b0a4..fcc6f0b432 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepository.php @@ -43,7 +43,8 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro $this->userGroup ->currencyExchangeRates() ->where('id', $rate->id) - ->delete(); + ->delete() + ; } #[Override] @@ -52,7 +53,8 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro return $this->userGroup ->currencyExchangeRates() ->orderBy('date', 'ASC') - ->get(); + ->get() + ; } #[Override] @@ -69,11 +71,12 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro }); }) ->orderBy('date', 'DESC') - ->get(['currency_exchange_rates.*']); + ->get(['currency_exchange_rates.*']) + ; } #[Override] - public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): null|CurrencyExchangeRate + public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate { /** @var null|CurrencyExchangeRate */ return $this->userGroup @@ -81,27 +84,28 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro ->where('from_currency_id', $from->id) ->where('to_currency_id', $to->id) ->where('date', $date->format('Y-m-d')) - ->first(); + ->first() + ; } #[Override] public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate { - $object = new CurrencyExchangeRate(); - $object->user_id = auth()->user()->id; - $object->user_group_id = $this->userGroup->id; + $object = new CurrencyExchangeRate(); + $object->user_id = auth()->user()->id; + $object->user_group_id = $this->userGroup->id; $object->from_currency_id = $from->id; - $object->to_currency_id = $to->id; - $object->rate = $rate; - $object->date = $date; - $object->date_tz = $date->format('e'); + $object->to_currency_id = $to->id; + $object->rate = $rate; + $object->date = $date; + $object->date_tz = $date->format('e'); $object->save(); return $object; } #[Override] - public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, null|Carbon $date = null): CurrencyExchangeRate + public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate { $object->rate = $rate; if ($date instanceof Carbon) { diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php b/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php index 7b76aaf862..04f8ac1072 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php @@ -53,9 +53,9 @@ interface ExchangeRateRepositoryInterface public function getRates(TransactionCurrency $from, TransactionCurrency $to): Collection; - public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): null|CurrencyExchangeRate; + public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate; public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate; - public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, null|Carbon $date = null): CurrencyExchangeRate; + public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate; } diff --git a/app/Repositories/Journal/JournalAPIRepository.php b/app/Repositories/Journal/JournalAPIRepository.php index 97336d237c..b3ea94e462 100644 --- a/app/Repositories/Journal/JournalAPIRepository.php +++ b/app/Repositories/Journal/JournalAPIRepository.php @@ -44,12 +44,13 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn /** * Returns transaction by ID. Used to validate attachments. */ - public function findTransaction(int $transactionId): null|Transaction + public function findTransaction(int $transactionId): ?Transaction { return Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_id', $this->user->id) ->where('transactions.id', $transactionId) - ->first(['transactions.*']); + ->first(['transactions.*']) + ; } /** @@ -59,14 +60,14 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn */ public function getAttachments(TransactionJournal $journal): Collection { - $set = $journal->attachments; + $set = $journal->attachments; $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { - $notes = $attachment->notes()->first(); + $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. + $attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this. return $attachment; }); diff --git a/app/Repositories/Journal/JournalAPIRepositoryInterface.php b/app/Repositories/Journal/JournalAPIRepositoryInterface.php index 7bc226caba..454250c8e4 100644 --- a/app/Repositories/Journal/JournalAPIRepositoryInterface.php +++ b/app/Repositories/Journal/JournalAPIRepositoryInterface.php @@ -47,7 +47,7 @@ interface JournalAPIRepositoryInterface /** * Returns transaction by ID. Used to validate attachments. */ - public function findTransaction(int $transactionId): null|Transaction; + public function findTransaction(int $transactionId): ?Transaction; /** * Return all attachments for journal. diff --git a/app/Repositories/Journal/JournalCLIRepository.php b/app/Repositories/Journal/JournalCLIRepository.php index 70eedf240b..9bc201c11f 100644 --- a/app/Repositories/Journal/JournalCLIRepository.php +++ b/app/Repositories/Journal/JournalCLIRepository.php @@ -49,7 +49,8 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereIn('transaction_types.type', $types) ->with(['user', 'transactionType', 'transactionCurrency', 'transactions', 'transactions.account']) - ->get(['transaction_journals.*']); + ->get(['transaction_journals.*']) + ; } /** @@ -57,7 +58,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn */ public function getJournalBudgetId(TransactionJournal $journal): int { - $budget = $journal->budgets()->first(); + $budget = $journal->budgets()->first(); if (null !== $budget) { return $budget->id; } @@ -77,7 +78,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn */ public function getJournalCategoryId(TransactionJournal $journal): int { - $category = $journal->categories()->first(); + $category = $journal->categories()->first(); if (null !== $category) { return $category->id; } @@ -103,7 +104,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDate(TransactionJournal $journal, string $field): null|Carbon + public function getMetaDate(TransactionJournal $journal, string $field): ?Carbon { $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); @@ -127,9 +128,9 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return value of a meta field (or NULL) as a string. */ - public function getMetaField(TransactionJournal $journal, string $field): null|string + public function getMetaField(TransactionJournal $journal, string $field): ?string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); $cache->addProperty($journal->id); $cache->addProperty($field); @@ -138,12 +139,12 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn return $cache->get(); } - $entry = $journal->transactionJournalMeta()->where('name', $field)->first(); + $entry = $journal->transactionJournalMeta()->where('name', $field)->first(); if (null === $entry) { return null; } - $value = $entry->data; + $value = $entry->data; if (is_array($value)) { $return = implode(',', $value); @@ -162,7 +163,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return text of a note attached to journal, or NULL */ - public function getNoteText(TransactionJournal $journal): null|string + public function getNoteText(TransactionJournal $journal): ?string { $note = $journal->notes()->first(); diff --git a/app/Repositories/Journal/JournalCLIRepositoryInterface.php b/app/Repositories/Journal/JournalCLIRepositoryInterface.php index 10e3da2922..4a43340142 100644 --- a/app/Repositories/Journal/JournalCLIRepositoryInterface.php +++ b/app/Repositories/Journal/JournalCLIRepositoryInterface.php @@ -67,17 +67,17 @@ interface JournalCLIRepositoryInterface /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDate(TransactionJournal $journal, string $field): null|Carbon; + public function getMetaDate(TransactionJournal $journal, string $field): ?Carbon; /** * Return value of a meta field (or NULL). */ - public function getMetaField(TransactionJournal $journal, string $field): null|string; + public function getMetaField(TransactionJournal $journal, string $field): ?string; /** * Return text of a note attached to journal, or NULL */ - public function getNoteText(TransactionJournal $journal): null|string; + public function getNoteText(TransactionJournal $journal): ?string; /** * Returns all journals with more than 2 transactions. Should only return empty collections diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index 4f7748d37e..7439cf6d48 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -67,18 +67,20 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac ->transactionJournals() ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereIn('transaction_types.type', $types) - ->get(['transaction_journals.*']); + ->get(['transaction_journals.*']) + ; } /** * Get users first transaction journal or NULL. */ - public function firstNull(): null|TransactionJournal + public function firstNull(): ?TransactionJournal { return $this->user ->transactionJournals() ->orderBy('date', 'ASC') - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; } public function getDestinationAccount(TransactionJournal $journal): Account @@ -97,7 +99,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac */ public function getJournalTotal(TransactionJournal $journal): string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($journal->id); $cache->addProperty('amount-positive'); if ($cache->has()) { @@ -112,12 +114,13 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac return $amount; } - public function getLast(): null|TransactionJournal + public function getLast(): ?TransactionJournal { return $this->user ->transactionJournals() ->orderBy('date', 'DESC') - ->first(['transaction_journals.*']); + ->first(['transaction_journals.*']) + ; } public function getLinkNoteText(TransactionJournalLink $link): string @@ -131,7 +134,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDateById(int $journalId, string $field): null|Carbon + public function getMetaDateById(int $journalId, string $field): ?Carbon { $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); @@ -172,7 +175,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** * Find a specific journal. */ - public function find(int $journalId): null|TransactionJournal + public function find(int $journalId): ?TransactionJournal { /** @var null|TransactionJournal */ return $this->user->transactionJournals()->find($journalId); @@ -186,7 +189,8 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac $query = $this->user ->transactionJournals() ->orderBy('date', 'DESC') - ->orderBy('description', 'ASC'); + ->orderBy('description', 'ASC') + ; if ('' !== $search) { $query->whereLike('description', sprintf('%%%s%%', $search)); } diff --git a/app/Repositories/Journal/JournalRepositoryInterface.php b/app/Repositories/Journal/JournalRepositoryInterface.php index f5bc93f8e5..8971bf9234 100644 --- a/app/Repositories/Journal/JournalRepositoryInterface.php +++ b/app/Repositories/Journal/JournalRepositoryInterface.php @@ -60,14 +60,14 @@ interface JournalRepositoryInterface /** * Find a specific journal. */ - public function find(int $journalId): null|TransactionJournal; + public function find(int $journalId): ?TransactionJournal; public function findByType(array $types): Collection; /** * Get users very first transaction journal. */ - public function firstNull(): null|TransactionJournal; + public function firstNull(): ?TransactionJournal; /** * Returns the destination account of the journal. @@ -81,14 +81,14 @@ interface JournalRepositoryInterface */ public function getJournalTotal(TransactionJournal $journal): string; - public function getLast(): null|TransactionJournal; + public function getLast(): ?TransactionJournal; public function getLinkNoteText(TransactionJournalLink $link): string; /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDateById(int $journalId, string $field): null|Carbon; + public function getMetaDateById(int $journalId, string $field): ?Carbon; /** * Returns the source account of the journal. diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index 6e787b26cc..def2c260f9 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -45,7 +45,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $linkType->transactionJournalLinks()->count(); } - public function destroy(LinkType $linkType, null|LinkType $moveTo = null): bool + public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool { if ($moveTo instanceof LinkType) { TransactionJournalLink::where('link_type_id', $linkType->id)->update(['link_type_id' => $moveTo->id]); @@ -113,7 +113,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * Returns all the journal links (of a specific type). */ - public function getJournalLinks(null|LinkType $linkType = null): Collection + public function getJournalLinks(?LinkType $linkType = null): Collection { $query = TransactionJournalLink::with(['source', 'destination']) ->leftJoin('transaction_journals as source_journals', 'journal_links.source_id', '=', 'source_journals.id') @@ -121,7 +121,8 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf ->where('source_journals.user_id', $this->user->id) ->where('dest_journals.user_id', $this->user->id) ->whereNull('source_journals.deleted_at') - ->whereNull('dest_journals.deleted_at'); + ->whereNull('dest_journals.deleted_at') + ; if ($linkType instanceof LinkType) { $query->where('journal_links.link_type_id', $linkType->id); @@ -130,7 +131,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $query->get(['journal_links.*']); } - public function getLink(TransactionJournal $one, TransactionJournal $two): null|TransactionJournalLink + public function getLink(TransactionJournal $one, TransactionJournal $two): ?TransactionJournalLink { $left = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->first(); if (null !== $left) { @@ -149,15 +150,15 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $inward = TransactionJournalLink::whereDestinationId($journal->id)->get(); $merged = $outward->merge($inward); - return $merged->filter(static fn(TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination); + return $merged->filter(static fn (TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination); } public function store(array $data): LinkType { - $linkType = new LinkType(); - $linkType->name = $data['name']; - $linkType->inward = $data['inward']; - $linkType->outward = $data['outward']; + $linkType = new LinkType(); + $linkType->name = $data['name']; + $linkType->inward = $data['inward']; + $linkType->outward = $data['outward']; $linkType->editable = true; $linkType->save(); @@ -169,7 +170,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf * * @throws Exception */ - public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink + public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink { $linkType = $this->find((int) ($information['link_type_id'] ?? 0)); @@ -187,7 +188,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $existing; } - $link = new TransactionJournalLink(); + $link = new TransactionJournalLink(); $link->linkType()->associate($linkType); if ('inward' === $information['direction']) { Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id)); @@ -208,12 +209,12 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $link; } - public function find(int $linkTypeId): null|LinkType + public function find(int $linkTypeId): ?LinkType { return LinkType::find($linkTypeId); } - public function findByName(null|string $name = null): null|LinkType + public function findByName(?string $name = null): ?LinkType { if (null === $name) { return null; @@ -225,12 +226,13 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * See if such a link already exists (and get it). */ - public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink + public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink { return TransactionJournalLink::where('link_type_id', $linkType->id) ->where('source_id', $inward->id) ->where('destination_id', $outward->id) - ->first(); + ->first() + ; } /** @@ -265,8 +267,8 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf public function switchLink(TransactionJournalLink $link): bool { - $source = $link->source_id; - $link->source_id = $link->destination_id; + $source = $link->source_id; + $link->source_id = $link->destination_id; $link->destination_id = $source; $link->save(); @@ -280,7 +282,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf */ public function updateLink(TransactionJournalLink $journalLink, array $data): TransactionJournalLink { - $journalLink->source_id = $data['inward_id'] ?? $journalLink->source_id; + $journalLink->source_id = $data['inward_id'] ?? $journalLink->source_id; $journalLink->destination_id = $data['outward_id'] ?? $journalLink->destination_id; $journalLink->save(); if (array_key_exists('link_type_name', $data)) { @@ -292,7 +294,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $journalLink->refresh(); } - $journalLink->link_type_id = $data['link_type_id'] ?? $journalLink->link_type_id; + $journalLink->link_type_id = $data['link_type_id'] ?? $journalLink->link_type_id; $journalLink->save(); if (array_key_exists('notes', $data) && null !== $data['notes']) { $this->setNoteText($journalLink, $data['notes']); diff --git a/app/Repositories/LinkType/LinkTypeRepositoryInterface.php b/app/Repositories/LinkType/LinkTypeRepositoryInterface.php index 87ef87c8ec..23cdeca825 100644 --- a/app/Repositories/LinkType/LinkTypeRepositoryInterface.php +++ b/app/Repositories/LinkType/LinkTypeRepositoryInterface.php @@ -46,16 +46,16 @@ interface LinkTypeRepositoryInterface { public function countJournals(LinkType $linkType): int; - public function destroy(LinkType $linkType, null|LinkType $moveTo = null): bool; + public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool; public function destroyLink(TransactionJournalLink $link): bool; - public function find(int $linkTypeId): null|LinkType; + public function find(int $linkTypeId): ?LinkType; /** * Find link type by name. */ - public function findByName(null|string $name = null): null|LinkType; + public function findByName(?string $name = null): ?LinkType; /** * Check if link exists between journals. @@ -65,7 +65,7 @@ interface LinkTypeRepositoryInterface /** * See if such a link already exists (and get it). */ - public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink; + public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink; public function get(): Collection; @@ -74,7 +74,7 @@ interface LinkTypeRepositoryInterface */ public function getJournalIds(LinkType $linkType): array; - public function getJournalLinks(null|LinkType $linkType = null): Collection; + public function getJournalLinks(?LinkType $linkType = null): Collection; /** * Return list of existing connections. @@ -86,7 +86,7 @@ interface LinkTypeRepositoryInterface /** * Store link between two journals. */ - public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink; + public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink; public function switchLink(TransactionJournalLink $link): bool; diff --git a/app/Repositories/ObjectGroup/CreatesObjectGroups.php b/app/Repositories/ObjectGroup/CreatesObjectGroups.php index a480551687..e77d7823ea 100644 --- a/app/Repositories/ObjectGroup/CreatesObjectGroups.php +++ b/app/Repositories/ObjectGroup/CreatesObjectGroups.php @@ -31,16 +31,17 @@ use FireflyIII\Models\ObjectGroup; */ trait CreatesObjectGroups { - protected function findObjectGroupById(int $groupId): null|ObjectGroup + protected function findObjectGroupById(int $groupId): ?ObjectGroup { /** @var null|ObjectGroup */ return $this->user ->objectGroups() ->where('id', $groupId) - ->first(); + ->first() + ; } - protected function findOrCreateObjectGroup(string $title): null|ObjectGroup + protected function findOrCreateObjectGroup(string $title): ?ObjectGroup { $title = substr($title, 0, 255); $maxOrder = $this->getObjectGroupMaxOrder(); @@ -49,7 +50,7 @@ trait CreatesObjectGroups 'user_id' => $this->user->id, 'user_group_id' => $this->user->user_group_id, 'title' => $title, - 'order' => $maxOrder + 1 + 'order' => $maxOrder + 1, ]); } @@ -66,15 +67,17 @@ trait CreatesObjectGroups return 1 === $this->user ->objectGroups() ->where('title', $title) - ->count(); + ->count() + ; } - protected function findObjectGroup(string $title): null|ObjectGroup + protected function findObjectGroup(string $title): ?ObjectGroup { /** @var null|ObjectGroup */ return $this->user ->objectGroups() ->where('title', $title) - ->first(); + ->first() + ; } } diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php index a69c0fae31..449c1669de 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php @@ -58,7 +58,8 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup ->with(['piggyBanks', 'bills']) ->orderBy('order', 'ASC') ->orderBy('title', 'ASC') - ->get(); + ->get() + ; } public function deleteEmpty(): void @@ -124,7 +125,8 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup $dbQuery = $this->user ->objectGroups() ->orderBy('order', 'ASC') - ->orderBy('title', 'ASC'); + ->orderBy('title', 'ASC') + ; if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); @@ -162,7 +164,8 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup ->where('object_groups.order', '<=', $newOrder) ->where('object_groups.order', '>', $oldOrder) ->where('object_groups.id', '!=', $objectGroup->id) - ->decrement('object_groups.order'); + ->decrement('object_groups.order') + ; $objectGroup->order = $newOrder; $objectGroup->save(); @@ -173,7 +176,8 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup ->where('object_groups.order', '>=', $newOrder) ->where('object_groups.order', '<', $oldOrder) ->where('object_groups.id', '!=', $objectGroup->id) - ->increment('object_groups.order'); + ->increment('object_groups.order') + ; $objectGroup->order = $newOrder; $objectGroup->save(); diff --git a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php index 616f07944b..0adbae44f0 100644 --- a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php +++ b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php @@ -50,17 +50,17 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic { - $stat = new PeriodStatistic(); + $stat = new PeriodStatistic(); $stat->primaryStatable()->associate($model); $stat->transaction_currency_id = $currencyId; - $stat->user_group_id = $this->getUserGroup()->id; - $stat->start = $start; - $stat->start_tz = $start->format('e'); - $stat->end = $end; - $stat->end_tz = $end->format('e'); - $stat->amount = $amount; - $stat->count = $count; - $stat->type = $type; + $stat->user_group_id = $this->getUserGroup()->id; + $stat->start = $start; + $stat->start_tz = $start->format('e'); + $stat->end = $end; + $stat->end_tz = $end->format('e'); + $stat->amount = $amount; + $stat->count = $count; + $stat->type = $type; $stat->save(); Log::debug(sprintf( @@ -96,7 +96,8 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U ->where('type', 'LIKE', sprintf('%s%%', $prefix)) ->where('start', '>=', $start) ->where('end', '<=', $end) - ->get(); + ->get() + ; } #[Override] @@ -109,16 +110,16 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U int $count, string $amount ): PeriodStatistic { - $stat = new PeriodStatistic(); + $stat = new PeriodStatistic(); $stat->transaction_currency_id = $currencyId; - $stat->user_group_id = $this->getUserGroup()->id; - $stat->start = $start; - $stat->start_tz = $start->format('e'); - $stat->end = $end; - $stat->end_tz = $end->format('e'); - $stat->amount = $amount; - $stat->count = $count; - $stat->type = sprintf('%s_%s', $prefix, $type); + $stat->user_group_id = $this->getUserGroup()->id; + $stat->start = $start; + $stat->start_tz = $start->format('e'); + $stat->end = $end; + $stat->end_tz = $end->format('e'); + $stat->amount = $amount; + $stat->count = $count; + $stat->type = sprintf('%s_%s', $prefix, $type); $stat->save(); Log::debug(sprintf( diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php index b531353c13..7de020c89f 100644 --- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php +++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php @@ -64,17 +64,17 @@ trait ModifiesPiggyBanks } } - public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool + public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool { - $currentAmount = $this->getCurrentAmount($piggyBank, $account); - $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; - $pivot->current_amount = bcsub((string) $currentAmount, $amount); + $currentAmount = $this->getCurrentAmount($piggyBank, $account); + $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; + $pivot->current_amount = bcsub((string) $currentAmount, $amount); $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount); } @@ -87,17 +87,17 @@ trait ModifiesPiggyBanks return true; } - public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool + public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool { - $currentAmount = $this->getCurrentAmount($piggyBank, $account); - $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; - $pivot->current_amount = bcadd((string) $currentAmount, $amount); + $currentAmount = $this->getCurrentAmount($piggyBank, $account); + $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; + $pivot->current_amount = bcadd((string) $currentAmount, $amount); $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount); } @@ -128,8 +128,8 @@ trait ModifiesPiggyBanks Log::debug(sprintf('Maximum amount: %s', $maxAmount)); } - $compare = bccomp($amount, (string) $maxAmount); - $result = $compare <= 0; + $compare = bccomp($amount, (string) $maxAmount); + $result = $compare <= 0; Log::debug(sprintf('Compare <= 0? %d, so canAddAmount is %s', $compare, var_export($result, true))); @@ -163,15 +163,15 @@ trait ModifiesPiggyBanks public function setCurrentAmount(PiggyBank $piggyBank, string $amount): PiggyBank { - $repetition = $this->getRepetition($piggyBank); + $repetition = $this->getRepetition($piggyBank); if (null === $repetition) { return $piggyBank; } - $max = $piggyBank->target_amount; + $max = $piggyBank->target_amount; if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->target_amount, '0')) { $amount = $max; } - $difference = bcsub($amount, (string) $repetition->current_amount); + $difference = bcsub($amount, (string) $repetition->current_amount); $repetition->current_amount = $amount; $repetition->save(); @@ -202,7 +202,7 @@ trait ModifiesPiggyBanks */ public function store(array $data): PiggyBank { - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; return $factory->store($data); @@ -210,20 +210,20 @@ trait ModifiesPiggyBanks public function update(PiggyBank $piggyBank, array $data): PiggyBank { - $piggyBank = $this->updateProperties($piggyBank, $data); + $piggyBank = $this->updateProperties($piggyBank, $data); if (array_key_exists('notes', $data)) { $this->updateNote($piggyBank, (string) $data['notes']); } // update the order of the piggy bank: - $oldOrder = $piggyBank->order; - $newOrder = (int) ($data['order'] ?? $oldOrder); + $oldOrder = $piggyBank->order; + $newOrder = (int) ($data['order'] ?? $oldOrder); if ($oldOrder !== $newOrder) { $this->setOrder($piggyBank, $newOrder); } // update the accounts - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; // the piggy bank currency is set or updated FIRST, if it exists. @@ -285,7 +285,7 @@ trait ModifiesPiggyBanks $piggyBank->name = $data['name']; } if (array_key_exists('transaction_currency_id', $data) && is_int($data['transaction_currency_id'])) { - $currency = Amount::getTransactionCurrencyById($data['transaction_currency_id']); + $currency = Amount::getTransactionCurrencyById($data['transaction_currency_id']); $piggyBank->transaction_currency_id = $currency->id; } @@ -296,11 +296,11 @@ trait ModifiesPiggyBanks $piggyBank->target_amount = '0'; } if (array_key_exists('target_date', $data) && '' !== $data['target_date']) { - $piggyBank->target_date = $data['target_date']; + $piggyBank->target_date = $data['target_date']; $piggyBank->target_date_tz = $data['target_date']?->format('e'); } if (array_key_exists('start_date', $data)) { - $piggyBank->start_date = $data['start_date']; + $piggyBank->start_date = $data['start_date']; $piggyBank->start_date_tz = $data['target_date']?->format('e'); } $piggyBank->save(); @@ -316,7 +316,7 @@ trait ModifiesPiggyBanks return; } - $dbNote = $piggyBank->notes()->first(); + $dbNote = $piggyBank->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($piggyBank); @@ -327,7 +327,7 @@ trait ModifiesPiggyBanks public function setOrder(PiggyBank $piggyBank, int $newOrder): bool { - $oldOrder = $piggyBank->order; + $oldOrder = $piggyBank->order; // Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); if ($newOrder > $oldOrder) { PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') @@ -337,7 +337,8 @@ trait ModifiesPiggyBanks ->where('piggy_banks.order', '>', $oldOrder) ->where('piggy_banks.id', '!=', $piggyBank->id) ->distinct() - ->decrement('piggy_banks.order'); + ->decrement('piggy_banks.order') + ; $piggyBank->order = $newOrder; Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); @@ -352,7 +353,8 @@ trait ModifiesPiggyBanks ->where('piggy_banks.order', '<', $oldOrder) ->where('piggy_banks.id', '!=', $piggyBank->id) ->distinct() - ->increment('piggy_banks.order'); + ->increment('piggy_banks.order') + ; $piggyBank->order = $newOrder; Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); @@ -373,7 +375,7 @@ trait ModifiesPiggyBanks } // if this account contains less than the amount, remove the current amount, update the amount and continue. $this->removeAmount($piggyBank, $account, $current); - $amount = bcsub($amount, (string) $current); + $amount = bcsub($amount, (string) $current); } } } diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index b251f8ce37..9538912d03 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -62,10 +62,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->delete(); + ->delete() + ; } - public function findPiggyBank(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank + public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank { Log::debug('Searching for piggy information.'); @@ -90,37 +91,39 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte return null; } - public function find(int $piggyBankId): null|PiggyBank + public function find(int $piggyBankId): ?PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.id', $piggyBankId) - ->first(['piggy_banks.*']); + ->first(['piggy_banks.*']) + ; } /** * Find by name or return NULL. */ - public function findByName(string $name): null|PiggyBank + public function findByName(string $name): ?PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.name', $name) - ->first(['piggy_banks.*']); + ->first(['piggy_banks.*']) + ; } public function getAttachments(PiggyBank $piggyBank): Collection { - $set = $piggyBank->attachments()->get(); + $set = $piggyBank->attachments()->get(); $disk = Storage::disk('upload'); return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + $attachment->notes_text = null !== $notes ? $notes->text : ''; return $attachment; }); @@ -129,7 +132,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** * Get current amount saved in piggy bank. */ - public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, null|Account $account = null): string + public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, ?Account $account = null): string { $sum = '0'; foreach ($piggyBank->accounts as $current) { @@ -158,15 +161,15 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte { Log::debug(sprintf('Now in getExactAmount(%d, %d)', $piggyBank->id, $journal->id)); - $operator = null; - $currency = null; + $operator = null; + $currency = null; /** @var JournalRepositoryInterface $journalRepost */ - $journalRepost = app(JournalRepositoryInterface::class); + $journalRepost = app(JournalRepositoryInterface::class); $journalRepost->setUser($this->user); /** @var AccountRepositoryInterface $accountRepos */ - $accountRepos = app(AccountRepositoryInterface::class); + $accountRepos = app(AccountRepositoryInterface::class); $accountRepos->setUser($this->user); $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); @@ -174,11 +177,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte Log::debug(sprintf('Piggy bank #%d currency is %s', $piggyBank->id, $piggyBank->transactionCurrency->code)); /** @var Transaction $source */ - $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first(); + $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first(); /** @var Transaction $destination */ - $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first(); - $hits = 0; + $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first(); + $hits = 0; foreach ($piggyBank->accounts as $account) { // matches source, which means amount will be removed from piggy: if ($account->id === $source->account_id) { @@ -208,7 +211,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } // currency of the account + the piggy bank currency are almost the same. // which amount from the transaction matches? - $amount = null; + $amount = null; if ((int) $source->transaction_currency_id === $currency->id) { Log::debug('Use normal amount'); $amount = Steam::{$operator}($source->amount); // @phpstan-ignore-line @@ -224,9 +227,9 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } Log::debug(sprintf('The currency is %s and the amount is %s', $currency->code, $amount)); - $currentAmount = $this->getCurrentAmount($piggyBank); - $room = bcsub($piggyBank->target_amount, $currentAmount); - $compare = bcmul($currentAmount, '-1'); + $currentAmount = $this->getCurrentAmount($piggyBank); + $room = bcsub($piggyBank->target_amount, $currentAmount); + $compare = bcmul($currentAmount, '-1'); if (0 === bccomp($piggyBank->target_amount, '0')) { // amount is zero? then the "room" is positive amount of we wish to add or remove. @@ -261,7 +264,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** * Get current amount saved in piggy bank. */ - public function getCurrentAmount(PiggyBank $piggyBank, null|Account $account = null): string + public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string { $sum = '0'; foreach ($piggyBank->accounts as $current) { @@ -298,7 +301,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** @var PiggyBank $piggy */ foreach ($set as $piggy) { $currentAmount = $this->getCurrentAmount($piggy); - $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false)); + $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false)); } return $set; @@ -323,10 +326,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte ->with(['objectGroups']) ->orderBy('piggy_banks.order', 'ASC') ->distinct() - ->get(['piggy_banks.*']); + ->get(['piggy_banks.*']) + ; } - public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): null|PiggyBankRepetition + public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): ?PiggyBankRepetition { if (false === $overrule) { throw new FireflyException('[b] Piggy bank repetitions are EOL.'); @@ -400,13 +404,14 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->with(['objectGroups']) - ->delete(); + ->delete() + ; } #[Override] public function resetOrder(): void { - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; $factory->resetOrder(); } @@ -419,7 +424,8 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte ->with(['objectGroups']) ->orderBy('piggy_banks.order', 'ASC') ->orderBy('piggy_banks.name', 'ASC') - ->distinct(); + ->distinct() + ; if ('' !== $query) { $search->whereLike('piggy_banks.name', sprintf('%%%s%%', $query)); } diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php index 97d30b9eeb..0f9a259942 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php +++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php @@ -49,7 +49,7 @@ interface PiggyBankRepositoryInterface { public function resetHistory(PiggyBank $piggyBank): void; - public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool; + public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool; public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void; @@ -64,23 +64,23 @@ interface PiggyBankRepositoryInterface public function destroyAll(): void; - public function find(int $piggyBankId): null|PiggyBank; + public function find(int $piggyBankId): ?PiggyBank; /** * Find by name or return NULL. */ - public function findByName(string $name): null|PiggyBank; + public function findByName(string $name): ?PiggyBank; - public function findPiggyBank(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank; + public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank; public function getAttachments(PiggyBank $piggyBank): Collection; /** * Get current amount saved in piggy bank. */ - public function getCurrentAmount(PiggyBank $piggyBank, null|Account $account = null): string; + public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string; - public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, null|Account $account = null): string; + public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, ?Account $account = null): string; /** * Get all events. @@ -111,7 +111,7 @@ interface PiggyBankRepositoryInterface */ public function getPiggyBanksWithAmount(): Collection; - public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): null|PiggyBankRepetition; + public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): ?PiggyBankRepetition; /** * Returns the suggested amount the user should save per month, or "". @@ -125,7 +125,7 @@ interface PiggyBankRepositoryInterface public function purgeAll(): void; - public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool; + public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool; public function removeAmountFromAll(PiggyBank $piggyBank, string $amount): void; diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 106843ae5a..c9a8a41580 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -104,7 +104,8 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->orderBy('active', 'DESC') ->orderBy('transaction_type_id', 'ASC') ->orderBy('title', 'ASC') - ->get(); + ->get() + ; } /** @@ -132,10 +133,11 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return Recurrence::with(['TransactionCurrency', 'TransactionType', 'RecurrenceRepetitions', 'RecurrenceTransactions']) ->orderBy('active', 'DESC') ->orderBy('title', 'ASC') - ->get(); + ->get() + ; } - public function getBillId(RecurrenceTransaction $recTransaction): null|int + public function getBillId(RecurrenceTransaction $recTransaction): ?int { $return = null; @@ -152,7 +154,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the budget ID from a recurring transaction transaction. */ - public function getBudget(RecurrenceTransaction $recTransaction): null|int + public function getBudget(RecurrenceTransaction $recTransaction): ?int { $return = 0; @@ -169,7 +171,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the category from a recurring transaction transaction. */ - public function getCategoryId(RecurrenceTransaction $recTransaction): null|int + public function getCategoryId(RecurrenceTransaction $recTransaction): ?int { $return = ''; @@ -186,7 +188,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the category from a recurring transaction transaction. */ - public function getCategoryName(RecurrenceTransaction $recTransaction): null|string + public function getCategoryName(RecurrenceTransaction $recTransaction): ?string { $return = ''; @@ -203,14 +205,15 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Returns the journals created for this recurrence, possibly limited by time. */ - public function getJournalCount(Recurrence $recurrence, null|Carbon $start = null, null|Carbon $end = null): int + public function getJournalCount(Recurrence $recurrence, ?Carbon $start = null, ?Carbon $end = null): int { Log::debug(sprintf('Now in getJournalCount(#%d, "%s", "%s")', $recurrence->id, $start?->format('Y-m-d H:i:s'), $end?->format('Y-m-d H:i:s'))); $query = TransactionJournal::leftJoin('journal_meta', 'journal_meta.transaction_journal_id', '=', 'transaction_journals.id') ->where('transaction_journals.user_id', $recurrence->user_id) ->whereNull('transaction_journals.deleted_at') ->where('journal_meta.name', 'recurrence_id') - ->where('journal_meta.data', '"' . $recurrence->id . '"'); + ->where('journal_meta.data', '"'.$recurrence->id.'"') + ; if ($start instanceof Carbon) { $query->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00')); } @@ -234,7 +237,8 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('journal_meta.data', '=', json_encode((string) $recurrence->id)) ->get(['journal_meta.transaction_journal_id']) ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; } /** @@ -248,7 +252,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return (string) $note?->text; } - public function getPiggyBank(RecurrenceTransaction $transaction): null|int + public function getPiggyBank(RecurrenceTransaction $transaction): ?int { $meta = $transaction->recurrenceTransactionMeta; @@ -288,14 +292,15 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('data', json_encode((string) $recurrence->id)) ->get() ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $search = []; foreach ($journalMeta as $journalId) { $search[] = (int) $journalId; } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($recurrence->user); $collector->withCategoryInformation()->withBudgetInformation()->setLimit($pageSize)->setPage($page)->withAccountInformation(); @@ -313,7 +318,8 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('data', json_encode((string) $recurrence->id)) ->get() ->pluck('transaction_journal_id') - ->toArray(); + ->toArray() + ; $search = []; foreach ($journalMeta as $journalId) { @@ -324,7 +330,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($recurrence->user); $collector->withCategoryInformation()->withBudgetInformation()->withAccountInformation(); @@ -403,7 +409,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return $this->filterMaxDate($repeatUntil, $occurrences); } - private function filterMaxDate(null|Carbon $max, array $occurrences): array + private function filterMaxDate(?Carbon $max, array $occurrences): array { $filtered = []; if (!$max instanceof Carbon) { @@ -465,21 +471,21 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ); } if ('ndom' === $repetition->repetition_type) { - $parts = explode(',', $repetition->repetition_moment); + $parts = explode(',', $repetition->repetition_moment); // first part is number of week, second is weekday. $dayOfWeek = trans(sprintf('config.dow_%s', $parts[1]), [], $language); return (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $language); } if ('yearly' === $repetition->repetition_type) { - $today = today(config('app.timezone'))->endOfYear(); - $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); + $today = today(config('app.timezone'))->endOfYear(); + $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); if (!$repDate instanceof Carbon) { $repDate = clone $today; } $diffInYears = (int) $today->diffInYears($repDate, true); $repDate->addYears($diffInYears); // technically not necessary. - $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); + $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); return (string) trans('firefly.recurring_yearly', ['date' => $string], $language); } @@ -539,7 +545,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte $occurrences = []; $mutator = clone $start; $mutator->startOfDay(); - $skipMod = $repetition->repetition_skip + 1; + $skipMod = $repetition->repetition_skip + 1; Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); diff --git a/app/Repositories/Recurring/RecurringRepositoryInterface.php b/app/Repositories/Recurring/RecurringRepositoryInterface.php index 23e7608d6b..9fb715e545 100644 --- a/app/Repositories/Recurring/RecurringRepositoryInterface.php +++ b/app/Repositories/Recurring/RecurringRepositoryInterface.php @@ -73,27 +73,27 @@ interface RecurringRepositoryInterface /** * Get the category from a recurring transaction transaction. */ - public function getBillId(RecurrenceTransaction $recTransaction): null|int; + public function getBillId(RecurrenceTransaction $recTransaction): ?int; /** * Get the budget ID from a recurring transaction transaction. */ - public function getBudget(RecurrenceTransaction $recTransaction): null|int; + public function getBudget(RecurrenceTransaction $recTransaction): ?int; /** * Get the category from a recurring transaction transaction. */ - public function getCategoryId(RecurrenceTransaction $recTransaction): null|int; + public function getCategoryId(RecurrenceTransaction $recTransaction): ?int; /** * Get the category from a recurring transaction transaction. */ - public function getCategoryName(RecurrenceTransaction $recTransaction): null|string; + public function getCategoryName(RecurrenceTransaction $recTransaction): ?string; /** * Returns the count of journals created for this recurrence, possibly limited by time. */ - public function getJournalCount(Recurrence $recurrence, null|Carbon $start = null, null|Carbon $end = null): int; + public function getJournalCount(Recurrence $recurrence, ?Carbon $start = null, ?Carbon $end = null): int; /** * Get journal ID's for journals created by this recurring transaction. @@ -110,7 +110,7 @@ interface RecurringRepositoryInterface */ public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array; - public function getPiggyBank(RecurrenceTransaction $transaction): null|int; + public function getPiggyBank(RecurrenceTransaction $transaction): ?int; /** * Get the tags from the recurring transaction. diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 8242bae0f2..836e5b44e9 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -61,14 +61,14 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function duplicate(Rule $rule): Rule { - $newRule = $rule->replicate(); + $newRule = $rule->replicate(); $newRule->title = (string) trans('firefly.rule_copy_of', ['title' => $rule->title]); $newRule->save(); // replicate all triggers /** @var RuleTrigger $trigger */ foreach ($rule->ruleTriggers as $trigger) { - $newTrigger = $trigger->replicate(); + $newTrigger = $trigger->replicate(); $newTrigger->rule_id = $newRule->id; $newTrigger->save(); } @@ -76,7 +76,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface // replicate all actions /** @var RuleAction $action */ foreach ($rule->ruleActions as $action) { - $newAction = $action->replicate(); + $newAction = $action->replicate(); $newAction->rule_id = $newRule->id; $newAction->save(); } @@ -92,7 +92,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface return $this->user ->rules() ->with(['ruleGroup']) - ->get(); + ->get() + ; } /** @@ -116,7 +117,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface { $count = $rule->ruleTriggers()->count(); if (0 === $count) { - throw new FireflyException('Rules should have more than zero triggers, rule #' . $rule->id . ' has none!'); + throw new FireflyException('Rules should have more than zero triggers, rule #'.$rule->id.' has none!'); } return $rule->ruleTriggers()->where('trigger_type', 'user_action')->first()->trigger_value; @@ -146,7 +147,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface if ('user_action' === $trigger->trigger_type) { continue; } - $triggerType = $trigger->trigger_type; + $triggerType = $trigger->trigger_type; if (str_starts_with((string) $trigger->trigger_type, '-')) { $triggerType = substr((string) $trigger->trigger_type, 1); } @@ -173,7 +174,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->orderBy('rules.order', 'ASC') ->orderBy('rules.id', 'ASC') ->with(['ruleGroup', 'ruleTriggers']) - ->get(['rules.*']); + ->get(['rules.*']) + ; $filtered = new Collection(); /** @var Rule $rule */ @@ -200,7 +202,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->orderBy('rules.order', 'ASC') ->orderBy('rules.id', 'ASC') ->with(['ruleGroup', 'ruleTriggers']) - ->get(); + ->get() + ; $filtered = new Collection(); /** @var Rule $rule */ @@ -232,7 +235,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface */ public function store(array $data): Rule { - $ruleGroup = null; + $ruleGroup = null; if (array_key_exists('rule_group_id', $data)) { $ruleGroup = $this->user->ruleGroups()->find($data['rule_group_id']); } @@ -240,7 +243,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface $ruleGroup = $this->user ->ruleGroups() ->where('title', $data['rule_group_title']) - ->first(); + ->first() + ; } if (null === $ruleGroup) { throw new FireflyException('No such rule group.'); @@ -249,17 +253,17 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface /** @var RuleGroup $ruleGroup */ // start by creating a new rule: - $rule = new Rule(); + $rule = new Rule(); $rule->user()->associate($this->user); $rule->userGroup()->associate($this->user->userGroup); - $rule->rule_group_id = $ruleGroup->id; - $rule->order = 31337; - $rule->active = array_key_exists('active', $data) ? $data['active'] : true; - $rule->strict = array_key_exists('strict', $data) ? $data['strict'] : false; + $rule->rule_group_id = $ruleGroup->id; + $rule->order = 31337; + $rule->active = array_key_exists('active', $data) ? $data['active'] : true; + $rule->strict = array_key_exists('strict', $data) ? $data['strict'] : false; $rule->stop_processing = array_key_exists('stop_processing', $data) ? $data['stop_processing'] : false; - $rule->title = array_key_exists('title', $data) ? $data['title'] : ''; - $rule->description = array_key_exists('description', $data) ? $data['description'] : ''; + $rule->title = array_key_exists('title', $data) ? $data['title'] : ''; + $rule->description = array_key_exists('description', $data) ? $data['description'] : ''; $rule->save(); $rule->refresh(); @@ -284,7 +288,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface return $rule; } - public function find(int $ruleId): null|Rule + public function find(int $ruleId): ?Rule { /** @var null|Rule */ return $this->user->rules()->find($ruleId); @@ -293,19 +297,19 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface private function setRuleTrigger(string $moment, Rule $rule): void { /** @var null|RuleTrigger $trigger */ - $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); + $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); if (null !== $trigger) { $trigger->trigger_value = $moment; $trigger->save(); return; } - $trigger = new RuleTrigger(); - $trigger->order = 0; - $trigger->trigger_type = 'user_action'; - $trigger->trigger_value = $moment; - $trigger->rule_id = $rule->id; - $trigger->active = true; + $trigger = new RuleTrigger(); + $trigger->order = 0; + $trigger->trigger_type = 'user_action'; + $trigger->trigger_value = $moment; + $trigger->rule_id = $rule->id; + $trigger->active = true; $trigger->stop_processing = false; $trigger->save(); } @@ -321,10 +325,10 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function setOrder(Rule $rule, int $newOrder): void { - $oldOrder = $rule->order; - $groupId = $rule->rule_group_id; - $maxOrder = $this->maxOrder($rule->ruleGroup); - $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; + $oldOrder = $rule->order; + $groupId = $rule->rule_group_id; + $maxOrder = $this->maxOrder($rule->ruleGroup); + $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; Log::debug(sprintf('New order will be %d', $newOrder)); if ($newOrder > $oldOrder) { @@ -334,7 +338,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->where('rules.order', '<=', $newOrder) ->where('rules.order', '>', $oldOrder) ->where('rules.id', '!=', $rule->id) - ->decrement('rules.order'); + ->decrement('rules.order') + ; $rule->order = $newOrder; Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); @@ -348,7 +353,8 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface ->where('rules.order', '>=', $newOrder) ->where('rules.order', '<', $oldOrder) ->where('rules.id', '!=', $rule->id) - ->increment('rules.order'); + ->increment('rules.order') + ; $rule->order = $newOrder; Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); @@ -373,7 +379,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface // empty the value in case the rule needs no context // TODO create a helper to automatically return these. - $needTrue = [ + $needTrue = [ 'reconciled', 'has_attachments', 'has_any_category', @@ -394,18 +400,18 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface 'account_is_cash', 'exists', 'no_external_id', - 'any_external_id' + 'any_external_id', ]; if (in_array($type, $needTrue, true)) { $value = ''; } - $triggerValues = [ + $triggerValues = [ 'action' => $type, 'value' => $value, 'stop_processing' => $stopProcessing, 'order' => $order, - 'active' => $active + 'active' => $active, ]; $this->storeTrigger($rule, $triggerValues); ++$order; @@ -414,13 +420,13 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function storeTrigger(Rule $rule, array $values): RuleTrigger { - $ruleTrigger = new RuleTrigger(); + $ruleTrigger = new RuleTrigger(); $ruleTrigger->rule()->associate($rule); - $ruleTrigger->order = $values['order']; - $ruleTrigger->active = $values['active']; + $ruleTrigger->order = $values['order']; + $ruleTrigger->active = $values['active']; $ruleTrigger->stop_processing = $values['stop_processing']; - $ruleTrigger->trigger_type = $values['action']; - $ruleTrigger->trigger_value = $values['value'] ?? ''; + $ruleTrigger->trigger_type = $values['action']; + $ruleTrigger->trigger_value = $values['value'] ?? ''; $ruleTrigger->save(); return $ruleTrigger; @@ -438,7 +444,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface 'value' => $value, 'stop_processing' => $stopProcessing, 'order' => $order, - 'active' => $active + 'active' => $active, ]; $this->storeAction($rule, $actionValues); ++$order; @@ -447,13 +453,13 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function storeAction(Rule $rule, array $values): RuleAction { - $ruleAction = new RuleAction(); + $ruleAction = new RuleAction(); $ruleAction->rule()->associate($rule); - $ruleAction->order = $values['order']; - $ruleAction->active = $values['active']; + $ruleAction->order = $values['order']; + $ruleAction->active = $values['active']; $ruleAction->stop_processing = $values['stop_processing']; - $ruleAction->action_type = $values['action']; - $ruleAction->action_value = $values['value'] ?? ''; + $ruleAction->action_type = $values['action']; + $ruleAction->action_value = $values['value'] ?? ''; $ruleAction->save(); return $ruleAction; @@ -470,7 +476,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface } $rule->save(); $rule->refresh(); - $group = $rule->ruleGroup; + $group = $rule->ruleGroup; // update the order: $this->resetRuleOrder($group); if (array_key_exists('order', $data)) { diff --git a/app/Repositories/Rule/RuleRepositoryInterface.php b/app/Repositories/Rule/RuleRepositoryInterface.php index dcd35730a4..e4d8e53394 100644 --- a/app/Repositories/Rule/RuleRepositoryInterface.php +++ b/app/Repositories/Rule/RuleRepositoryInterface.php @@ -51,7 +51,7 @@ interface RuleRepositoryInterface public function duplicate(Rule $rule): Rule; - public function find(int $ruleId): null|Rule; + public function find(int $ruleId): ?Rule; /** * Get all the users rules. diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index 48211deefa..67a7fa6db5 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -48,7 +48,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->orderBy('order', 'ASC') ->orderBy('active', 'DESC') ->orderBy('title', 'ASC') - ->get(['rule_groups.id']); + ->get(['rule_groups.id']) + ; $index = 1; /** @var RuleGroup $ruleGroup */ @@ -66,7 +67,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte return $this->user ->ruleGroups() ->orderBy('order', 'ASC') - ->get(); + ->get() + ; } public function count(): int @@ -77,7 +79,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte /** * @throws Exception */ - public function destroy(RuleGroup $ruleGroup, null|RuleGroup $moveTo): bool + public function destroy(RuleGroup $ruleGroup, ?RuleGroup $moveTo): bool { /** @var Rule $rule */ foreach ($ruleGroup->rules as $rule) { @@ -108,7 +110,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->whereNull('deleted_at') ->orderBy('order', 'ASC') ->orderBy('title', 'DESC') - ->get(); + ->get() + ; $count = 1; /** @var RuleGroup $entry */ @@ -193,19 +196,20 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte } } - public function find(int $ruleGroupId): null|RuleGroup + public function find(int $ruleGroupId): ?RuleGroup { /** @var null|RuleGroup */ return $this->user->ruleGroups()->find($ruleGroupId); } - public function findByTitle(string $title): null|RuleGroup + public function findByTitle(string $title): ?RuleGroup { /** @var null|RuleGroup */ return $this->user ->ruleGroups() ->where('title', $title) - ->first(); + ->first() + ; } public function getActiveGroups(): Collection @@ -215,7 +219,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->with(['rules']) ->where('rule_groups.active', true) ->orderBy('order', 'ASC') - ->get(['rule_groups.*']); + ->get(['rule_groups.*']) + ; } public function getActiveRules(RuleGroup $group): Collection @@ -232,7 +237,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->where('rule_triggers.trigger_type', 'user_action') ->where('rule_triggers.trigger_value', 'store-journal') ->where('rules.active', true) - ->get(['rules.*']); + ->get(['rules.*']) + ; } public function getActiveUpdateRules(RuleGroup $group): Collection @@ -243,10 +249,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->where('rule_triggers.trigger_type', 'user_action') ->where('rule_triggers.trigger_value', 'update-journal') ->where('rules.active', true) - ->get(['rules.*']); + ->get(['rules.*']) + ; } - public function getAllRuleGroupsWithRules(null|string $filter): Collection + public function getAllRuleGroupsWithRules(?string $filter): Collection { $groups = $this->user ->ruleGroups() @@ -262,9 +269,10 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte }, 'rules.ruleActions' => static function (HasMany $query): void { $query->orderBy('order', 'ASC'); - } + }, ]) - ->get(); + ->get() + ; if (null === $filter) { return $groups; } @@ -298,7 +306,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte return (int) $entry; } - public function getRuleGroupsWithRules(null|string $filter): Collection + public function getRuleGroupsWithRules(?string $filter): Collection { $groups = $this->user ->ruleGroups() @@ -314,9 +322,10 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte }, 'rules.ruleActions' => static function (HasMany $query): void { $query->orderBy('order', 'ASC'); - } + }, ]) - ->get(); + ->get() + ; if (null === $filter) { return $groups; } @@ -353,7 +362,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte return (int) $this->user ->ruleGroups() ->where('active', true) - ->max('order'); + ->max('order') + ; } public function searchRuleGroup(string $query, int $limit): Collection @@ -375,7 +385,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte 'title' => $data['title'], 'description' => $data['description'], 'order' => 31337, - 'active' => array_key_exists('active', $data) ? $data['active'] : true + 'active' => array_key_exists('active', $data) ? $data['active'] : true, ]); $newRuleGroup->save(); $this->resetOrder(); @@ -388,7 +398,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte public function setOrder(RuleGroup $ruleGroup, int $newOrder): void { - $oldOrder = $ruleGroup->order; + $oldOrder = $ruleGroup->order; if ($newOrder > $oldOrder) { $this->user @@ -396,7 +406,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->where('rule_groups.order', '<=', $newOrder) ->where('rule_groups.order', '>', $oldOrder) ->where('rule_groups.id', '!=', $ruleGroup->id) - ->decrement('order'); + ->decrement('order') + ; $ruleGroup->order = $newOrder; Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); $ruleGroup->save(); @@ -409,7 +420,8 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->where('rule_groups.order', '>=', $newOrder) ->where('rule_groups.order', '<', $oldOrder) ->where('rule_groups.id', '!=', $ruleGroup->id) - ->increment('order'); + ->increment('order') + ; $ruleGroup->order = $newOrder; Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); $ruleGroup->save(); diff --git a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php index 552de07dd9..54b24c1adb 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php +++ b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php @@ -49,16 +49,16 @@ interface RuleGroupRepositoryInterface public function count(): int; - public function destroy(RuleGroup $ruleGroup, null|RuleGroup $moveTo): bool; + public function destroy(RuleGroup $ruleGroup, ?RuleGroup $moveTo): bool; /** * Delete everything. */ public function destroyAll(): void; - public function find(int $ruleGroupId): null|RuleGroup; + public function find(int $ruleGroupId): ?RuleGroup; - public function findByTitle(string $title): null|RuleGroup; + public function findByTitle(string $title): ?RuleGroup; /** * Get all rule groups. @@ -76,11 +76,11 @@ interface RuleGroupRepositoryInterface /** * Also inactive groups. */ - public function getAllRuleGroupsWithRules(null|string $filter): Collection; + public function getAllRuleGroupsWithRules(?string $filter): Collection; public function getHighestOrderRuleGroup(): int; - public function getRuleGroupsWithRules(null|string $filter): Collection; + public function getRuleGroupsWithRules(?string $filter): Collection; public function getRules(RuleGroup $group): Collection; diff --git a/app/Repositories/Tag/OperationsRepository.php b/app/Repositories/Tag/OperationsRepository.php index c69d8301cd..7cad9543c3 100644 --- a/app/Repositories/Tag/OperationsRepository.php +++ b/app/Repositories/Tag/OperationsRepository.php @@ -45,12 +45,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $tagIds = []; + $tagIds = []; if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } @@ -74,14 +74,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int) $tag['id']; - $tagName = (string) $tag['name']; - $journalId = (int) $journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (!in_array($tagId, $tagIds, true)) { continue; } @@ -90,7 +90,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if (in_array($journalId, $listedJournals, true)) { continue; } - $listedJournals[] = $journalId; + $listedJournals[] = $journalId; $array[$currencyId]['tags'][$tagId] ??= ['id' => $tagId, 'name' => $tagName, 'transaction_journals' => []]; $array[$currencyId]['tags'][$tagId]['transaction_journals'][$journalId] = [ @@ -103,7 +103,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'] + 'transaction_group_id' => $journal['transaction_group_id'], ]; } } @@ -124,12 +124,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $tagIds = []; + $tagIds = []; if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } @@ -154,14 +154,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'] + 'currency_decimal_places' => $journal['currency_decimal_places'], ]; // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int) $tag['id']; - $tagName = (string) $tag['name']; - $journalId = (int) $journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (!in_array($tagId, $tagIds, true)) { continue; @@ -170,10 +170,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if (in_array($journalId, $listedJournals, true)) { continue; } - $listedJournals[] = $journalId; + $listedJournals[] = $journalId; $array[$currencyId]['tags'][$tagId] ??= ['id' => $tagId, 'name' => $tagName, 'transaction_journals' => []]; - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['tags'][$tagId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -183,7 +183,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'] + 'transaction_group_id' => $journal['transaction_group_id'], ]; } } @@ -196,7 +196,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * @throws FireflyException */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array { throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__)); } @@ -206,7 +206,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * @throws FireflyException */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array { throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__)); } diff --git a/app/Repositories/Tag/OperationsRepositoryInterface.php b/app/Repositories/Tag/OperationsRepositoryInterface.php index a96f48e09c..b7cd50c57c 100644 --- a/app/Repositories/Tag/OperationsRepositoryInterface.php +++ b/app/Repositories/Tag/OperationsRepositoryInterface.php @@ -48,22 +48,22 @@ interface OperationsRepositoryInterface * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; + public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; /** * Sum of withdrawal journals in period for a set of tags, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; /** * Sum of income journals in period for a set of tags, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; } diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index b46ff63ccb..4c0d8c29c2 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -85,7 +85,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $this->user ->tags() ->orderBy('tag', 'ASC') - ->get(['tags.*']); + ->get(['tags.*']) + ; } public function expenseInPeriod(Tag $tag, Carbon $start, Carbon $end): array @@ -99,22 +100,23 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $collector->getExtractedJournals(); } - public function find(int $tagId): null|Tag + public function find(int $tagId): ?Tag { /** @var null|Tag */ return $this->user->tags()->find($tagId); } - public function findByTag(string $tag): null|Tag + public function findByTag(string $tag): ?Tag { /** @var null|Tag */ return $this->user ->tags() ->where('tag', $tag) - ->first(); + ->first() + ; } - public function firstUseDate(Tag $tag): null|Carbon + public function firstUseDate(Tag $tag): ?Carbon { return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date; } @@ -126,20 +128,21 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $set->each(static function (Attachment $attachment) use ($disk): void { // @phpstan-ignore-line /** @var null|Note $note */ - $note = $attachment->notes()->first(); + $note = $attachment->notes()->first(); // only used in v1 view of tags $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null === $note ? '' : $note->text; + $attachment->notes_text = null === $note ? '' : $note->text; }); } - public function getTagsInYear(null|int $year): array + public function getTagsInYear(?int $year): array { // get all tags in the year (if present): - $tagQuery = $this->user + $tagQuery = $this->user ->tags() ->with(['locations', 'attachments']) - ->orderBy('tags.tag'); + ->orderBy('tags.tag') + ; // add date range (or not): if (null === $year) { @@ -163,7 +166,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface 'id' => $tag->id, 'created_at' => $tag->created_at, 'location' => $tag->locations->first(), - 'attachments' => $tag->attachments + 'attachments' => $tag->attachments, ]; } @@ -181,7 +184,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $collector->getExtractedJournals(); } - public function lastUseDate(Tag $tag): null|Carbon + public function lastUseDate(Tag $tag): ?Carbon { return $tag->transactionJournals()->orderBy('date', 'DESC')->first()?->date; } @@ -189,24 +192,26 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface /** * Will return the newest tag (if known) or NULL. */ - public function newestTag(): null|Tag + public function newestTag(): ?Tag { /** @var null|Tag */ return $this->user ->tags() ->whereNotNull('date') ->orderBy('date', 'DESC') - ->first(); + ->first() + ; } - public function oldestTag(): null|Tag + public function oldestTag(): ?Tag { /** @var null|Tag */ return $this->user ->tags() ->whereNotNull('date') ->orderBy('date', 'ASC') - ->first(); + ->first() + ; } /** @@ -219,7 +224,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $this->user ->tags() ->whereLike('tag', $search) - ->get(['tags.*']); + ->get(['tags.*']) + ; } /** @@ -245,7 +251,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $factory->create($data); } - public function sumsOfTag(Tag $tag, null|Carbon $start, null|Carbon $end): array + public function sumsOfTag(Tag $tag, ?Carbon $start, ?Carbon $end): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -255,13 +261,13 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface } $collector->setTag($tag)->withAccountInformation(); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); - $sums = []; + $sums = []; /** @var array $journal */ foreach ($journals as $journal) { - $found = false; + $found = false; /** @var array $localTag */ foreach ($journal['tags'] as $localTag) { @@ -272,7 +278,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface if (false === $found) { continue; } - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $sums[$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], @@ -282,18 +288,18 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface TransactionTypeEnum::DEPOSIT->value => '0', TransactionTypeEnum::TRANSFER->value => '0', TransactionTypeEnum::RECONCILIATION->value => '0', - TransactionTypeEnum::OPENING_BALANCE->value => '0' + TransactionTypeEnum::OPENING_BALANCE->value => '0', ]; // add amount to correct type: - $amount = Steam::positive((string) $journal['amount']); - $type = $journal['transaction_type_type']; + $amount = Steam::positive((string) $journal['amount']); + $type = $journal['transaction_type_type']; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $amount = bcmul($amount, '-1'); } $sums[$currencyId][$type] = bcadd((string) $sums[$currencyId][$type], $amount); - $foreignCurrencyId = $journal['foreign_currency_id']; + $foreignCurrencyId = $journal['foreign_currency_id']; if (null !== $foreignCurrencyId && 0 !== $foreignCurrencyId) { $sums[$foreignCurrencyId] ??= [ 'currency_id' => $foreignCurrencyId, @@ -304,10 +310,10 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface TransactionTypeEnum::DEPOSIT->value => '0', TransactionTypeEnum::TRANSFER->value => '0', TransactionTypeEnum::RECONCILIATION->value => '0', - TransactionTypeEnum::OPENING_BALANCE->value => '0' + TransactionTypeEnum::OPENING_BALANCE->value => '0', ]; // add foreign amount to correct type: - $amount = Steam::positive((string) $journal['foreign_amount']); + $amount = Steam::positive((string) $journal['foreign_amount']); if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $amount = bcmul($amount, '-1'); } @@ -325,7 +331,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $this->user ->tags() ->whereLike('tag', $search) - ->get(['tags.*']); + ->get(['tags.*']) + ; } public function tagStartsWith(string $query): Collection @@ -335,7 +342,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $this->user ->tags() ->whereLike('tag', $search) - ->get(['tags.*']); + ->get(['tags.*']) + ; } public function transferredInPeriod(Tag $tag, Carbon $start, Carbon $end): array @@ -360,7 +368,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface $tag->description = $data['description']; } - $tag->latitude = null; + $tag->latitude = null; $tag->longitude = null; $tag->zoomLevel = null; $tag->save(); @@ -378,14 +386,14 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { - $location = $this->getLocation($tag); + $location = $this->getLocation($tag); if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($tag); } - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->save(); } @@ -397,7 +405,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $tag; } - public function getLocation(Tag $tag): null|Location + public function getLocation(Tag $tag): ?Location { /** @var null|Location */ return $tag->locations()->first(); @@ -438,7 +446,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount' + 'transactions.foreign_amount', ]) ->toArray(); } diff --git a/app/Repositories/Tag/TagRepositoryInterface.php b/app/Repositories/Tag/TagRepositoryInterface.php index 89f5099b31..5a53efe7fe 100644 --- a/app/Repositories/Tag/TagRepositoryInterface.php +++ b/app/Repositories/Tag/TagRepositoryInterface.php @@ -60,11 +60,11 @@ interface TagRepositoryInterface public function expenseInPeriod(Tag $tag, Carbon $start, Carbon $end): array; - public function find(int $tagId): null|Tag; + public function find(int $tagId): ?Tag; - public function findByTag(string $tag): null|Tag; + public function findByTag(string $tag): ?Tag; - public function firstUseDate(Tag $tag): null|Carbon; + public function firstUseDate(Tag $tag): ?Carbon; /** * This method returns all the user's tags. @@ -76,23 +76,23 @@ interface TagRepositoryInterface /** * Return location, or NULL. */ - public function getLocation(Tag $tag): null|Location; + public function getLocation(Tag $tag): ?Location; - public function getTagsInYear(null|int $year): array; + public function getTagsInYear(?int $year): array; public function incomeInPeriod(Tag $tag, Carbon $start, Carbon $end): array; - public function lastUseDate(Tag $tag): null|Carbon; + public function lastUseDate(Tag $tag): ?Carbon; /** * Will return the newest tag (if known) or NULL. */ - public function newestTag(): null|Tag; + public function newestTag(): ?Tag; /** * Will return the newest tag (if known) or NULL. */ - public function oldestTag(): null|Tag; + public function oldestTag(): ?Tag; /** * Find one or more tags based on the query. @@ -112,7 +112,7 @@ interface TagRepositoryInterface /** * Calculates various amounts in tag. */ - public function sumsOfTag(Tag $tag, null|Carbon $start, null|Carbon $end): array; + public function sumsOfTag(Tag $tag, ?Carbon $start, ?Carbon $end): array; /** * Find one or more tags that start with the string in the query diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 18d2393996..fe617af9c9 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -72,7 +72,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** * Find a transaction group by its ID. */ - public function find(int $groupId): null|TransactionGroup + public function find(int $groupId): ?TransactionGroup { /** @var null|TransactionGroup */ return $this->user->transactionGroups()->find($groupId); @@ -87,7 +87,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, public function expandGroup(TransactionGroup $group): array { - $result = $group->toArray(); + $result = $group->toArray(); $result['transaction_journals'] = []; /** @var TransactionJournal $journal */ @@ -100,16 +100,16 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, private function expandJournal(TransactionJournal $journal): array { - $array = $journal->toArray(); - $array['transactions'] = []; - $array['meta'] = $journal->transactionJournalMeta->toArray(); - $array['tags'] = $journal->tags->toArray(); - $array['categories'] = $journal->categories->toArray(); - $array['budgets'] = $journal->budgets->toArray(); - $array['notes'] = $journal->notes->toArray(); - $array['locations'] = []; - $array['attachments'] = $journal->attachments->toArray(); - $array['links'] = []; + $array = $journal->toArray(); + $array['transactions'] = []; + $array['meta'] = $journal->transactionJournalMeta->toArray(); + $array['tags'] = $journal->tags->toArray(); + $array['categories'] = $journal->categories->toArray(); + $array['budgets'] = $journal->budgets->toArray(); + $array['notes'] = $journal->notes->toArray(); + $array['locations'] = []; + $array['attachments'] = $journal->attachments->toArray(); + $array['links'] = []; $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray(); /** @var Transaction $transaction */ @@ -122,9 +122,9 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, private function expandTransaction(Transaction $transaction): array { - $array = $transaction->toArray(); - $array['account'] = $transaction->account->toArray(); - $array['budgets'] = []; + $array = $transaction->toArray(); + $array['account'] = $transaction->account->toArray(); + $array['budgets'] = []; $array['categories'] = []; foreach ($transaction->categories as $category) { @@ -145,25 +145,26 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, { $repository = app(AttachmentRepositoryInterface::class); $repository->setUser($this->user); - $journals = $group->transactionJournals->pluck('id')->toArray(); - $set = Attachment::whereIn('attachable_id', $journals) + $journals = $group->transactionJournals->pluck('id')->toArray(); + $set = Attachment::whereIn('attachable_id', $journals) ->where('attachable_type', TransactionJournal::class) ->where('uploaded', true) ->whereNull('deleted_at') - ->get(); + ->get() + ; - $result = []; + $result = []; /** @var Attachment $attachment */ foreach ($set as $attachment) { - $journalId = $attachment->attachable_id; + $journalId = $attachment->attachable_id; $result[$journalId] ??= []; - $current = $attachment->toArray(); - $current['file_exists'] = true; - $current['notes'] = $repository->getNoteText($attachment); + $current = $attachment->toArray(); + $current['file_exists'] = true; + $current['notes'] = $repository->getNoteText($attachment); // already determined that this attachable is a TransactionJournal. $current['journal_title'] = $attachment->attachable->description; - $result[$journalId][] = $current; + $result[$journalId][] = $current; } return $result; @@ -172,7 +173,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** * Get the note text for a journal (by ID). */ - public function getNoteText(int $journalId): null|string + public function getNoteText(int $journalId): ?string { /** @var null|Note $note */ $note = Note::where('noteable_id', $journalId)->where('noteable_type', TransactionJournal::class)->first(); @@ -194,7 +195,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, 'journal_links.*', 'link_types.inward', 'link_types.outward', - 'link_types.editable' + 'link_types.editable', ]); /** @var TransactionJournalLink $entry */ @@ -205,8 +206,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, // phpstan: the editable field is provided by the query. if ($journalId === $entry->source_id) { - $amount = $this->getFormattedAmount($entry->destination); - $foreignAmount = $this->getFormattedForeignAmount($entry->destination); + $amount = $this->getFormattedAmount($entry->destination); + $foreignAmount = $this->getFormattedForeignAmount($entry->destination); $return[$journalId][] = [ 'id' => $entry->id, 'link' => $entry->outward, @@ -214,12 +215,12 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, 'description' => $entry->destination->description, 'editable' => 1 === (int) $entry->editable, 'amount' => $amount, - 'foreign_amount' => $foreignAmount + 'foreign_amount' => $foreignAmount, ]; } if ($journalId === $entry->destination_id) { - $amount = $this->getFormattedAmount($entry->source); - $foreignAmount = $this->getFormattedForeignAmount($entry->source); + $amount = $this->getFormattedAmount($entry->source); + $foreignAmount = $this->getFormattedForeignAmount($entry->source); $return[$journalId][] = [ 'id' => $entry->id, 'link' => $entry->inward, @@ -227,7 +228,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, 'description' => $entry->source->description, 'editable' => 1 === (int) $entry->editable, 'amount' => $amount, - 'foreign_amount' => $foreignAmount + 'foreign_amount' => $foreignAmount, ]; } } @@ -261,9 +262,9 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, return ''; } - $currency = $transaction->foreignCurrency; - $type = $journal->transactionType->type; - $amount = Steam::positive($transaction->foreign_amount); + $currency = $transaction->foreignCurrency; + $type = $journal->transactionType->type; + $amount = Steam::positive($transaction->foreign_amount); if (TransactionTypeEnum::WITHDRAWAL->value === $type) { return Amount::formatAnything($currency, Steam::negative($amount)); } @@ -271,7 +272,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, return Amount::formatAnything($currency, $amount); } - public function getLocation(int $journalId): null|Location + public function getLocation(int $journalId): ?Location { /** @var TransactionJournal $journal */ $journal = $this->user->transactionJournals()->find($journalId); @@ -291,7 +292,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->where('transaction_journal_id', $journalId) ->whereIn('name', $fields) ->whereNull('deleted_at') - ->get(['name', 'data']); + ->get(['name', 'data']) + ; $return = []; foreach ($query as $row) { @@ -310,7 +312,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->where('transaction_journal_id', $journalId) ->whereIn('name', $fields) ->whereNull('deleted_at') - ->get(['name', 'data']); + ->get(['name', 'data']) + ; $return = []; foreach ($query as $row) { @@ -338,17 +341,17 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, continue; } // get currency preference. - $currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id)->where('name', 'currency_id')->first(); + $currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id)->where('name', 'currency_id')->first(); if (null !== $currencyPreference) { $currency = Amount::getTransactionCurrencyById((int) $currencyPreference->data); } - $journalId = $row->transaction_journal_id; + $journalId = $row->transaction_journal_id; $return[$journalId] ??= []; $return[$journalId][] = [ 'piggy' => $row->piggyBank->name, 'piggy_id' => $row->piggy_bank_id, - 'amount' => Amount::formatAnything($currency, $row->amount) + 'amount' => Amount::formatAnything($currency, $row->amount), ]; } @@ -375,7 +378,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id') ->where('tag_transaction_journal.transaction_journal_id', $journalId) ->orderBy('tags.tag', 'ASC') - ->get(['tags.tag']); + ->get(['tags.tag']) + ; return $result->pluck('tag')->toArray(); } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php index bcbc4da9f5..e95cd68f75 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php @@ -64,7 +64,7 @@ interface TransactionGroupRepositoryInterface /** * Find a transaction group by its ID. */ - public function find(int $groupId): null|TransactionGroup; + public function find(int $groupId): ?TransactionGroup; /** * Return all attachments for all journals in the group. @@ -79,7 +79,7 @@ interface TransactionGroupRepositoryInterface /** * Get the location of a journal or NULL. */ - public function getLocation(int $journalId): null|Location; + public function getLocation(int $journalId): ?Location; /** * Return object with all found meta field things as Carbon objects. @@ -94,7 +94,7 @@ interface TransactionGroupRepositoryInterface /** * Get the note text for a journal (by ID). */ - public function getNoteText(int $journalId): null|string; + public function getNoteText(int $journalId): ?string; /** * Return all piggy bank events for all journals in the group. diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php index 041314f605..25cdfb741a 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepository.php +++ b/app/Repositories/TransactionType/TransactionTypeRepository.php @@ -34,7 +34,7 @@ use Illuminate\Support\Facades\Log; */ class TransactionTypeRepository implements TransactionTypeRepositoryInterface { - public function findTransactionType(null|TransactionType $type, null|string $typeString): TransactionType + public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType { Log::debug('Now looking for a transaction type.'); if ($type instanceof TransactionType) { @@ -43,7 +43,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface return $type; } $typeString ??= TransactionTypeEnum::WITHDRAWAL->value; - $search = $this->findByType($typeString); + $search = $this->findByType($typeString); if (!$search instanceof TransactionType) { $search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value); } @@ -52,7 +52,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface return $search; } - public function findByType(string $type): null|TransactionType + public function findByType(string $type): ?TransactionType { $search = ucfirst($type); diff --git a/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php b/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php index 78ef7c64a9..dfc8681fba 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php +++ b/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php @@ -43,9 +43,9 @@ use Illuminate\Support\Collection; */ interface TransactionTypeRepositoryInterface { - public function findByType(string $type): null|TransactionType; + public function findByType(string $type): ?TransactionType; - public function findTransactionType(null|TransactionType $type, null|string $typeString): TransactionType; + public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType; public function searchTypes(string $query, int $limit): Collection; } diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index 4eafaaa928..eae5178ce3 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -56,19 +56,19 @@ class UserRepository implements UserRepositoryInterface */ public function changeEmail(User $user, string $newEmail): bool { - $oldEmail = $user->email; + $oldEmail = $user->email; // save old email as pref Preferences::setForUser($user, 'previous_email_latest', $oldEmail); - Preferences::setForUser($user, 'previous_email_' . Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); + Preferences::setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); // set undo and confirm token: Preferences::setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16))); Preferences::setForUser($user, 'email_change_confirm_token', bin2hex(random_bytes(16))); // update user - $user->email = $newEmail; - $user->blocked = true; + $user->email = $newEmail; + $user->blocked = true; $user->blocked_code = 'email_changed'; $user->save(); @@ -86,7 +86,7 @@ class UserRepository implements UserRepositoryInterface public function changeStatus(User $user, bool $isBlocked, string $code): bool { // change blocked status and code: - $user->blocked = $isBlocked; + $user->blocked = $isBlocked; $user->blocked_code = $code; $user->save(); @@ -142,7 +142,7 @@ class UserRepository implements UserRepositoryInterface return User::orderBy('id', 'DESC')->get(['users.*']); } - public function findByEmail(string $email): null|User + public function findByEmail(string $email): ?User { return User::where('email', $email)->first(); } @@ -150,7 +150,7 @@ class UserRepository implements UserRepositoryInterface /** * Returns the first user in the DB. Generally only works when there is just one. */ - public function first(): null|User + public function first(): ?User { return User::orderBy('id', 'ASC')->first(); } @@ -160,7 +160,7 @@ class UserRepository implements UserRepositoryInterface return InvitedUser::with('user')->get(); } - public function getRoleByUser(User $user): null|string + public function getRoleByUser(User $user): ?string { /** @var null|Role $role */ $role = $user->roles()->first(); @@ -174,7 +174,7 @@ class UserRepository implements UserRepositoryInterface public function getRolesInGroup(User $user, int $groupId): array { /** @var null|UserGroup $group */ - $group = UserGroup::find($groupId); + $group = UserGroup::find($groupId); if (null === $group) { throw new FireflyException(sprintf('Could not find group #%d', $groupId)); } @@ -183,14 +183,14 @@ class UserRepository implements UserRepositoryInterface /** @var GroupMembership $membership */ foreach ($memberships as $membership) { - $role = $membership->userRole; + $role = $membership->userRole; $roles[] = $role->title; } return $roles; } - public function find(int $userId): null|User + public function find(int $userId): ?User { return User::find($userId); } @@ -221,7 +221,7 @@ class UserRepository implements UserRepositoryInterface ->count('budget_limits.budget_id'), 'rule_groups' => $user->ruleGroups()->count(), 'rules' => $user->rules()->count(), - 'tags' => $user->tags()->count() + 'tags' => $user->tags()->count(), ]; } @@ -254,7 +254,7 @@ class UserRepository implements UserRepositoryInterface /** @var null|UserGroup $group */ $group = $membership->userGroup()->first(); if (null !== $group) { - $groupId = $group->id; + $groupId = $group->id; if (in_array($groupId, array_keys($set), true)) { continue; } @@ -271,15 +271,15 @@ class UserRepository implements UserRepositoryInterface if (!$user instanceof User) { throw new FireflyException('User is not a User object.'); } - $now = now(config('app.timezone')); + $now = now(config('app.timezone')); $now->addDays(2); - $invitee = new InvitedUser(); + $invitee = new InvitedUser(); $invitee->user()->associate($user); $invitee->invite_code = Str::random(64); - $invitee->email = $email; - $invitee->redeemed = false; - $invitee->expires = $now; - $invitee->expires_tz = $now->format('e'); + $invitee->email = $email; + $invitee->redeemed = false; + $invitee->expires = $now; + $invitee->expires_tz = $now->format('e'); $invitee->save(); return $invitee; @@ -297,7 +297,7 @@ class UserRepository implements UserRepositoryInterface /** * Set MFA code. */ - public function setMFACode(User $user, null|string $code): void + public function setMFACode(User $user, ?string $code): void { $user->mfa_secret = $code; $user->save(); @@ -309,7 +309,7 @@ class UserRepository implements UserRepositoryInterface 'blocked' => $data['blocked'] ?? false, 'blocked_code' => $data['blocked_code'] ?? null, 'email' => $data['email'], - 'password' => Str::random(24) + 'password' => Str::random(24), ]); $role = $data['role'] ?? ''; if ('' !== $role) { @@ -340,7 +340,7 @@ class UserRepository implements UserRepositoryInterface public function unblockUser(User $user): void { - $user->blocked = false; + $user->blocked = false; $user->blocked_code = ''; $user->save(); } @@ -380,11 +380,11 @@ class UserRepository implements UserRepositoryInterface if ('' === $newEmail) { return true; } - $oldEmail = $user->email; + $oldEmail = $user->email; // save old email as pref Preferences::setForUser($user, 'admin_previous_email_latest', $oldEmail); - Preferences::setForUser($user, 'admin_previous_email_' . Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); + Preferences::setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); $user->email = $newEmail; $user->save(); @@ -404,7 +404,7 @@ class UserRepository implements UserRepositoryInterface $user->roles()->detach($roleObj->id); } - public function getRole(string $role): null|Role + public function getRole(string $role): ?Role { return Role::where('name', $role)->first(); } @@ -415,7 +415,8 @@ class UserRepository implements UserRepositoryInterface $invitee = InvitedUser::where('invite_code', $code) ->where('expires', '>', $now->format('Y-m-d H:i:s')) ->where('redeemed', 0) - ->first(); + ->first() + ; return null !== $invitee; } diff --git a/app/Repositories/User/UserRepositoryInterface.php b/app/Repositories/User/UserRepositoryInterface.php index 4bb898e8a0..392ee2f7dc 100644 --- a/app/Repositories/User/UserRepositoryInterface.php +++ b/app/Repositories/User/UserRepositoryInterface.php @@ -82,20 +82,20 @@ interface UserRepositoryInterface public function destroy(User $user): bool; - public function find(int $userId): null|User; + public function find(int $userId): ?User; - public function findByEmail(string $email): null|User; + public function findByEmail(string $email): ?User; /** * Returns the first user in the DB. Generally only works when there is just one. */ - public function first(): null|User; + public function first(): ?User; public function getInvitedUsers(): Collection; - public function getRole(string $role): null|Role; + public function getRole(string $role): ?Role; - public function getRoleByUser(User $user): null|string; + public function getRoleByUser(User $user): ?string; public function getRolesInGroup(User $user, int $groupId): array; @@ -120,7 +120,7 @@ interface UserRepositoryInterface /** * Set MFA code. */ - public function setMFACode(User $user, null|string $code): void; + public function setMFACode(User $user, ?string $code): void; public function store(array $data): User; diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php index 3b52b001ee..6aa8425f46 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -54,7 +54,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte /** @var GroupMembership $membership */ foreach ($memberships as $membership) { /** @var null|User $user */ - $user = $membership->user()->first(); + $user = $membership->user()->first(); if (null === $user) { continue; } @@ -63,7 +63,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $count = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->count(); if (0 === $count) { Log::debug('User has no other memberships and needs a new user group.'); - $newUserGroup = $this->createNewUserGroup($user); + $newUserGroup = $this->createNewUserGroup($user); $user->user_group_id = $newUserGroup->id; $user->save(); Log::debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title)); @@ -73,7 +73,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte 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(); + $first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first(); $user->user_group_id = $first->id; $user->save(); } @@ -83,7 +83,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte // all users are now moved away from user group. // time to DESTROY all objects. // we have to do this one by one to trigger the necessary observers :( - $objects = [ + $objects = [ 'availableBudgets', 'bills', 'budgets', @@ -98,7 +98,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte 'transactionJournals', 'piggyBanks', 'accounts', - 'webhooks' + 'webhooks', ]; foreach ($objects as $object) { foreach ($userGroup->{$object}()->get() as $item) { // @phpstan-ignore-line @@ -123,7 +123,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte /** @var null|UserGroup $group */ $group = $membership->userGroup()->first(); if (null !== $group) { - $groupId = $group->id; + $groupId = $group->id; if (in_array($groupId, array_keys($set), true)) { continue; } @@ -148,18 +148,18 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte while ($exists && $loop < 10) { $existingGroup = $this->findByName($groupName); if (!$existingGroup instanceof UserGroup) { - $exists = false; + $exists = false; $existingGroup = $this->store(['user' => $user, 'title' => $groupName]); } - $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999) . microtime()), 0, 4)); + $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999).microtime()), 0, 4)); ++$loop; } return $existingGroup; } - public function findByName(string $title): null|UserGroup + public function findByName(string $title): ?UserGroup { return UserGroup::whereTitle($title)->first(); } @@ -172,7 +172,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $data['user'] = $this->user; /** @var UserGroupFactory $factory */ - $factory = app(UserGroupFactory::class); + $factory = app(UserGroupFactory::class); return $factory->create($data); } @@ -186,7 +186,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte } #[Override] - public function getById(int $id): null|UserGroup + public function getById(int $id): ?UserGroup { return UserGroup::find($id); } @@ -197,17 +197,18 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte return $this->user ->groupMemberships() ->where('user_group_id', $groupId) - ->get(); + ->get() + ; } public function update(UserGroup $userGroup, array $data): UserGroup { $userGroup->title = $data['title']; $userGroup->save(); - $currency = null; + $currency = null; /** @var CurrencyRepositoryInterface $repository */ - $repository = app(CurrencyRepositoryInterface::class); + $repository = app(CurrencyRepositoryInterface::class); if (array_key_exists('primary_currency_code', $data)) { $repository->setUser($this->user); @@ -232,11 +233,11 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte */ public function updateMembership(UserGroup $userGroup, array $data): UserGroup { - $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); + $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); Log::debug('in update membership'); /** @var null|User $user */ - $user = null; + $user = null; if (array_key_exists('id', $data)) { /** @var null|User $user */ $user = User::find($data['id']); diff --git a/app/Repositories/UserGroup/UserGroupRepositoryInterface.php b/app/Repositories/UserGroup/UserGroupRepositoryInterface.php index ce28fc1f6e..c1a6152ab0 100644 --- a/app/Repositories/UserGroup/UserGroupRepositoryInterface.php +++ b/app/Repositories/UserGroup/UserGroupRepositoryInterface.php @@ -48,7 +48,7 @@ interface UserGroupRepositoryInterface public function getAll(): Collection; - public function getById(int $id): null|UserGroup; + public function getById(int $id): ?UserGroup; public function getMembershipsFromGroupId(int $groupId): Collection; diff --git a/app/Repositories/Webhook/WebhookRepository.php b/app/Repositories/Webhook/WebhookRepository.php index b2862876d0..f29ba0c7fe 100644 --- a/app/Repositories/Webhook/WebhookRepository.php +++ b/app/Repositories/Webhook/WebhookRepository.php @@ -51,7 +51,8 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac ->where('delivery', 1) ->where('response', 1) ->where('trigger', 1) - ->get(); + ->get() + ; } public function destroy(Webhook $webhook): void @@ -89,14 +90,15 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac ->where('webhook_messages.sent', 0) ->where('webhook_messages.errored', 0) ->get(['webhook_messages.*']) - ->filter(static fn(WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) // @phpstan-ignore-line - ->splice(0, 3); + ->filter(static fn (WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) // @phpstan-ignore-line + ->splice(0, 3) + ; } public function store(array $data): Webhook { - $secret = Str::random(24); - $fullData = [ + $secret = Str::random(24); + $fullData = [ 'user_id' => $this->user->id, 'user_group_id' => $this->user->user_group_id, 'active' => $data['active'] ?? false, @@ -104,11 +106,11 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac // 'trigger' => $data['trigger'], // 'response' => $data['response'], // 'delivery' => $data['delivery'], - 'trigger' => 1, - 'response' => 1, - 'delivery' => 1, - 'secret' => $secret, - 'url' => $data['url'] + 'trigger' => 1, + 'response' => 1, + 'delivery' => 1, + 'secret' => $secret, + 'url' => $data['url'], ]; /** @var Webhook $webhook */ @@ -153,19 +155,19 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac public function update(Webhook $webhook, array $data): Webhook { $webhook->active = $data['active'] ?? $webhook->active; - $webhook->title = $data['title'] ?? $webhook->title; - $webhook->url = $data['url'] ?? $webhook->url; + $webhook->title = $data['title'] ?? $webhook->title; + $webhook->url = $data['url'] ?? $webhook->url; if (array_key_exists('secret', $data) && true === $data['secret']) { - $secret = Str::random(24); + $secret = Str::random(24); $webhook->secret = $secret; } $webhook->save(); - $triggers = new Collection(); - $responses = new Collection(); - $deliveries = new Collection(); + $triggers = new Collection(); + $responses = new Collection(); + $deliveries = new Collection(); foreach ($data['triggers'] as $trigger) { // get the relevant ID: diff --git a/app/Rules/Account/IsValidAccountType.php b/app/Rules/Account/IsValidAccountType.php index e22d8a5951..d2ac0603cf 100644 --- a/app/Rules/Account/IsValidAccountType.php +++ b/app/Rules/Account/IsValidAccountType.php @@ -38,7 +38,7 @@ class IsValidAccountType implements ValidationRule { // only check the type. if (array_key_exists('type', $value)) { - $value = $value['type']; + $value = $value['type']; if (!is_array($value)) { $value = [$value]; } diff --git a/app/Rules/Account/IsValidAccountTypeList.php b/app/Rules/Account/IsValidAccountTypeList.php index 277afab291..d2a8d97c51 100644 --- a/app/Rules/Account/IsValidAccountTypeList.php +++ b/app/Rules/Account/IsValidAccountTypeList.php @@ -44,7 +44,7 @@ class IsValidAccountTypeList implements ValidationRule if (!is_array($values)) { $fail('validation.invalid_account_list')->translate(); } - $keys = array_keys($this->types); + $keys = array_keys($this->types); foreach ($values as $entry) { if (!in_array($entry, $keys, true)) { $fail('validation.invalid_account_list')->translate(['value' => $entry]); diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php index d4ee76ab4e..b0acc68ecd 100644 --- a/app/Rules/BelongsUser.php +++ b/app/Rules/BelongsUser.php @@ -50,17 +50,17 @@ class BelongsUser implements ValidationRule } Log::debug(sprintf('Going to validate %s', $attribute)); - $result = match ($attribute) { - 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), - 'piggy_bank_name' => $this->validatePiggyBankName($value), - 'bill_id' => $this->validateBillId((int) $value), + $result = match ($attribute) { + 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), + 'piggy_bank_name' => $this->validatePiggyBankName($value), + 'bill_id' => $this->validateBillId((int) $value), 'transaction_journal_id' => $this->validateJournalId((int) $value), - 'bill_name' => $this->validateBillName($value), - 'budget_id' => $this->validateBudgetId((int) $value), - 'category_id' => $this->validateCategoryId((int) $value), - 'budget_name' => $this->validateBudgetName($value), + 'bill_name' => $this->validateBillName($value), + 'budget_id' => $this->validateBudgetId((int) $value), + 'category_id' => $this->validateCategoryId((int) $value), + 'budget_name' => $this->validateBudgetName($value), 'source_id', 'destination_id' => $this->validateAccountId((int) $value), - default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) + default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) }; if (false === $result) { $fail('validation.belongs_user')->translate(); @@ -86,7 +86,8 @@ class BelongsUser implements ValidationRule ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('piggy_banks.id', '=', $value) ->where('accounts.user_id', '=', auth()->user()->id) - ->count(); + ->count() + ; return $count > 0; } @@ -97,7 +98,8 @@ class BelongsUser implements ValidationRule ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('piggy_banks.name', '=', $value) ->where('accounts.user_id', '=', auth()->user()->id) - ->count(); + ->count() + ; return $count > 0; } @@ -137,13 +139,13 @@ class BelongsUser implements ValidationRule // get all objects belonging to user: if (PiggyBank::class === $class) { $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', '=', auth()->user()->id)->get([ - 'piggy_banks.*' + 'piggy_banks.*', ]); } if (PiggyBank::class !== $class) { $objects = $class::where('user_id', '=', auth()->user()->id)->get(); } - $count = 0; + $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); diff --git a/app/Rules/BelongsUserGroup.php b/app/Rules/BelongsUserGroup.php index c11615f187..a9c74c0bda 100644 --- a/app/Rules/BelongsUserGroup.php +++ b/app/Rules/BelongsUserGroup.php @@ -61,17 +61,17 @@ class BelongsUserGroup implements ValidationRule } Log::debug(sprintf('Group: Going to validate "%s"', $attribute)); - $result = match ($attribute) { - 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), - 'piggy_bank_name' => $this->validatePiggyBankName($value), - 'bill_id' => $this->validateBillId((int) $value), + $result = match ($attribute) { + 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), + 'piggy_bank_name' => $this->validatePiggyBankName($value), + 'bill_id' => $this->validateBillId((int) $value), 'transaction_journal_id' => $this->validateJournalId((int) $value), - 'bill_name' => $this->validateBillName($value), - 'budget_id' => $this->validateBudgetId((int) $value), - 'category_id' => $this->validateCategoryId((int) $value), - 'budget_name' => $this->validateBudgetName($value), + 'bill_name' => $this->validateBillName($value), + 'budget_id' => $this->validateBudgetId((int) $value), + 'category_id' => $this->validateCategoryId((int) $value), + 'budget_name' => $this->validateBudgetName($value), 'source_id', 'destination_id' => $this->validateAccountId((int) $value), - default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) + default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) }; if (false === $result) { $fail('validation.belongs_user_or_user_group')->translate(); @@ -96,7 +96,8 @@ class BelongsUserGroup implements ValidationRule $count = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id') ->where('piggy_banks.id', '=', $value) ->where('accounts.user_group_id', '=', $this->userGroup->id) - ->count(); + ->count() + ; return 1 === $count; } @@ -123,7 +124,7 @@ class BelongsUserGroup implements ValidationRule if (PiggyBank::class !== $class) { $objects = $class::where('user_group_id', '=', $this->userGroup->id)->get(); } - $count = 0; + $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); diff --git a/app/Rules/IsAssetAccountId.php b/app/Rules/IsAssetAccountId.php index c9497554f9..eadc485442 100644 --- a/app/Rules/IsAssetAccountId.php +++ b/app/Rules/IsAssetAccountId.php @@ -41,7 +41,7 @@ class IsAssetAccountId implements ValidationRule $accountId = (int) $value; /** @var null|Account $account */ - $account = Account::with('accountType')->find($accountId); + $account = Account::with('accountType')->find($accountId); if (null === $account) { $fail('validation.no_asset_account')->translate(); diff --git a/app/Rules/IsDefaultUserGroupName.php b/app/Rules/IsDefaultUserGroupName.php index 8bb4513fe7..9151580e34 100644 --- a/app/Rules/IsDefaultUserGroupName.php +++ b/app/Rules/IsDefaultUserGroupName.php @@ -49,12 +49,12 @@ class IsDefaultUserGroupName implements ValidationRule // are you owner of this group and the name is the same? fail. /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var UserRepositoryInterface $userRepos */ $userRepos = app(UserRepositoryInterface::class); - $roles = $userRepos->getRolesInGroup($user, $this->userGroup->id); + $roles = $userRepos->getRolesInGroup($user, $this->userGroup->id); if ($this->userGroup->title === $user->email && in_array('owner', $roles, true)) { $fail('validation.administration_owner_rename')->translate(); } diff --git a/app/Rules/IsTransferAccount.php b/app/Rules/IsTransferAccount.php index a7abb9dfe5..ce255dc1f3 100644 --- a/app/Rules/IsTransferAccount.php +++ b/app/Rules/IsTransferAccount.php @@ -43,7 +43,7 @@ class IsTransferAccount implements ValidationRule Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value)); /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType(TransactionTypeEnum::TRANSFER->value); $validator->setUser(auth()->user()); diff --git a/app/Rules/IsValidActionExpression.php b/app/Rules/IsValidActionExpression.php index 772af79b46..ef6bc8ed48 100644 --- a/app/Rules/IsValidActionExpression.php +++ b/app/Rules/IsValidActionExpression.php @@ -45,7 +45,7 @@ class IsValidActionExpression implements ValidationRule return; } $value ??= ''; - $expr = new ActionExpression($value); + $expr = new ActionExpression($value); if (!$expr->isValid()) { $fail('validation.rule_action_expression')->translate(['error' => $expr->getValidationError()->getMessage()]); diff --git a/app/Rules/IsValidAmount.php b/app/Rules/IsValidAmount.php index 2d2ec7b2a5..6cc9ad87cd 100644 --- a/app/Rules/IsValidAmount.php +++ b/app/Rules/IsValidAmount.php @@ -72,7 +72,7 @@ class IsValidAmount implements ValidationRule // must be more than minus a lots: if ($this->lessThanLots($value)) { - $amount = bcmul('-1', self::BIG_AMOUNT); + $amount = bcmul('-1', self::BIG_AMOUNT); $fail('validation.gte.numeric')->translate(['value' => $amount]); $message = sprintf('IsValidAmount: "%s" must be more than %s.', $value, $amount); Log::debug($message); diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index 4d8e02ed16..f825bc535a 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -55,7 +55,7 @@ class IsValidAttachmentModel implements ValidationRule */ public function __construct(string $model) { - $model = $this->normalizeModel($model); + $model = $this->normalizeModel($model); $this->model = $model; } @@ -79,15 +79,15 @@ class IsValidAttachmentModel implements ValidationRule return; } $result = match ($this->model) { - Account::class => $this->validateAccount((int) $value), - Bill::class => $this->validateBill((int) $value), - Budget::class => $this->validateBudget((int) $value), - Category::class => $this->validateCategory((int) $value), - PiggyBank::class => $this->validatePiggyBank((int) $value), - Tag::class => $this->validateTag((int) $value), - Transaction::class => $this->validateTransaction((int) $value), + Account::class => $this->validateAccount((int) $value), + Bill::class => $this->validateBill((int) $value), + Budget::class => $this->validateBudget((int) $value), + Category::class => $this->validateCategory((int) $value), + PiggyBank::class => $this->validatePiggyBank((int) $value), + Tag::class => $this->validateTag((int) $value), + Transaction::class => $this->validateTransaction((int) $value), TransactionJournal::class => $this->validateJournal((int) $value), - default => false + default => false }; if (false === $result) { diff --git a/app/Rules/IsValidDateRange.php b/app/Rules/IsValidDateRange.php index ada4f2da62..b50de3f95f 100644 --- a/app/Rules/IsValidDateRange.php +++ b/app/Rules/IsValidDateRange.php @@ -38,13 +38,13 @@ class IsValidDateRange implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - $value = (string) $value; + $value = (string) $value; if ('' === $value) { $fail('validation.date_or_time')->translate(); return; } - $other = 'startPeriod'; + $other = 'startPeriod'; if ('startPeriod' === $attribute) { $other = 'endPeriod'; } diff --git a/app/Rules/IsValidSortInstruction.php b/app/Rules/IsValidSortInstruction.php index 6b2f3a97a2..acc4f1dbde 100644 --- a/app/Rules/IsValidSortInstruction.php +++ b/app/Rules/IsValidSortInstruction.php @@ -35,7 +35,7 @@ class IsValidSortInstruction implements ValidationRule public function validate(string $attribute, mixed $value, Closure $fail): void { - $shortClass = str_replace('FireflyIII\Models\\', '', $this->class); + $shortClass = str_replace('FireflyIII\Models\\', '', $this->class); if (!is_string($value)) { $fail('validation.invalid_sort_instruction')->translate(['object' => $shortClass]); @@ -52,7 +52,7 @@ class IsValidSortInstruction implements ValidationRule return; } - $parts = explode(',', $value); + $parts = explode(',', $value); foreach ($parts as $i => $part) { $part = trim($part); if (strlen($part) < 2) { diff --git a/app/Rules/TransactionType/IsValidTransactionTypeList.php b/app/Rules/TransactionType/IsValidTransactionTypeList.php index 5ec2b6f020..1acf81c4d9 100644 --- a/app/Rules/TransactionType/IsValidTransactionTypeList.php +++ b/app/Rules/TransactionType/IsValidTransactionTypeList.php @@ -44,7 +44,7 @@ class IsValidTransactionTypeList implements ValidationRule if (!is_array($values)) { $fail('validation.invalid_transaction_type_list')->translate(); } - $keys = array_keys($this->transactionTypes); + $keys = array_keys($this->transactionTypes); foreach ($values as $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 66efd637a1..412fba5465 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -42,8 +42,8 @@ class UniqueAccountNumber implements ValidationRule * Create a new rule instance. */ public function __construct( - private readonly null|Account $account, - private null|string $expectedType + private readonly ?Account $account, + private ?string $expectedType ) { app('log')->debug('Constructed UniqueAccountNumber'); // a very basic fix to make sure we get the correct account type: @@ -131,7 +131,8 @@ class UniqueAccountNumber implements ValidationRule ->where('accounts.user_id', auth()->user()->id) ->where('account_types.type', $type) ->where('account_meta.name', '=', 'account_number') - ->where('account_meta.data', json_encode($accountNumber)); + ->where('account_meta.data', json_encode($accountNumber)) + ; if ($this->account instanceof Account) { $query->where('accounts.id', '!=', $this->account->id); diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php index 2ecb51648f..4df6c9de58 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -42,8 +42,8 @@ class UniqueIban implements ValidationRule * Create a new rule instance. */ public function __construct( - private readonly null|Account $account, - null|string $expectedType + private readonly ?Account $account, + ?string $expectedType ) { if (null === $expectedType) { return; @@ -129,7 +129,7 @@ class UniqueIban implements ValidationRule AccountTypeEnum::ASSET->value => 0, AccountTypeEnum::EXPENSE->value => 0, AccountTypeEnum::REVENUE->value => 0, - 'liabilities' => 0 + 'liabilities' => 0, ]; if (in_array('expense', $this->expectedTypes, true) || in_array(AccountTypeEnum::EXPENSE->value, $this->expectedTypes, true)) { @@ -152,12 +152,13 @@ class UniqueIban implements ValidationRule if ('liabilities' === $type) { $typesArray = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; } - $query = auth() + $query = auth() ->user() ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->where('accounts.iban', $iban) - ->whereIn('account_types.type', $typesArray); + ->whereIn('account_types.type', $typesArray) + ; if ($this->account instanceof Account) { $query->where('accounts.id', '!=', $this->account->id); diff --git a/app/Rules/ValidRecurrenceRepetitionValue.php b/app/Rules/ValidRecurrenceRepetitionValue.php index 07c504c3b0..1df3b307e4 100644 --- a/app/Rules/ValidRecurrenceRepetitionValue.php +++ b/app/Rules/ValidRecurrenceRepetitionValue.php @@ -82,8 +82,8 @@ class ValidRecurrenceRepetitionValue implements ValidationRule if (2 !== count($parameters)) { return false; } - $nthDay = (int) $parameters[0]; - $dayOfWeek = (int) $parameters[1]; + $nthDay = (int) $parameters[0]; + $dayOfWeek = (int) $parameters[1]; if ($nthDay < 1 || $nthDay > 5) { return false; } diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index ab3f7da296..0f5b694c69 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -47,7 +47,7 @@ class UpdateRequest implements UpdateRequestInterface $information = ['level' => 'error', 'message' => (string) trans('firefly.unknown_error')]; // try to get array from update server: - $updateInfo = $this->contactServer($channel); + $updateInfo = $this->contactServer($channel); if ('error' === $updateInfo['level']) { Log::error('Update information contains an error.'); Log::error($updateInfo['message']); @@ -64,14 +64,14 @@ class UpdateRequest implements UpdateRequestInterface { Log::debug(sprintf('Now in contactServer(%s)', $channel)); // always fall back to current version: - $return = [ + $return = [ 'version' => config('firefly.version'), 'date' => today(config('app.timezone'))->startOfDay(), 'level' => 'error', - 'message' => (string) trans('firefly.unknown_error') + 'message' => (string) trans('firefly.unknown_error'), ]; - $url = config('firefly.update_endpoint'); + $url = config('firefly.update_endpoint'); Log::debug(sprintf('Going to call %s', $url)); try { @@ -94,7 +94,7 @@ class UpdateRequest implements UpdateRequestInterface return $return; } - $body = (string) $res->getBody(); + $body = (string) $res->getBody(); try { $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); @@ -113,14 +113,14 @@ class UpdateRequest implements UpdateRequestInterface } // parse response a bit. No message yet. - $response = $json['firefly_iii'][$channel]; - $date = Carbon::createFromFormat('Y-m-d', $response['date']); + $response = $json['firefly_iii'][$channel]; + $date = Carbon::createFromFormat('Y-m-d', $response['date']); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $return['version'] = $response['version']; - $return['level'] = 'success'; - $return['date'] = $date->startOfDay(); + $return['level'] = 'success'; + $return['date'] = $date->startOfDay(); Log::info('Response from update server', $response); @@ -133,8 +133,8 @@ class UpdateRequest implements UpdateRequestInterface private function parseResult(array $information): array { Log::debug('Now in parseResult()', $information); - $current = (string) config('firefly.version'); - $latest = (string) $information['version']; + $current = (string) config('firefly.version'); + $latest = (string) $information['version']; // strip the 'v' from the version if it's there. if (str_starts_with($latest, 'v')) { @@ -144,7 +144,7 @@ class UpdateRequest implements UpdateRequestInterface return $this->parseResultDevelop($current, $latest); } - $compare = version_compare($latest, $current); + $compare = version_compare($latest, $current); Log::debug(sprintf('Current version is "%s", latest is "%s", result is: %d', $current, $latest, $compare)); @@ -178,16 +178,16 @@ class UpdateRequest implements UpdateRequestInterface private function parseResultDevelop(string $current, string $latest): array { Log::debug(sprintf('User is running develop version "%s"', $current)); - $compare = $this->compareDevelopVersions($current, $latest); - $return = []; + $compare = $this->compareDevelopVersions($current, $latest); + $return = []; if (-1 === $compare) { - $return['level'] = 'info'; + $return['level'] = 'info'; $return['message'] = (string) trans('firefly.update_current_dev_older', ['version' => $current, 'new_version' => $latest]); return $return; } - $return['level'] = 'info'; + $return['level'] = 'info'; $return['message'] = (string) trans('firefly.update_current_dev_newer', ['version' => $current, 'new_version' => $latest]); return $return; @@ -197,7 +197,7 @@ class UpdateRequest implements UpdateRequestInterface { $return = [ 'level' => 'info', - 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]) + 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]), ]; Log::debug('User is running a newer version', $return); @@ -218,7 +218,7 @@ class UpdateRequest implements UpdateRequestInterface $message = (string) trans('firefly.update_new_version_alert', [ 'your_version' => $current, 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), ]); return ['level' => 'success', 'message' => sprintf('%s %s', $message, trans('firefly.update_version_alpha'))]; @@ -230,7 +230,7 @@ class UpdateRequest implements UpdateRequestInterface $message = (string) trans('firefly.update_new_version_alert', [ 'your_version' => $current, 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), ]); return ['level' => 'success', 'message' => sprintf('%s %s', $message, trans('firefly.update_version_beta'))]; @@ -242,7 +242,7 @@ class UpdateRequest implements UpdateRequestInterface $message = (string) trans('firefly.update_new_version_alert', [ 'your_version' => $current, 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), ]); Log::debug('New release is here!', [$message]); event(new SystemFoundNewVersionOnline($message)); diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index 9fa2d41032..d17542f220 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -40,7 +40,7 @@ use stdClass; */ class AccountDestroyService { - public function destroy(Account $account, null|Account $moveTo): void + public function destroy(Account $account, ?Account $moveTo): void { // find and delete opening balance journal + opposing account $this->destroyOpeningBalance($account); @@ -72,9 +72,10 @@ class AccountDestroyService ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value) - ->get(['transactions.transaction_journal_id']); + ->get(['transactions.transaction_journal_id']) + ; if ($set->count() > 0) { - $journalId = $set->first()->transaction_journal_id; + $journalId = $set->first()->transaction_journal_id; Log::debug(sprintf('Found opening balance journal with ID #%d', $journalId)); // get transactions with this journal (should be just one): @@ -92,7 +93,7 @@ class AccountDestroyService } /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($journalId); + $journal = TransactionJournal::find($journalId); if (null !== $journal) { /** @var JournalDestroyService $service */ $service = app(JournalDestroyService::class); @@ -109,15 +110,15 @@ class AccountDestroyService $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') + DB::raw('count(*) as the_count'), ]); if (0 === $collection->count()) { return; } /** @var JournalDestroyService $service */ - $service = app(JournalDestroyService::class); - $user = $account->user; + $service = app(JournalDestroyService::class); + $user = $account->user; /** @var stdClass $row */ foreach ($collection as $row) { @@ -140,7 +141,7 @@ class AccountDestroyService private function destroyRecurrences(Account $account): void { - $recurrences = RecurrenceTransaction::where(static function (Builder $q) use ($account): void { + $recurrences = RecurrenceTransaction::where(static function (Builder $q) use ($account): void { $q->where('source_id', $account->id); $q->orWhere('destination_id', $account->id); })->get(['recurrence_id'])->pluck('recurrence_id')->toArray(); diff --git a/app/Services/Internal/Destroy/CategoryDestroyService.php b/app/Services/Internal/Destroy/CategoryDestroyService.php index 55e3d97292..8c9680c04d 100644 --- a/app/Services/Internal/Destroy/CategoryDestroyService.php +++ b/app/Services/Internal/Destroy/CategoryDestroyService.php @@ -46,6 +46,7 @@ class CategoryDestroyService DB::table('rt_meta') ->where('name', 'category_id') ->where('value', $category->id) - ->delete(); + ->delete() + ; } } diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index 6bdaecadd8..de50f81f5f 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -53,7 +53,7 @@ trait AccountServiceTrait { protected AccountRepositoryInterface $accountRepository; - public function filterIban(null|string $iban): null|string + public function filterIban(?string $iban): ?string { if (null === $iban) { return null; @@ -81,12 +81,11 @@ trait AccountServiceTrait } // if is set, but is empty: - return ( + return array_key_exists('opening_balance', $data) && '' === $data['opening_balance'] || array_key_exists('opening_balance_date', $data) - && '' === $data['opening_balance_date'] - ); + && '' === $data['opening_balance_date']; } /** @@ -98,14 +97,14 @@ trait AccountServiceTrait */ public function updateMetaData(Account $account, array $data): void { - $fields = $this->validFields; + $fields = $this->validFields; if (AccountTypeEnum::ASSET->value === $account->accountType->type) { $fields = $this->validAssetFields; } // remove currency_id if necessary. - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); if (!in_array($type, $list, true)) { $pos = array_search('currency_id', $fields, true); if (false !== $pos) { @@ -154,7 +153,7 @@ trait AccountServiceTrait public function updateNote(Account $account, string $note): bool { - $dbNote = $account->notes()->first(); + $dbNote = $account->notes()->first(); if ('' === $note) { $dbNote?->delete(); @@ -202,7 +201,7 @@ trait AccountServiceTrait protected function createOBGroup(Account $account, array $data): TransactionGroup { Log::debug('Now going to create an OB group.'); - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } @@ -233,10 +232,10 @@ trait AccountServiceTrait } // make amount positive, regardless: - $amount = Steam::positive($amount); + $amount = Steam::positive($amount); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -268,13 +267,13 @@ trait AccountServiceTrait 'piggy_bank_name' => null, 'reconciled' => false, 'notes' => null, - 'tags' => [] - ]] + 'tags' => [], + ]], ]; Log::debug('Going for submission in createOBGroup', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { @@ -309,7 +308,7 @@ trait AccountServiceTrait /** * Returns the credit transaction group, or NULL if it does not exist. */ - protected function getCreditTransaction(Account $account): null|TransactionGroup + protected function getCreditTransaction(Account $account): ?TransactionGroup { Log::debug(sprintf('Now at %s', __METHOD__)); @@ -337,7 +336,7 @@ trait AccountServiceTrait /** * Returns the opening balance group, or NULL if it does not exist. */ - protected function getOBGroup(Account $account): null|TransactionGroup + protected function getOBGroup(Account $account): ?TransactionGroup { return $this->accountRepository->getOpeningBalanceGroup($account); } @@ -346,10 +345,10 @@ trait AccountServiceTrait { // find currency, or use default currency instead. /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); + $factory = app(TransactionCurrencyFactory::class); /** @var null|TransactionCurrency $currency */ - $currency = $factory->find($currencyId, $currencyCode); + $currency = $factory->find($currencyId, $currencyCode); if (null === $currency) { // use default currency: @@ -377,7 +376,7 @@ trait AccountServiceTrait } // if direction is "debit" (I owe this debt), amount is negative. // which means the liability will have a negative balance which the user must fill. - $openingBalance = Steam::negative($openingBalance); + $openingBalance = Steam::negative($openingBalance); // if direction is "credit" (I am owed this debt), amount is positive. // which means the liability will have a positive balance which is drained when its paid back into any asset. @@ -386,30 +385,30 @@ trait AccountServiceTrait } // create if not exists: - $clGroup = $this->getCreditTransaction($account); + $clGroup = $this->getCreditTransaction($account); if (null === $clGroup) { return $this->createCreditTransaction($account, $openingBalance, $openingBalanceDate); } // if exists, update: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } // simply grab the first journal and change it: - $journal = $this->getObJournal($clGroup); - $clTransaction = $this->getOBTransaction($journal, $account); - $accountTransaction = $this->getNotOBTransaction($journal, $account); - $journal->date = $openingBalanceDate; + $journal = $this->getObJournal($clGroup); + $clTransaction = $this->getOBTransaction($journal, $account); + $accountTransaction = $this->getNotOBTransaction($journal, $account); + $journal->date = $openingBalanceDate; $journal->transactionCurrency()->associate($currency); // account always gains money: - $accountTransaction->amount = Steam::positive($openingBalance); + $accountTransaction->amount = Steam::positive($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // CL account always loses money: - $clTransaction->amount = Steam::negative($openingBalance); - $clTransaction->transaction_currency_id = $currency->id; + $clTransaction->amount = Steam::negative($openingBalance); + $clTransaction->transaction_currency_id = $currency->id; // save both $accountTransaction->save(); $clTransaction->save(); @@ -432,11 +431,11 @@ trait AccountServiceTrait throw new FireflyException('Amount for new liability credit was unexpectedly 0.'); } - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } - $language = (string) $language; + $language = (string) $language; // set source and/or destination based on whether the amount is positive or negative. // first, assume the amount is positive and go from there: @@ -454,10 +453,10 @@ trait AccountServiceTrait } // amount must be positive for the transaction to work. - $amount = Steam::positive($openingBalance); + $amount = Steam::positive($openingBalance); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -488,13 +487,13 @@ trait AccountServiceTrait 'piggy_bank_name' => null, 'reconciled' => false, 'notes' => null, - 'tags' => [] - ]] + 'tags' => [], + ]], ]; Log::debug('Going for submission in createCreditTransaction', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { @@ -565,14 +564,14 @@ trait AccountServiceTrait { Log::debug(sprintf('Now in %s', __METHOD__)); // create if not exists: - $obGroup = $this->getOBGroup($account); + $obGroup = $this->getOBGroup($account); if (null === $obGroup) { return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate); } Log::debug('Update OB group'); // if exists, update: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -581,29 +580,29 @@ trait AccountServiceTrait $journal = $this->getObJournal($obGroup); $obTransaction = $this->getOBTransaction($journal, $account); $accountTransaction = $this->getNotOBTransaction($journal, $account); - $journal->date = $openingBalanceDate; + $journal->date = $openingBalanceDate; $journal->transactionCurrency()->associate($currency); // if amount is negative: if (1 === bccomp('0', $openingBalance)) { Log::debug('Amount is negative.'); // account transaction loses money: - $accountTransaction->amount = Steam::negative($openingBalance); + $accountTransaction->amount = Steam::negative($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // OB account transaction gains money - $obTransaction->amount = Steam::positive($openingBalance); - $obTransaction->transaction_currency_id = $currency->id; + $obTransaction->amount = Steam::positive($openingBalance); + $obTransaction->transaction_currency_id = $currency->id; } if (-1 === bccomp('0', $openingBalance)) { Log::debug('Amount is positive.'); // account gains money: - $accountTransaction->amount = Steam::positive($openingBalance); + $accountTransaction->amount = Steam::positive($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // OB account loses money: - $obTransaction->amount = Steam::negative($openingBalance); - $obTransaction->transaction_currency_id = $currency->id; + $obTransaction->amount = Steam::negative($openingBalance); + $obTransaction->transaction_currency_id = $currency->id; } // save both $accountTransaction->save(); @@ -620,7 +619,7 @@ trait AccountServiceTrait protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { Log::debug('Now going to create an OB group.'); - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } @@ -650,10 +649,10 @@ trait AccountServiceTrait } // make amount positive, regardless: - $amount = Steam::positive($openingBalance); + $amount = Steam::positive($openingBalance); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -685,13 +684,13 @@ trait AccountServiceTrait 'piggy_bank_name' => null, 'reconciled' => false, 'notes' => null, - 'tags' => [] - ]] + 'tags' => [], + ]], ]; Log::debug('Going for submission in createOBGroupV2', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { diff --git a/app/Services/Internal/Support/BillServiceTrait.php b/app/Services/Internal/Support/BillServiceTrait.php index 16c7389096..58907377f9 100644 --- a/app/Services/Internal/Support/BillServiceTrait.php +++ b/app/Services/Internal/Support/BillServiceTrait.php @@ -43,7 +43,8 @@ trait BillServiceTrait $set = RuleAction::whereIn('rule_id', $ruleIds) ->where('action_type', 'link_to_bill') ->where('action_value', $oldName) - ->get(); + ->get() + ; /** @var RuleAction $ruleAction */ foreach ($set as $ruleAction) { @@ -61,7 +62,7 @@ trait BillServiceTrait return true; } - $dbNote = $bill->notes()->first(); + $dbNote = $bill->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($bill); diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php index 2ec39113b4..50290f81b3 100644 --- a/app/Services/Internal/Support/CreditRecalculateService.php +++ b/app/Services/Internal/Support/CreditRecalculateService.php @@ -41,10 +41,10 @@ use Illuminate\Support\Facades\Log; */ class CreditRecalculateService { - private null|Account $account = null; - private null|TransactionGroup $group = null; + private ?Account $account = null; + private ?TransactionGroup $group = null; private AccountRepositoryInterface $repository; - private array $work = []; + private array $work = []; public function recalculate(): void { @@ -86,7 +86,7 @@ class CreditRecalculateService $destination = $this->getDestinationAccount($journal); // destination or source must be liability. - $valid = config('firefly.valid_liabilities'); + $valid = config('firefly.valid_liabilities'); if (in_array($destination->accountType->type, $valid, true)) { $this->work[] = $destination; } @@ -109,7 +109,7 @@ class CreditRecalculateService private function getAccountByDirection(TransactionJournal $journal, string $direction): Account { /** @var null|Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', $direction, '0')->first(); + $transaction = $journal->transactions()->where('amount', $direction, '0')->first(); if (null === $transaction) { throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id)); } @@ -159,12 +159,12 @@ class CreditRecalculateService if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) { $this->validateOpeningBalance($account, $openingBalance); } - $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; - $leftOfDebt = Steam::positive($startOfDebt); + $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; + $leftOfDebt = Steam::positive($startOfDebt); // Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', \FireflyIII\Support\Facades\Steam::bcround($startOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2))); /** @var AccountMetaFactory $factory */ - $factory = app(AccountMetaFactory::class); + $factory = app(AccountMetaFactory::class); // amount is positive or negative, doesn't matter. $factory->crud($account, 'start_of_debt', $startOfDebt); @@ -172,11 +172,12 @@ class CreditRecalculateService // Log::debug(sprintf('Debt direction is "%s"', $direction)); // now loop all transactions (except opening balance and credit thing) - $transactions = $account + $transactions = $account ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->orderBy('transaction_journals.date', 'ASC') - ->get(['transactions.*']); + ->get(['transactions.*']) + ; $transactions->count(); // Log::debug(sprintf('Found %d transaction(s) to process.', $total)); @@ -198,13 +199,13 @@ class CreditRecalculateService $source = $openingBalance->transactions()->where('amount', '<', 0)->first(); /** @var Transaction $dest */ - $dest = $openingBalance->transactions()->where('amount', '>', 0)->first(); + $dest = $openingBalance->transactions()->where('amount', '>', 0)->first(); if ($source->account_id !== $account->id) { Log::info(sprintf('Liability #%d has a reversed opening balance. Will fix this now.', $account->id)); Log::debug(sprintf('Source amount "%s" is now "%s"', $source->amount, Steam::positive($source->amount))); Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->amount, Steam::negative($dest->amount))); $source->amount = Steam::positive($source->amount); - $dest->amount = Steam::negative($source->amount); + $dest->amount = Steam::negative($source->amount); if (null !== $source->foreign_amount && '' !== $source->foreign_amount) { $source->foreign_amount = Steam::positive($source->foreign_amount); Log::debug(sprintf('Source foreign amount "%s" is now "%s"', $source->foreign_amount, Steam::positive($source->foreign_amount))); @@ -229,7 +230,7 @@ class CreditRecalculateService */ private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string { - $journal = $transaction->transactionJournal; + $journal = $transaction->transactionJournal; // here be null pointers. if (null === $journal) { @@ -256,10 +257,10 @@ class CreditRecalculateService // Log::debug(sprintf('Liability direction is "%s"', $direction)); // amount to use depends on the currency: - $usedAmount = $this->getAmountToUse($transaction, $accountCurrency, $foreignCurrency); - $isSameAccount = $account->id === $transaction->account_id; - $isDebit = 'debit' === $direction; - $isCredit = 'credit' === $direction; + $usedAmount = $this->getAmountToUse($transaction, $accountCurrency, $foreignCurrency); + $isSameAccount = $account->id === $transaction->account_id; + $isDebit = 'debit' === $direction; + $isCredit = 'credit' === $direction; if ($isSameAccount && $isCredit && $this->isWithdrawalIn($usedAmount, $type)) { // case 1 $usedAmount = Steam::positive($usedAmount); @@ -352,7 +353,7 @@ class CreditRecalculateService return $leftOfDebt; } - private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, null|TransactionCurrency $foreignCurrency): string + private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, ?TransactionCurrency $foreignCurrency): string { $usedAmount = $transaction->amount; // Log::debug(sprintf('Amount of transaction is %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2))); @@ -450,7 +451,7 @@ class CreditRecalculateService return TransactionTypeEnum::TRANSFER->value === $transactionType && -1 === bccomp($amount, '0'); } - public function setAccount(null|Account $account): void + public function setAccount(?Account $account): void { $this->account = $account; } diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index 5039387026..0566be1ce1 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -55,7 +55,7 @@ trait JournalServiceTrait /** * @throws FireflyException */ - protected function getAccount(string $transactionType, string $direction, array $data, null|Account $opposite = null): null|Account + protected function getAccount(string $transactionType, string $direction, array $data, ?Account $opposite = null): ?Account { // some debug logging: Log::debug(sprintf('Now in getAccount(%s)', $direction), $data); @@ -67,23 +67,23 @@ trait JournalServiceTrait unset($array); // and now try to find it, based on the type of transaction. - $message = 'Transaction = %s, %s account should be in: %s. Direction is %s.'; + $message = 'Transaction = %s, %s account should be in: %s. Direction is %s.'; Log::debug(sprintf($message, $transactionType, $direction, implode(', ', $expectedTypes[$transactionType] ?? ['UNKNOWN']), $direction)); - $result = $this->findAccountById($data, $expectedTypes[$transactionType], $opposite); - $result = $this->findAccountByIban($result, $data, $expectedTypes[$transactionType], $opposite); - $ibanResult = $result; - $result = $this->findAccountByNumber($result, $data, $expectedTypes[$transactionType], $opposite); - $numberResult = $result; - $result = $this->findAccountByName($result, $data, $expectedTypes[$transactionType], $opposite); - $nameResult = $result; + $result = $this->findAccountById($data, $expectedTypes[$transactionType], $opposite); + $result = $this->findAccountByIban($result, $data, $expectedTypes[$transactionType], $opposite); + $ibanResult = $result; + $result = $this->findAccountByNumber($result, $data, $expectedTypes[$transactionType], $opposite); + $numberResult = $result; + $result = $this->findAccountByName($result, $data, $expectedTypes[$transactionType], $opposite); + $nameResult = $result; // if $result (find by name) is NULL, but IBAN is set, any result of the search by NAME can't overrule // this account. In such a case, the name search must be retried with a new name. if (null !== $nameResult && null === $numberResult && null === $ibanResult && '' !== (string) $data['iban'] && '' !== (string) $nameResult->iban) { $data['name'] = sprintf('%s (%s)', $data['name'], $data['iban']); Log::debug(sprintf('Search again using the new name, "%s".', $data['name'])); - $result = $this->findAccountByName(null, $data, $expectedTypes[$transactionType], $opposite); + $result = $this->findAccountByName(null, $data, $expectedTypes[$transactionType], $opposite); } // the account that Firefly III creates must be "creatable", aka select the one we can create from the list just in case @@ -112,7 +112,7 @@ trait JournalServiceTrait return $result; } - private function findAccountById(array $data, array $types, null|Account $opposite = null): null|Account + private function findAccountById(array $data, array $types, ?Account $opposite = null): ?Account { // first attempt, find by ID. if (null !== $data['id']) { @@ -139,7 +139,7 @@ trait JournalServiceTrait return null; } - private function findAccountByIban(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account + private function findAccountByIban(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -172,7 +172,7 @@ trait JournalServiceTrait return null; } - private function findAccountByNumber(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account + private function findAccountByNumber(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -207,7 +207,7 @@ trait JournalServiceTrait return null; } - private function findAccountByName(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account + private function findAccountByName(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -244,7 +244,7 @@ trait JournalServiceTrait return null; } - private function getCreatableType(array $types): null|string + private function getCreatableType(array $types): ?string { $result = null; $list = config('firefly.dynamic_creation_allowed'); @@ -265,7 +265,7 @@ trait JournalServiceTrait * @throws FireflyException * @throws JsonException */ - private function createAccount(null|Account $account, array $data, string $preferredType): null|Account + private function createAccount(?Account $account, array $data, string $preferredType): ?Account { Log::debug('Now in createAccount()', $data); // return new account. @@ -302,7 +302,7 @@ trait JournalServiceTrait // $data['name'] = $data['name'] ?? '(no name)'; - $account = $this->accountRepository->store([ + $account = $this->accountRepository->store([ 'account_type_id' => null, 'account_type_name' => $preferredType, 'name' => $data['name'], @@ -310,7 +310,7 @@ trait JournalServiceTrait 'active' => true, 'iban' => $data['iban'], 'currency_id' => $data['currency_id'] ?? null, - 'order' => $this->accountRepository->maxOrder($preferredType) + 'order' => $this->accountRepository->maxOrder($preferredType), ]); // store BIC if (null !== $data['bic']) { @@ -329,7 +329,7 @@ trait JournalServiceTrait return $account; } - private function getCashAccount(null|Account $account, array $data, array $types): null|Account + private function getCashAccount(?Account $account, array $data, array $types): ?Account { // return cash account. if (!$account instanceof Account && '' === (string) $data['name'] && in_array(AccountTypeEnum::CASH->value, $types, true)) { @@ -356,7 +356,7 @@ trait JournalServiceTrait return $amount; } - protected function getForeignAmount(null|string $amount): null|string + protected function getForeignAmount(?string $amount): ?string { if (null === $amount) { Log::debug('No foreign amount info in array. Return NULL'); @@ -409,7 +409,7 @@ trait JournalServiceTrait $journal->categories()->sync([]); } - protected function storeNotes(TransactionJournal $journal, null|string $notes): void + protected function storeNotes(TransactionJournal $journal, ?string $notes): void { $notes = (string) $notes; $note = $journal->notes()->first(); @@ -431,7 +431,7 @@ trait JournalServiceTrait /** * Link tags to journal. */ - protected function storeTags(TransactionJournal $journal, null|array $tags): void + protected function storeTags(TransactionJournal $journal, ?array $tags): void { Log::debug('Now in storeTags()', $tags ?? []); $this->tagFactory->setUser($journal->user); diff --git a/app/Services/Internal/Support/LocationServiceTrait.php b/app/Services/Internal/Support/LocationServiceTrait.php index 06338d9662..38b63f963d 100644 --- a/app/Services/Internal/Support/LocationServiceTrait.php +++ b/app/Services/Internal/Support/LocationServiceTrait.php @@ -32,13 +32,13 @@ use Illuminate\Database\Eloquent\Model; */ trait LocationServiceTrait { - protected function storeNewLocation(Model $model, array $data): null|Location + protected function storeNewLocation(Model $model, array $data): ?Location { $data['store_location'] ??= false; if ($data['store_location']) { - $location = new Location(); - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location = new Location(); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->locatable()->associate($model); $location->save(); diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index c6c2b87dd8..e9fd511ba9 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -59,7 +59,7 @@ trait RecurringTransactionTrait return true; } - $dbNote = $recurrence->notes()->first(); + $dbNote = $recurrence->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($recurrence); @@ -79,7 +79,7 @@ trait RecurringTransactionTrait 'repetition_type' => $array['type'], 'repetition_moment' => $array['moment'] ?? '', 'repetition_skip' => $array['skip'] ?? 0, - 'weekend' => $array['weekend'] ?? 1 + 'weekend' => $array['weekend'] ?? 1, ]); } } @@ -96,10 +96,10 @@ trait RecurringTransactionTrait Log::debug('Now in createTransactions()'); foreach ($transactions as $index => $array) { 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); - $destination = $this->findAccount($destTypes, $array['destination_id'], null); + $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); + $destination = $this->findAccount($destTypes, $array['destination_id'], null); /** @var TransactionCurrencyFactory $factory */ $factory = app(TransactionCurrencyFactory::class); @@ -117,7 +117,7 @@ trait RecurringTransactionTrait // once the accounts have been determined, we still verify their validity: /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setUser($recurrence->user); $validator->setTransactionType($recurrence->transactionType->type); @@ -132,7 +132,7 @@ trait RecurringTransactionTrait unset($array['foreign_amount']); } // TODO typeOverrule. The account validator may have a different opinion on the type of the transaction. - $transaction = new RecurrenceTransaction([ + $transaction = new RecurrenceTransaction([ 'recurrence_id' => $recurrence->id, 'transaction_currency_id' => $currency->id, 'foreign_currency_id' => $foreignCurrency?->id, @@ -140,7 +140,7 @@ trait RecurringTransactionTrait 'destination_id' => $destination->id, 'amount' => $array['amount'], 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string) $array['foreign_amount'] : null, - 'description' => $array['description'] + 'description' => $array['description'], ]); $transaction->save(); @@ -165,24 +165,24 @@ trait RecurringTransactionTrait } } - protected function findAccount(array $expectedTypes, null|int $accountId, null|string $accountName): Account + protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account { - $result = null; - $accountId = (int) $accountId; - $accountName = (string) $accountName; + $result = null; + $accountId = (int) $accountId; + $accountName = (string) $accountName; /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); // if user has submitted an account ID, search for it. - $result = $repository->find($accountId); + $result = $repository->find($accountId); if (null !== $result) { return $result; } // if user has submitted a name, search for it: - $result = $repository->findByName($accountName, $expectedTypes); + $result = $repository->findByName($accountName, $expectedTypes); if (null !== $result) { return $result; } @@ -193,11 +193,11 @@ trait RecurringTransactionTrait AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value + AccountTypeEnum::CREDITCARD->value, ]; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($this->user); /** @var string $expectedType */ @@ -222,7 +222,7 @@ trait RecurringTransactionTrait Log::debug(sprintf('Now in %s', __METHOD__)); $budgetFactory = app(BudgetFactory::class); $budgetFactory->setUser($transaction->recurrence->user); - $budget = $budgetFactory->find($budgetId, null); + $budget = $budgetFactory->find($budgetId, null); if (null === $budget) { // remove budget from recurring transaction: $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->delete(); @@ -230,13 +230,13 @@ trait RecurringTransactionTrait return; } - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'budget_id'; + $meta->name = 'budget_id'; } - $meta->value = $budget->id; + $meta->value = $budget->id; $meta->save(); } @@ -244,7 +244,7 @@ trait RecurringTransactionTrait { $billFactory = app(BillFactory::class); $billFactory->setUser($transaction->recurrence->user); - $bill = $billFactory->find($billId, null); + $bill = $billFactory->find($billId, null); if (null === $bill) { // remove bill from recurring transaction: $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->delete(); @@ -252,11 +252,11 @@ trait RecurringTransactionTrait return; } - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'bill_id'; + $meta->name = 'bill_id'; } $meta->value = $bill->id; $meta->save(); @@ -266,7 +266,7 @@ trait RecurringTransactionTrait { $categoryFactory = app(CategoryFactory::class); $categoryFactory->setUser($transaction->recurrence->user); - $category = $categoryFactory->findOrCreate($categoryId, null); + $category = $categoryFactory->findOrCreate($categoryId, null); if (null === $category) { // remove category: $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->delete(); @@ -275,25 +275,25 @@ trait RecurringTransactionTrait return; } $transaction->recurrenceTransactionMeta()->where('name', 'category_name')->delete(); - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'category_id'; + $meta->name = 'category_id'; } - $meta->value = $category->id; + $meta->value = $category->id; $meta->save(); } protected function updatePiggyBank(RecurrenceTransaction $transaction, int $piggyId): void { /** @var PiggyBankFactory $factory */ - $factory = app(PiggyBankFactory::class); + $factory = app(PiggyBankFactory::class); $factory->user = $transaction->recurrence->user; - $piggyBank = $factory->find($piggyId, null); + $piggyBank = $factory->find($piggyId, null); if (null !== $piggyBank) { /** @var null|RecurrenceMeta $entry */ - $entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first(); + $entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first(); if (null === $entry) { $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]); } @@ -310,7 +310,7 @@ trait RecurringTransactionTrait { if (0 !== count($tags)) { /** @var null|RecurrenceMeta $entry */ - $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); + $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); if (null === $entry) { $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]); } diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index 81c74fde67..b8bed0cfaf 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -58,10 +58,10 @@ class AccountUpdateService public function __construct() { $this->canHaveOpeningBalance = config('firefly.can_have_opening_balance'); - $this->validAssetFields = config('firefly.valid_asset_fields'); - $this->validCCFields = config('firefly.valid_cc_fields'); - $this->validFields = config('firefly.valid_account_fields'); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); + $this->accountRepository = app(AccountRepositoryInterface::class); } /** @@ -74,12 +74,12 @@ class AccountUpdateService Log::debug(sprintf('Now in %s', __METHOD__)); $this->accountRepository->setUser($account->user); $this->user = $account->user; - $account = $this->updateAccount($account, $data); - $account = $this->updateAccountOrder($account, $data); + $account = $this->updateAccount($account, $data); + $account = $this->updateAccountOrder($account, $data); // find currency, or use default currency instead. if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { - $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); + $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); unset($data['currency_code'], $data['currency_id']); $data['currency_id'] = $currency->id; } @@ -130,7 +130,7 @@ class AccountUpdateService // set liability, but account must already be a liability. // $liabilityType = $data['liability_type'] ?? ''; if ($this->isLiability($account) && array_key_exists('liability_type', $data)) { - $type = $this->getAccountType($data['liability_type']); + $type = $this->getAccountType($data['liability_type']); $account->account_type_id = $type->id; } // set liability, alternative method used in v1 layout: @@ -174,7 +174,7 @@ class AccountUpdateService return $account; } // skip if not of orderable type. - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array( $type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], @@ -185,10 +185,10 @@ class AccountUpdateService return $account; } // get account type ID's because a join and an update is hard: - $oldOrder = $account->order; - $newOrder = $data['order']; + $oldOrder = $account->order; + $newOrder = $data['order']; 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]); + $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]); if (AccountTypeEnum::ASSET->value === $type) { $list = $this->getTypeIds([AccountTypeEnum::ASSET->value]); } @@ -200,7 +200,8 @@ class AccountUpdateService ->where('accounts.order', '>', $oldOrder) ->where('accounts.id', '!=', $account->id) ->whereIn('accounts.account_type_id', $list) - ->decrement('order'); + ->decrement('order') + ; $account->order = $newOrder; Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); @@ -214,7 +215,8 @@ class AccountUpdateService ->where('accounts.order', '<', $oldOrder) ->where('accounts.id', '!=', $account->id) ->whereIn('accounts.account_type_id', $list) - ->increment('order'); + ->increment('order') + ; $account->order = $newOrder; Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); @@ -229,7 +231,7 @@ class AccountUpdateService /** @var string $type */ foreach ($array as $type) { /** @var AccountType $type */ - $type = AccountType::whereType($type)->first(); + $type = AccountType::whereType($type)->first(); $return[] = $type->id; } @@ -248,14 +250,14 @@ class AccountUpdateService // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { - $location = $this->accountRepository->getLocation($account); + $location = $this->accountRepository->getLocation($account); if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($account); } - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->save(); } @@ -299,11 +301,11 @@ class AccountUpdateService if (true === $account->active) { return; } - $preference = Preferences::getForUser($account->user, 'frontpageAccounts'); + $preference = Preferences::getForUser($account->user, 'frontpageAccounts'); if (null === $preference) { return; } - $array = $preference->data; + $array = $preference->data; if (!is_array($array)) { $array = [$array]; } diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index 2c70f7f5fb..97c2e5f803 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -52,28 +52,28 @@ class BillUpdateService $this->user = $bill->user; if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find( + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find( (int) ($data['currency_id'] ?? null), $data['currency_code'] ?? null ) ?? Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); // enable the currency if it isn't. - $currency->enabled = true; + $currency->enabled = true; $currency->save(); $bill->transaction_currency_id = $currency->id; $bill->save(); } // update bill properties: - $bill = $this->updateBillProperties($bill, $data); + $bill = $this->updateBillProperties($bill, $data); $bill->save(); $bill->refresh(); // old values - $oldData = [ + $oldData = [ 'name' => $bill->name, 'amount_min' => $bill->amount_min, 'amount_max' => $bill->amount_max, - 'transaction_currency_name' => $bill->transactionCurrency->name + 'transaction_currency_name' => $bill->transactionCurrency->name, ]; // update note: if (array_key_exists('notes', $data)) { @@ -147,7 +147,7 @@ class BillUpdateService $bill->amount_max = $data['amount_max']; } if (array_key_exists('date', $data) && '' !== (string) $data['date']) { - $bill->date = $data['date']; + $bill->date = $data['date']; $bill->date_tz = $data['date']->format('e'); } if (array_key_exists('repeat_freq', $data) && '' !== (string) $data['repeat_freq']) { @@ -160,15 +160,15 @@ class BillUpdateService $bill->active = $data['active']; } if (array_key_exists('end_date', $data)) { - $bill->end_date = $data['end_date']; + $bill->end_date = $data['end_date']; $bill->end_date_tz = $data['end_date']?->format('e'); } if (array_key_exists('extension_date', $data)) { - $bill->extension_date = $data['extension_date']; + $bill->extension_date = $data['extension_date']; $bill->extension_date_tz = $data['extension_date']?->format('e'); } - $bill->match = 'EMPTY'; + $bill->match = 'EMPTY'; $bill->automatch = true; $bill->save(); @@ -183,7 +183,8 @@ class BillUpdateService ->where('order', '<=', $newOrder) ->where('order', '>', $oldOrder) ->where('bills.id', '!=', $bill->id) - ->decrement('bills.order'); + ->decrement('bills.order') + ; $bill->order = $newOrder; $bill->save(); } @@ -193,7 +194,8 @@ class BillUpdateService ->where('order', '>=', $newOrder) ->where('order', '<', $oldOrder) ->where('bills.id', '!=', $bill->id) - ->increment('bills.order'); + ->increment('bills.order') + ; $bill->order = $newOrder; $bill->save(); } @@ -206,18 +208,18 @@ class BillUpdateService /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($bill->user); - $rules = $repository->getRulesForBill($bill); + $rules = $repository->getRulesForBill($bill); if (0 === $rules->count()) { Log::debug('Found no rules.'); return; } Log::debug(sprintf('Found %d rules', $rules->count())); - $fields = [ + $fields = [ 'name' => 'description_contains', 'amount_min' => 'amount_more', 'amount_max' => 'amount_less', - 'transaction_currency_name' => 'currency_is' + 'transaction_currency_name' => 'currency_is', ]; foreach ($fields as $field => $ruleTriggerKey) { if (!array_key_exists($field, $newData)) { @@ -257,7 +259,7 @@ class BillUpdateService } } - private function getRuleTrigger(Rule $rule, string $key): null|RuleTrigger + private function getRuleTrigger(Rule $rule, string $key): ?RuleTrigger { /** @var null|RuleTrigger */ return $rule->ruleTriggers()->where('trigger_type', $key)->first(); diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php index 1763042a61..1711f164f1 100644 --- a/app/Services/Internal/Update/CategoryUpdateService.php +++ b/app/Services/Internal/Update/CategoryUpdateService.php @@ -47,7 +47,7 @@ class CategoryUpdateService { if (auth()->check()) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->user = $user; } } @@ -87,7 +87,8 @@ class CategoryUpdateService ->where('rules.user_id', $this->user->id) ->whereIn('rule_triggers.trigger_type', $types) ->where('rule_triggers.trigger_value', $oldName) - ->get(['rule_triggers.*']); + ->get(['rule_triggers.*']) + ; Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ @@ -105,7 +106,8 @@ class CategoryUpdateService ->where('rules.user_id', $this->user->id) ->whereIn('rule_actions.action_type', $types) ->where('rule_actions.action_value', $oldName) - ->get(['rule_actions.*']); + ->get(['rule_actions.*']) + ; Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ @@ -123,7 +125,8 @@ class CategoryUpdateService ->where('recurrences.user_id', $this->user->id) ->where('rt_meta.name', 'category_name') ->where('rt_meta.value', $oldName) - ->update(['rt_meta.value' => $newName]); + ->update(['rt_meta.value' => $newName]) + ; } /** @@ -131,7 +134,7 @@ class CategoryUpdateService */ private function updateNotes(Category $category, array $data): void { - $note = $data['notes'] ?? null; + $note = $data['notes'] ?? null; if (null === $note) { return; } @@ -141,7 +144,7 @@ class CategoryUpdateService return; } - $dbNote = $category->notes()->first(); + $dbNote = $category->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($category); diff --git a/app/Services/Internal/Update/CurrencyUpdateService.php b/app/Services/Internal/Update/CurrencyUpdateService.php index 7c019351e1..445b82ac63 100644 --- a/app/Services/Internal/Update/CurrencyUpdateService.php +++ b/app/Services/Internal/Update/CurrencyUpdateService.php @@ -45,13 +45,13 @@ class CurrencyUpdateService $currency->name = e($data['name']); } - $currency->enabled = false; + $currency->enabled = false; if (array_key_exists('decimal_places', $data) && is_int($data['decimal_places'])) { $currency->decimal_places = $data['decimal_places']; } $currency->userGroupEnabled = null; - $currency->userGroupNative = null; + $currency->userGroupNative = null; $currency->save(); return $currency; diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.php index 107b38edde..90df07246f 100644 --- a/app/Services/Internal/Update/GroupCloneService.php +++ b/app/Services/Internal/Update/GroupCloneService.php @@ -53,9 +53,9 @@ class GroupCloneService private function cloneJournal(TransactionJournal $journal, TransactionGroup $newGroup, int $originalGroup): void { - $newJournal = $journal->replicate(); + $newJournal = $journal->replicate(); $newJournal->transaction_group_id = $newGroup->id; - $newJournal->date = now(); + $newJournal->date = now(); $newJournal->save(); foreach ($journal->transactions as $transaction) { @@ -98,7 +98,7 @@ class GroupCloneService // add relation. // TODO clone ALL linked piggy banks /** @var null|PiggyBankEvent $event */ - $event = $journal->piggyBankEvents()->first(); + $event = $journal->piggyBankEvents()->first(); if (null !== $event) { $piggyBank = $event->piggyBank; $factory = app(PiggyBankEventFactory::class); @@ -108,18 +108,18 @@ class GroupCloneService private function cloneTransaction(Transaction $transaction, TransactionJournal $newJournal): void { - $newTransaction = $transaction->replicate(); + $newTransaction = $transaction->replicate(); $newTransaction->transaction_journal_id = $newJournal->id; - $newTransaction->reconciled = false; + $newTransaction->reconciled = false; $newTransaction->save(); } private function cloneNote(Note $note, TransactionJournal $newJournal, int $oldGroupId): void { - $newNote = $note->replicate(); - $newNote->text = sprintf("%s\n\n%s", $newNote->text, trans('firefly.clones_journal_x', [ + $newNote = $note->replicate(); + $newNote->text = sprintf("%s\n\n%s", $newNote->text, trans('firefly.clones_journal_x', [ 'description' => $newJournal->description, - 'id' => $oldGroupId + 'id' => $oldGroupId, ])); $newNote->noteable_id = $newJournal->id; $newNote->save(); @@ -127,7 +127,7 @@ class GroupCloneService private function cloneMeta(TransactionJournalMeta $meta, TransactionJournal $newJournal): void { - $newMeta = $meta->replicate(); + $newMeta = $meta->replicate(); $newMeta->transaction_journal_id = $newJournal->id; if ('recurrence_id' !== $newMeta->name) { $newMeta->save(); diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index cabea63fc7..d677f73a6f 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -55,7 +55,7 @@ class GroupUpdateService // update group name. if (array_key_exists('group_title', $data)) { Log::debug(sprintf('Update transaction group #%d title.', $transactionGroup->id)); - $oldTitle = $transactionGroup->title; + $oldTitle = $transactionGroup->title; $transactionGroup->title = $data['group_title']; $transactionGroup->save(); event(new TriggeredAuditLog($transactionGroup->user, $transactionGroup, 'update_group_title', $oldTitle, $data['group_title'])); @@ -81,8 +81,8 @@ class GroupUpdateService Log::debug('Going to update split group.'); - $existing = $transactionGroup->transactionJournals->pluck('id')->toArray(); - $updated = $this->updateTransactions($transactionGroup, $transactions); + $existing = $transactionGroup->transactionJournals->pluck('id')->toArray(); + $updated = $this->updateTransactions($transactionGroup, $transactions); Log::debug('Array of updated IDs: ', $updated); if (0 === count($updated)) { @@ -94,7 +94,7 @@ class GroupUpdateService return $transactionGroup; } - $result = array_diff($existing, $updated); + $result = array_diff($existing, $updated); Log::debug('Result of DIFF: ', $result); /** @var string $deletedId */ @@ -154,7 +154,7 @@ class GroupUpdateService $journalId = (int) ($transaction['transaction_journal_id'] ?? 0); /** @var null|TransactionJournal $journal */ - $journal = $transactionGroup->transactionJournals()->find($journalId); + $journal = $transactionGroup->transactionJournals()->find($journalId); if (null === $journal) { Log::debug('This entry has no existing journal: make a new split.'); // force the transaction type on the transaction data. @@ -194,12 +194,12 @@ class GroupUpdateService * @throws DuplicateTransactionException * @throws FireflyException */ - private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): null|TransactionJournal + private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal { $submission = ['transactions' => [$data]]; /** @var TransactionJournalFactory $factory */ - $factory = app(TransactionJournalFactory::class); + $factory = app(TransactionJournalFactory::class); $factory->setUser($transactionGroup->user); try { diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index d84c946557..1234e24859 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -65,8 +65,8 @@ class JournalUpdateService private CurrencyRepositoryInterface $currencyRepository; private TransactionGroupRepositoryInterface $transactionGroupRepository; private array $data; - private null|Account $destinationAccount = null; - private null|Transaction $destinationTransaction = null; + private ?Account $destinationAccount = null; + private ?Transaction $destinationTransaction = null; private array $metaDate = [ 'interest_date', 'book_date', @@ -74,7 +74,7 @@ class JournalUpdateService 'due_date', 'payment_date', 'invoice_date', - '_internal_previous_date' + '_internal_previous_date', ]; private array $metaString = [ 'sepa_cc', @@ -89,12 +89,12 @@ class JournalUpdateService 'internal_reference', 'bunq_payment_id', 'external_id', - 'external_url' + 'external_url', ]; - private null|Account $sourceAccount = null; - private null|Transaction $sourceTransaction = null; - private null|TransactionGroup $transactionGroup = null; - private null|TransactionJournal $transactionJournal = null; + private ?Account $sourceAccount = null; + private ?Transaction $sourceTransaction = null; + private ?TransactionGroup $transactionGroup = null; + private ?TransactionJournal $transactionJournal = null; private string $startCompareHash = ''; /** @@ -102,12 +102,12 @@ class JournalUpdateService */ public function __construct() { - $this->billRepository = app(BillRepositoryInterface::class); - $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->tagFactory = app(TagFactory::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->categoryRepository = app(CategoryRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->tagFactory = app(TagFactory::class); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->currencyRepository = app(CurrencyRepositoryInterface::class); $this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class); } @@ -118,18 +118,18 @@ class JournalUpdateService public function setTransactionGroup(TransactionGroup $transactionGroup): void { - $this->transactionGroup = $transactionGroup; + $this->transactionGroup = $transactionGroup; $this->billRepository->setUser($transactionGroup->user); $this->categoryRepository->setUser($transactionGroup->user); $this->budgetRepository->setUser($transactionGroup->user); $this->tagFactory->setUser($transactionGroup->user); $this->accountRepository->setUser($transactionGroup->user); $this->transactionGroupRepository->setUser($transactionGroup->user); - $this->destinationAccount = null; + $this->destinationAccount = null; $this->destinationTransaction = null; - $this->sourceAccount = null; - $this->sourceTransaction = null; - $this->startCompareHash = $this->transactionGroupRepository->getCompareHash($transactionGroup); + $this->sourceAccount = null; + $this->sourceTransaction = null; + $this->startCompareHash = $this->transactionGroupRepository->getCompareHash($transactionGroup); } public function setTransactionJournal(TransactionJournal $transactionJournal): void @@ -189,8 +189,8 @@ class JournalUpdateService private function hasValidSourceAccount(): bool { - $sourceId = $this->data['source_id'] ?? null; - $sourceName = $this->data['source_name'] ?? null; + $sourceId = $this->data['source_id'] ?? null; + $sourceName = $this->data['source_name'] ?? null; Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName)); if (!$this->hasFields(['source_id', 'source_name'])) { @@ -205,11 +205,11 @@ class JournalUpdateService // make a new validator. /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType($expectedType); $validator->setUser($this->transactionJournal->user); - $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true))); // TODO type overrule the account validator may have a different opinion on the transaction type. @@ -220,13 +220,13 @@ class JournalUpdateService private function hasFields(array $fields): bool { - return array_any($fields, fn($field): bool => array_key_exists($field, $this->data)); + return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data)); } private function getOriginalSourceAccount(): Account { if (!$this->sourceAccount instanceof Account) { - $source = $this->getSourceTransaction(); + $source = $this->getSourceTransaction(); $this->sourceAccount = $source->account; } @@ -237,11 +237,12 @@ class JournalUpdateService { if (!$this->sourceTransaction instanceof Transaction) { /** @var null|Transaction $result */ - $result = $this->transactionJournal + $result = $this->transactionJournal ->transactions() ->with(['account']) ->where('amount', '<', 0) - ->first(); + ->first() + ; $this->sourceTransaction = $result; } Log::debug(sprintf('getSourceTransaction: %s', $this->sourceTransaction->amount)); @@ -269,8 +270,8 @@ class JournalUpdateService private function hasValidDestinationAccount(): bool { Log::debug('Now in hasValidDestinationAccount().'); - $destId = $this->data['destination_id'] ?? null; - $destName = $this->data['destination_name'] ?? null; + $destId = $this->data['destination_id'] ?? null; + $destName = $this->data['destination_name'] ?? null; if (!$this->hasFields(['destination_id', 'destination_name'])) { Log::debug('No destination info submitted, grab the original data.'); @@ -280,16 +281,16 @@ class JournalUpdateService } // make new account validator. - $expectedType = $this->getExpectedType(); + $expectedType = $this->getExpectedType(); Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType)); // make a new validator. /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType($expectedType); $validator->setUser($this->transactionJournal->user); $validator->source = $this->getValidSourceAccount(); - $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]); + $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]); Log::debug(sprintf('hasValidDestinationAccount(%d, "%s") will return %s', $destId, $destName, var_export($result, true))); // TODO typeOverrule: the account validator may have another opinion on the transaction type. @@ -301,7 +302,7 @@ class JournalUpdateService private function getOriginalDestinationAccount(): Account { if (!$this->destinationAccount instanceof Account) { - $destination = $this->getDestinationTransaction(); + $destination = $this->getDestinationTransaction(); $this->destinationAccount = $destination->account; } @@ -315,10 +316,11 @@ class JournalUpdateService { if (!$this->destinationTransaction instanceof Transaction) { /** @var null|Transaction $result */ - $result = $this->transactionJournal + $result = $this->transactionJournal ->transactions() ->where('amount', '>', 0) - ->first(); + ->first() + ; $this->destinationTransaction = $result; } @@ -336,12 +338,12 @@ class JournalUpdateService return $this->getOriginalSourceAccount(); } - $sourceInfo = [ + $sourceInfo = [ 'id' => (int) ($this->data['source_id'] ?? null), 'name' => $this->data['source_name'] ?? null, 'iban' => $this->data['source_iban'] ?? null, 'number' => $this->data['source_number'] ?? null, - 'bic' => $this->data['source_bic'] ?? null + 'bic' => $this->data['source_bic'] ?? null, ]; $expectedType = $this->getExpectedType(); @@ -364,8 +366,8 @@ class JournalUpdateService */ private function updateAccounts(): void { - $source = $this->getValidSourceAccount(); - $destination = $this->getValidDestinationAccount(); + $source = $this->getValidSourceAccount(); + $destination = $this->getValidDestinationAccount(); // cowardly refuse to update if both accounts are the same. if ($source->id === $destination->id) { @@ -378,7 +380,7 @@ class JournalUpdateService $origSourceTransaction->account()->associate($source); $origSourceTransaction->save(); - $destTransaction = $this->getDestinationTransaction(); + $destTransaction = $this->getDestinationTransaction(); $destTransaction->account()->associate($destination); $destTransaction->save(); @@ -400,12 +402,12 @@ class JournalUpdateService return $this->getOriginalDestinationAccount(); } - $destInfo = [ + $destInfo = [ 'id' => (int) ($this->data['destination_id'] ?? null), 'name' => $this->data['destination_name'] ?? null, 'iban' => $this->data['destination_iban'] ?? null, 'number' => $this->data['destination_number'] ?? null, - 'bic' => $this->data['destination_bic'] ?? null + 'bic' => $this->data['destination_bic'] ?? null, ]; // make new account validator. @@ -429,7 +431,7 @@ class JournalUpdateService { Log::debug('Now in updateType()'); if ($this->hasFields(['type'])) { - $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']; + $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']; Log::debug(sprintf( 'Trying to change journal #%d from a %s to a %s.', $this->transactionJournal->id, @@ -460,9 +462,9 @@ class JournalUpdateService { $type = $this->transactionJournal->transactionType->type; if ((array_key_exists('bill_id', $this->data) || array_key_exists('bill_name', $this->data)) && TransactionTypeEnum::WITHDRAWAL->value === $type) { - $billId = (int) ($this->data['bill_id'] ?? 0); - $billName = (string) ($this->data['bill_name'] ?? ''); - $bill = $this->billRepository->findBill($billId, $billName); + $billId = (int) ($this->data['bill_id'] ?? 0); + $billName = (string) ($this->data['bill_name'] ?? ''); + $bill = $this->billRepository->findBill($billId, $billName); $this->transactionJournal->bill_id = $bill?->id; Log::debug('Updated bill ID'); } @@ -474,7 +476,7 @@ class JournalUpdateService private function updateField(string $fieldName): void { if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) { - $value = $this->data[$fieldName]; + $value = $this->data[$fieldName]; if ('date' === $fieldName) { if (!$value instanceof Carbon) { @@ -490,12 +492,12 @@ class JournalUpdateService // do some parsing. Log::debug(sprintf('Create date value from string "%s".', $value)); $this->transactionJournal->date_tz = $value->format('e'); - $res = $value->gt($this->transactionJournal->date); + $res = $value->gt($this->transactionJournal->date); Log::debug(sprintf('Old date: %s, new date: %s', $this->transactionJournal->date->toW3cString(), $value->toW3cString())); /** @var TransactionJournalMetaFactory $factory */ - $factory = app(TransactionJournalMetaFactory::class); - $set = ['journal' => $this->transactionJournal, 'name' => '_internal_previous_date', 'data' => null]; + $factory = app(TransactionJournalMetaFactory::class); + $set = ['journal' => $this->transactionJournal, 'name' => '_internal_previous_date', 'data' => null]; if ($res) { Log::debug('Transaction is set to be AFTER its current date. Save also the "_internal_previous_date"-field.'); $set['data'] = clone $this->transactionJournal->date; @@ -593,7 +595,7 @@ class JournalUpdateService if ($this->hasFields([$field])) { $value = '' === $this->data[$field] ? null : $this->data[$field]; Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value)); - $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value]; + $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value]; $factory->updateOrCreate($set); } } @@ -629,19 +631,19 @@ class JournalUpdateService if (!$this->hasFields(['currency_id', 'currency_code'])) { return; } - $currencyId = $this->data['currency_id'] ?? null; - $currencyCode = $this->data['currency_code'] ?? null; - $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode); + $currencyId = $this->data['currency_id'] ?? null; + $currencyCode = $this->data['currency_code'] ?? null; + $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode); // update currency everywhere. $this->transactionJournal->transaction_currency_id = $currency->id; $this->transactionJournal->save(); - $source = $this->getSourceTransaction(); - $source->transaction_currency_id = $currency->id; + $source = $this->getSourceTransaction(); + $source->transaction_currency_id = $currency->id; $source->save(); - $dest = $this->getDestinationTransaction(); - $dest->transaction_currency_id = $currency->id; + $dest = $this->getDestinationTransaction(); + $dest->transaction_currency_id = $currency->id; $dest->save(); // refresh transactions. @@ -657,7 +659,7 @@ class JournalUpdateService return; } - $value = $this->data['amount'] ?? ''; + $value = $this->data['amount'] ?? ''; Log::debug(sprintf('[a] Amount is now "%s"', $value)); try { @@ -668,14 +670,14 @@ class JournalUpdateService return; } Log::debug(sprintf('[b] Amount is now "%s"', $value)); - $origSourceTransaction = $this->getSourceTransaction(); - $destTransaction = $this->getDestinationTransaction(); - $originalSourceAmount = $origSourceTransaction->amount; + $origSourceTransaction = $this->getSourceTransaction(); + $destTransaction = $this->getDestinationTransaction(); + $originalSourceAmount = $origSourceTransaction->amount; // $originalDestAmount = $destTransaction->amount; - $origSourceTransaction->amount = Steam::negative($amount); + $origSourceTransaction->amount = Steam::negative($amount); $origSourceTransaction->balance_dirty = true; - $destTransaction->amount = Steam::positive($amount); - $destTransaction->balance_dirty = true; + $destTransaction->amount = Steam::positive($amount); + $destTransaction->balance_dirty = true; $destTransaction->save(); $origSourceTransaction->save(); @@ -684,7 +686,7 @@ class JournalUpdateService $this->destinationTransaction->refresh(); Log::debug(sprintf('Updated amount to "%s"', $amount)); - $group = $this->transactionGroup; + $group = $this->transactionGroup; if (null === $group) { $group = $this->transactionJournal?->transactionGroup; } @@ -697,13 +699,13 @@ class JournalUpdateService return; } Log::debug('Amount was changed, needs audit log entry.'); - $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // $withdrawal = TransactionTypeEnum::WITHDRAWAL->value === $this->transactionJournal->transactionType->type; - $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; - $makePositive = $transfer || $deposit ? true : false; - $recordCurrency = $origSourceTransaction->transactionCurrency; - $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); - $value = $makePositive ? Steam::positive($value) : Steam::negative($value); + $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; + $makePositive = $transfer || $deposit ? true : false; + $recordCurrency = $origSourceTransaction->transactionCurrency; + $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); + $value = $makePositive ? Steam::positive($value) : Steam::negative($value); // should not return in NULL but seems to do. event( @@ -714,7 +716,7 @@ class JournalUpdateService [ 'currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $originalSourceAmount + 'amount' => $originalSourceAmount, ], ['currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, 'amount' => $value] ) @@ -736,9 +738,9 @@ class JournalUpdateService $originalSourceAmount = $source->foreign_amount; // find currency in data array - $newForeignId = $this->data['foreign_currency_id'] ?? null; - $newForeignCode = $this->data['foreign_currency_code'] ?? null; - $foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) ?? $foreignCurrency; + $newForeignId = $this->data['foreign_currency_id'] ?? null; + $newForeignCode = $this->data['foreign_currency_code'] ?? null; + $foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) ?? $foreignCurrency; // not the same as normal currency if (null !== $foreignCurrency && $foreignCurrency->id === $this->transactionJournal->transaction_currency_id) { @@ -750,26 +752,26 @@ class JournalUpdateService // add foreign currency info to source and destination if possible. if (null !== $foreignCurrency && null !== $foreignAmount) { $source->foreign_currency_id = $foreignCurrency->id; - $source->foreign_amount = Steam::negative($foreignAmount); + $source->foreign_amount = Steam::negative($foreignAmount); $source->save(); // if the transaction is a TRANSFER, and the foreign amount and currency are set (like they seem to be) // the correct fields to update in the destination transaction are NOT the foreign amount and currency // but rather the normal amount and currency. This is new behavior. - $isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // also check if it is not between an asset account and a liability, because then the same rule applies. - $isBetween = $this->isBetweenAssetAndLiability(); + $isBetween = $this->isBetweenAssetAndLiability(); if ($isTransfer || $isBetween) { Log::debug('Switch amounts, store in amount and not foreign_amount'); $dest->transaction_currency_id = $foreignCurrency->id; - $dest->amount = Steam::positive($foreignAmount); - $dest->foreign_amount = Steam::positive($source->amount); - $dest->foreign_currency_id = $source->transaction_currency_id; + $dest->amount = Steam::positive($foreignAmount); + $dest->foreign_amount = Steam::positive($source->amount); + $dest->foreign_currency_id = $source->transaction_currency_id; } if (!$isTransfer && !$isBetween) { $dest->foreign_currency_id = $foreignCurrency->id; - $dest->foreign_amount = Steam::positive($foreignAmount); + $dest->foreign_amount = Steam::positive($foreignAmount); } $dest->save(); @@ -783,7 +785,7 @@ class JournalUpdateService // add audit log entry. Log::debug(sprintf('Updated foreign amount to "%s"', $foreignAmount)); - $group = $this->transactionGroup; + $group = $this->transactionGroup; if (null === $group) { $group = $this->transactionJournal?->transactionGroup; } @@ -796,13 +798,13 @@ class JournalUpdateService return; } Log::debug('Amount was changed, needs audit log entry.'); - $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // $withdrawal = TransactionTypeEnum::WITHDRAWAL->value === $this->transactionJournal->transactionType->type; - $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; - $makePositive = $transfer || $deposit ? true : false; - $recordCurrency = $source->foreignCurrency; - $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); - $value = $makePositive ? Steam::positive($foreignAmount) : Steam::negative($foreignAmount); + $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; + $makePositive = $transfer || $deposit ? true : false; + $recordCurrency = $source->foreignCurrency; + $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); + $value = $makePositive ? Steam::positive($foreignAmount) : Steam::negative($foreignAmount); // should not return in NULL but seems to do. event( @@ -813,7 +815,7 @@ class JournalUpdateService [ 'currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $originalSourceAmount + 'amount' => $originalSourceAmount, ], ['currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, 'amount' => $value] ) @@ -821,11 +823,11 @@ class JournalUpdateService } if ('0' === $amount) { $source->foreign_currency_id = null; - $source->foreign_amount = null; + $source->foreign_amount = null; $source->save(); - $dest->foreign_currency_id = null; - $dest->foreign_amount = null; + $dest->foreign_currency_id = null; + $dest->foreign_amount = null; $dest->save(); Log::debug(sprintf('Foreign amount is "%s" so remove foreign amount info.', $amount)); @@ -841,16 +843,18 @@ class JournalUpdateService private function isBetweenAssetAndLiability(): bool { /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $this->transactionJournal + $sourceTransaction = $this->transactionJournal ->transactions() ->where('amount', '<', 0) - ->first(); + ->first() + ; /** @var null|Transaction $destinationTransaction */ $destinationTransaction = $this->transactionJournal ->transactions() ->where('amount', '>', 0) - ->first(); + ->first() + ; if (null === $sourceTransaction || null === $destinationTransaction) { Log::warning('Either transaction is false, stop.'); @@ -862,15 +866,15 @@ class JournalUpdateService return false; } - $source = $sourceTransaction->account; - $destination = $destinationTransaction->account; + $source = $sourceTransaction->account; + $destination = $destinationTransaction->account; if (null === $source || null === $destination) { Log::warning('Either is false, stop.'); return false; } - $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; // source is liability, destination is asset if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) { diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index b720b7678a..272a60dab8 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -66,13 +66,13 @@ class RecurrenceUpdateService $recurrence->description = $info['description']; } if (array_key_exists('first_date', $info)) { - $recurrence->first_date = $info['first_date']; + $recurrence->first_date = $info['first_date']; $recurrence->first_date_tz = $info['first_date']?->format('e'); } if (array_key_exists('repeat_until', $info)) { - $recurrence->repeat_until = $info['repeat_until']; + $recurrence->repeat_until = $info['repeat_until']; $recurrence->repeat_until_tz = $info['repeat_until']?->format('e'); - $recurrence->repetitions = 0; + $recurrence->repetitions = 0; } if (array_key_exists('nr_of_repetitions', $info)) { if (0 !== (int) $info['nr_of_repetitions']) { @@ -145,7 +145,7 @@ class RecurrenceUpdateService // loop all and try to match them: Log::debug('Loop and find'); foreach ($repetitions as $current) { - $match = $this->matchRepetition($recurrence, $current); + $match = $this->matchRepetition($recurrence, $current); if (!$match instanceof RecurrenceRepetition) { throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.'); } @@ -159,7 +159,7 @@ class RecurrenceUpdateService } } - private function matchRepetition(Recurrence $recurrence, array $data): null|RecurrenceRepetition + private function matchRepetition(Recurrence $recurrence, array $data): ?RecurrenceRepetition { $originalCount = $recurrence->recurrenceRepetitions()->count(); if (1 === $originalCount) { @@ -169,8 +169,8 @@ class RecurrenceUpdateService return $recurrence->recurrenceRepetitions()->first(); } // find it: - $fields = ['id' => 'id', 'type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend']; - $query = $recurrence->recurrenceRepetitions(); + $fields = ['id' => 'id', 'type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend']; + $query = $recurrence->recurrenceRepetitions(); foreach ($fields as $field => $column) { if (array_key_exists($field, $data)) { $query->where($column, $data[$field]); @@ -189,7 +189,7 @@ class RecurrenceUpdateService private function updateTransactions(Recurrence $recurrence, array $transactions): void { Log::debug('Now in updateTransactions()'); - $originalCount = $recurrence->recurrenceTransactions()->count(); + $originalCount = $recurrence->recurrenceTransactions()->count(); Log::debug(sprintf('Original count is %d', $originalCount)); if (0 === count($transactions)) { // won't drop transactions, rather avoid. @@ -211,7 +211,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); + $first = array_shift($originalTransactions); Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id'])); $combinations[] = ['original' => $first, 'submitted' => array_shift($transactions)]; unset($first); @@ -244,7 +244,7 @@ class RecurrenceUpdateService $currencyFactory = app(TransactionCurrencyFactory::class); /** @var RecurrenceTransaction $transaction */ - $transaction = $recurrence->recurrenceTransactions()->find($original['id']); + $transaction = $recurrence->recurrenceTransactions()->find($original['id']); Log::debug(sprintf('Now in updateCombination(#%d)', $original['id'])); // loop all and try to match them: @@ -276,14 +276,14 @@ class RecurrenceUpdateService } // update fields that are part of the recurring transaction itself. - $fields = [ + $fields = [ 'source_id' => 'source_id', 'destination_id' => 'destination_id', 'amount' => 'amount', 'foreign_amount' => 'foreign_amount', 'description' => 'description', 'currency_id' => 'transaction_currency_id', - 'foreign_currency_id' => 'foreign_currency_id' + 'foreign_currency_id' => 'foreign_currency_id', ]; foreach ($fields as $field => $column) { if (array_key_exists($field, $submitted)) { @@ -303,7 +303,7 @@ class RecurrenceUpdateService if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) { Log::debug('Category name is submitted but is empty. Set category to be empty.'); $submitted['category_name'] = null; - $submitted['category_id'] = 0; + $submitted['category_id'] = 0; } if (array_key_exists('category_id', $submitted)) { diff --git a/app/Services/Webhook/StandardWebhookSender.php b/app/Services/Webhook/StandardWebhookSender.php index 44b025bccf..4df8038a84 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -59,7 +59,7 @@ class StandardWebhookSender implements WebhookSenderInterface { // have the signature generator generate a signature. If it fails, the error thrown will // end up in send() to be caught. - $signatureGenerator = app(SignatureGeneratorInterface::class); + $signatureGenerator = app(SignatureGeneratorInterface::class); $this->message->sent = true; $this->message->save(); @@ -69,13 +69,13 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error('Did not send message because of a Firefly III Exception.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; - $attempt->logs = sprintf('Exception: %s', $e->getMessage()); + $attempt->status_code = 0; + $attempt->logs = sprintf('Exception: %s', $e->getMessage()); $attempt->save(); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); return; @@ -89,18 +89,18 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error('Did not send message because of a JSON error.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; - $attempt->logs = sprintf('Json error: %s', $e->getMessage()); + $attempt->status_code = 0; + $attempt->logs = sprintf('Json error: %s', $e->getMessage()); $attempt->save(); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); return; } - $options = [ + $options = [ 'body' => $json, 'headers' => [ 'Content-Type' => 'application/json', @@ -108,10 +108,10 @@ class StandardWebhookSender implements WebhookSenderInterface 'Signature' => $signature, 'connect_timeout' => 3.14, 'User-Agent' => sprintf('FireflyIII/%s', config('firefly.version')), - 'timeout' => 10 - ] + 'timeout' => 10, + ], ]; - $client = new Client(); + $client = new Client(); try { $res = $client->request('POST', $this->message->webhook->url, $options); @@ -120,22 +120,22 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $logs = sprintf("%s\n%s", $e->getMessage(), $e->getTraceAsString()); + $logs = sprintf("%s\n%s", $e->getMessage(), $e->getTraceAsString()); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; + $attempt->status_code = 0; if (method_exists($e, 'hasResponse') && method_exists($e, 'getResponse')) { $attempt->status_code = $e->hasResponse() ? $e->getResponse()->getStatusCode() : 0; Log::error(sprintf('The status code of the error response is: %d', $attempt->status_code)); - $body = (string) ($e->hasResponse() ? $e->getResponse()->getBody() : ''); + $body = (string) ($e->hasResponse() ? $e->getResponse()->getBody() : ''); Log::error(sprintf('The body of the error response is: %s', $body)); } - $attempt->logs = $logs; + $attempt->logs = $logs; $attempt->save(); return; diff --git a/app/Support/Amount.php b/app/Support/Amount.php index 83214af1d2..b8a455b019 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -60,11 +60,11 @@ class Amount // there are five possible positions for the "+" or "-" sign (if it is even used) // pos_a and pos_e could be the ( and ) symbol. - $posA = ''; // before everything - $posB = ''; // before currency symbol - $posC = ''; // after currency symbol - $posD = ''; // before amount - $posE = ''; // after everything + $posA = ''; // before everything + $posB = ''; // before currency symbol + $posC = ''; // after currency symbol + $posD = ''; // before amount + $posE = ''; // after everything // format would be (currency before amount) // AB%sC_D%vE @@ -106,20 +106,20 @@ class Amount } if ($csPrecedes) { - return $posA . $posB . '%s' . $posC . $space . $posD . '%v' . $posE; + return $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE; } - return $posA . $posD . '%v' . $space . $posB . '%s' . $posC . $posE; + return $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE; } - public function convertToPrimary(null|User $user = null): bool + public function convertToPrimary(?User $user = null): bool { $instance = PreferencesSingleton::getInstance(); if (!$user instanceof User) { $pref = $instance->getPreference('convert_to_primary_no_user'); if (null === $pref) { - $res = - true === Preferences::get('convert_to_primary', false)->data + $res + = true === Preferences::get('convert_to_primary', false)->data && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $instance->setPreference('convert_to_primary_no_user', $res); @@ -128,11 +128,11 @@ class Amount return $pref; } - $key = sprintf('convert_to_primary_%d', $user->id); - $pref = $instance->getPreference($key); + $key = sprintf('convert_to_primary_%d', $user->id); + $pref = $instance->getPreference($key); if (null === $pref) { - $res = - true === Preferences::getForUser($user, 'convert_to_primary', false)->data + $res + = true === Preferences::getForUser($user, 'convert_to_primary', false)->data && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $instance->setPreference($key, $res); @@ -148,12 +148,12 @@ class Amount * * @throws FireflyException */ - public function formatAnything(TransactionCurrency $format, string $amount, null|bool $coloured = null): string + public function formatAnything(TransactionCurrency $format, string $amount, ?bool $coloured = null): string { return $this->formatFlat($format->symbol, $format->decimal_places, $amount, $coloured); } - public function formatByCurrencyId(int $currencyId, string $amount, null|bool $coloured = null): string + public function formatByCurrencyId(int $currencyId, string $amount, ?bool $coloured = null): string { $format = $this->getTransactionCurrencyById($currencyId); @@ -166,18 +166,18 @@ class Amount * * @throws FireflyException */ - public function formatFlat(string $symbol, int $decimalPlaces, string $amount, null|bool $coloured = null): string + public function formatFlat(string $symbol, int $decimalPlaces, string $amount, ?bool $coloured = null): string { - $amount = Steam::anonymous() ? '0' : $amount; - $locale = Steam::getLocale(); - $rounded = Steam::bcround($amount, $decimalPlaces); + $amount = Steam::anonymous() ? '0' : $amount; + $locale = Steam::getLocale(); + $rounded = Steam::bcround($amount, $decimalPlaces); $coloured ??= true; - $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol); $fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); - $result = (string) $fmt->format((float) $rounded); // intentional float + $result = (string) $fmt->format((float) $rounded); // intentional float if ($coloured) { if (1 === bccomp($rounded, '0')) { @@ -225,16 +225,16 @@ class Amount */ public function getAmountFromJournalObject(TransactionJournal $journal): string { - $convertToPrimary = $this->convertToPrimary(); - $currency = $this->getPrimaryCurrency(); - $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount'; + $convertToPrimary = $this->convertToPrimary(); + $currency = $this->getPrimaryCurrency(); + $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount'; /** @var null|Transaction $sourceTransaction */ $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $sourceTransaction) { return '0'; } - $amount = $sourceTransaction->{$field} ?? '0'; + $amount = $sourceTransaction->{$field} ?? '0'; if ((int) $sourceTransaction->foreign_currency_id === $currency->id) { // use foreign amount instead! $amount = (string) $sourceTransaction->foreign_amount; // hard coded to be foreign amount. @@ -268,7 +268,7 @@ class Amount return [ 'mon_decimal_point' => $config['mon_decimal_point'], 'mon_thousands_sep' => $config['mon_thousands_sep'], - 'format' => ['pos' => $positive, 'neg' => $negative, 'zero' => $positive] + 'format' => ['pos' => $positive, 'neg' => $negative, 'zero' => $positive], ]; } @@ -287,7 +287,7 @@ class Amount public function getPrimaryCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty('getPrimaryCurrencyByGroup'); $cache->addProperty($userGroup->id); if ($cache->has()) { @@ -317,7 +317,7 @@ class Amount $key = sprintf('transaction_currency_%s', $code); /** @var null|TransactionCurrency $pref */ - $pref = $instance->getPreference($key); + $pref = $instance->getPreference($key); if (null !== $pref) { return $pref; } @@ -344,7 +344,7 @@ class Amount $key = sprintf('transaction_currency_%d', $currencyId); /** @var null|TransactionCurrency $pref */ - $pref = $instance->getPreference($key); + $pref = $instance->getPreference($key); if (null !== $pref) { return $pref; } @@ -371,20 +371,20 @@ class Amount private function getLocaleInfo(): array { // get config from preference, not from translation: - $locale = Steam::getLocale(); - $array = Steam::getLocaleArray($locale); + $locale = Steam::getLocale(); + $array = Steam::getLocaleArray($locale); setlocale(LC_MONETARY, $array); - $info = localeconv(); + $info = localeconv(); // correct variables - $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes'); - $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes'); + $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes'); + $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes'); - $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space'); - $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space'); + $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space'); + $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space'); - $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); $info['mon_decimal_point'] = $fmt->getSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL); $info['mon_thousands_sep'] = $fmt->getSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL); diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index 81f4fa7464..1ca788fd2b 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -39,7 +39,7 @@ use Illuminate\Support\Facades\Log; class RemoteUserGuard implements Guard { protected Application $application; - protected null|User $user = null; + protected ?User $user = null; /** * Create a new authentication guard. @@ -62,8 +62,8 @@ class RemoteUserGuard implements Guard return; } // Get the user identifier from $_SERVER or apache filtered headers - $header = config('auth.guard_header', 'REMOTE_USER'); - $userID = request()->server($header) ?? null; + $header = config('auth.guard_header', 'REMOTE_USER'); + $userID = request()->server($header) ?? null; if (function_exists('apache_request_headers')) { Log::debug('Use apache_request_headers to find user ID.'); @@ -82,7 +82,7 @@ class RemoteUserGuard implements Guard $retrievedUser = $this->provider->retrieveById($userID); // store email address if present in header and not already set. - $header = config('auth.guard_email'); + $header = config('auth.guard_email'); if (null !== $header) { $emailAddress = (string) (request()->server($header) ?? apache_request_headers()[$header] ?? null); @@ -98,7 +98,7 @@ class RemoteUserGuard implements Guard } Log::debug(sprintf('Result of getting user from provider: %s', $retrievedUser->email)); - $this->user = $retrievedUser; + $this->user = $retrievedUser; } public function check(): bool @@ -143,7 +143,7 @@ class RemoteUserGuard implements Guard Log::error(sprintf('Did not set user at %s', __METHOD__)); } - public function user(): null|User + public function user(): ?User { // Log::debug(sprintf('Now at %s', __METHOD__)); $user = $this->user; diff --git a/app/Support/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php index 8149ed3b13..cef126bd62 100644 --- a/app/Support/Authentication/RemoteUserProvider.php +++ b/app/Support/Authentication/RemoteUserProvider.php @@ -53,7 +53,7 @@ class RemoteUserProvider implements UserProvider * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function retrieveByCredentials(array $credentials): null|Authenticatable + public function retrieveByCredentials(array $credentials): ?Authenticatable { Log::debug(sprintf('Now at %s', __METHOD__)); @@ -94,7 +94,7 @@ class RemoteUserProvider implements UserProvider * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function retrieveByToken($identifier, #[SensitiveParameter] $token): null|Authenticatable + public function retrieveByToken($identifier, #[SensitiveParameter] $token): ?Authenticatable { Log::debug(sprintf('Now at %s', __METHOD__)); diff --git a/app/Support/Balance.php b/app/Support/Balance.php index fcd47d1d36..03b24b1a99 100644 --- a/app/Support/Balance.php +++ b/app/Support/Balance.php @@ -50,20 +50,21 @@ class Balance return $cache->get(); } - $query = Transaction::whereIn('transactions.account_id', $accounts->pluck('id')->toArray()) + $query = Transaction::whereIn('transactions.account_id', $accounts->pluck('id')->toArray()) ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->orderBy('transaction_journals.date', 'desc') ->orderBy('transaction_journals.order', 'asc') ->orderBy('transaction_journals.description', 'desc') ->orderBy('transactions.amount', 'desc') - ->where('transaction_journals.date', '<=', $date); + ->where('transaction_journals.date', '<=', $date) + ; - $result = $query->get(['transactions.account_id', 'transactions.transaction_currency_id', 'transactions.balance_after']); + $result = $query->get(['transactions.account_id', 'transactions.transaction_currency_id', 'transactions.balance_after']); foreach ($result as $entry) { - $accountId = (int) $entry->account_id; - $currencyId = (int) $entry->transaction_currency_id; + $accountId = (int) $entry->account_id; + $currencyId = (int) $entry->transaction_currency_id; $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $return[$accountId] ??= []; + $return[$accountId] ??= []; if (array_key_exists($currencyId, $return[$accountId])) { continue; } diff --git a/app/Support/Binder/AccountList.php b/app/Support/Binder/AccountList.php index ad6daac31e..6171a3e005 100644 --- a/app/Support/Binder/AccountList.php +++ b/app/Support/Binder/AccountList.php @@ -51,14 +51,15 @@ class AccountList implements BinderInterface AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]) ->orderBy('accounts.name', 'ASC') - ->get(['accounts.*']); + ->get(['accounts.*']) + ; } if ('allAssetAccounts' !== $value) { - $incoming = array_map(\intval(...), explode(',', $value)); - $list = array_merge(array_unique($incoming), [0]); + $incoming = array_map(\intval(...), explode(',', $value)); + $list = array_merge(array_unique($incoming), [0]); /** @var Collection $collection */ $collection = auth() @@ -67,7 +68,8 @@ class AccountList implements BinderInterface ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('accounts.id', $list) ->orderBy('accounts.name', 'ASC') - ->get(['accounts.*']); + ->get(['accounts.*']) + ; } if ($collection->count() > 0) { diff --git a/app/Support/Binder/BudgetList.php b/app/Support/Binder/BudgetList.php index 14038f699b..29d756356d 100644 --- a/app/Support/Binder/BudgetList.php +++ b/app/Support/Binder/BudgetList.php @@ -44,7 +44,7 @@ class BudgetList implements BinderInterface return auth()->user()->budgets()->where('active', true)->orderBy('order', 'ASC')->orderBy('name', 'ASC')->get(); } - $list = array_unique(array_map(\intval(...), explode(',', $value))); + $list = array_unique(array_map(\intval(...), explode(',', $value))); if (0 === count($list)) { // @phpstan-ignore-line Log::warning('Budget list count is zero, return 404.'); diff --git a/app/Support/Binder/CategoryList.php b/app/Support/Binder/CategoryList.php index 3e7b4c93a2..e7f14bd6b6 100644 --- a/app/Support/Binder/CategoryList.php +++ b/app/Support/Binder/CategoryList.php @@ -43,7 +43,7 @@ class CategoryList implements BinderInterface return auth()->user()->categories()->orderBy('name', 'ASC')->get(); } - $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 812641c8a2..a89cc8f2a3 100644 --- a/app/Support/Binder/Date.php +++ b/app/Support/Binder/Date.php @@ -44,21 +44,21 @@ class Date implements BinderInterface /** @var FiscalHelperInterface $fiscalHelper */ $fiscalHelper = app(FiscalHelperInterface::class); - $magicWords = [ - 'currentMonthStart' => today(config('app.timezone'))->startOfMonth(), - 'currentMonthEnd' => today(config('app.timezone'))->endOfMonth(), - 'currentYearStart' => today(config('app.timezone'))->startOfYear(), - 'currentYearEnd' => today(config('app.timezone'))->endOfYear(), + $magicWords = [ + 'currentMonthStart' => today(config('app.timezone'))->startOfMonth(), + 'currentMonthEnd' => today(config('app.timezone'))->endOfMonth(), + 'currentYearStart' => today(config('app.timezone'))->startOfYear(), + 'currentYearEnd' => today(config('app.timezone'))->endOfYear(), - 'previousMonthStart' => today(config('app.timezone'))->startOfMonth()->subDay()->startOfMonth(), - 'previousMonthEnd' => today(config('app.timezone'))->startOfMonth()->subDay()->endOfMonth(), - 'previousYearStart' => today(config('app.timezone'))->startOfYear()->subDay()->startOfYear(), - 'previousYearEnd' => today(config('app.timezone'))->startOfYear()->subDay()->endOfYear(), + 'previousMonthStart' => today(config('app.timezone'))->startOfMonth()->subDay()->startOfMonth(), + 'previousMonthEnd' => today(config('app.timezone'))->startOfMonth()->subDay()->endOfMonth(), + 'previousYearStart' => today(config('app.timezone'))->startOfYear()->subDay()->startOfYear(), + 'previousYearEnd' => today(config('app.timezone'))->startOfYear()->subDay()->endOfYear(), 'currentFiscalYearStart' => $fiscalHelper->startOfFiscalYear(today(config('app.timezone'))), 'currentFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone'))), 'previousFiscalYearStart' => $fiscalHelper->startOfFiscalYear(today(config('app.timezone')))->subYear(), - 'previousFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone')))->subYear() + 'previousFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone')))->subYear(), ]; if (array_key_exists($value, $magicWords)) { $return = $magicWords[$value]; diff --git a/app/Support/Binder/DynamicConfigKey.php b/app/Support/Binder/DynamicConfigKey.php index b71474bd08..bf4599b414 100644 --- a/app/Support/Binder/DynamicConfigKey.php +++ b/app/Support/Binder/DynamicConfigKey.php @@ -42,7 +42,7 @@ class DynamicConfigKey 'configuration.enable_external_map', // boolean 'configuration.enable_external_rates', // boolean 'configuration.allow_webhooks', // boolean - 'configuration.valid_url_protocols' // string ("http,https") + 'configuration.valid_url_protocols', // string ("http,https") ]; /** diff --git a/app/Support/Binder/EitherConfigKey.php b/app/Support/Binder/EitherConfigKey.php index 0b34c86642..1d5e98f62f 100644 --- a/app/Support/Binder/EitherConfigKey.php +++ b/app/Support/Binder/EitherConfigKey.php @@ -61,7 +61,7 @@ class EitherConfigKey // webhooks 'webhook.triggers', 'webhook.responses', - 'webhook.deliveries' + 'webhook.deliveries', ]; /** diff --git a/app/Support/Binder/JournalList.php b/app/Support/Binder/JournalList.php index f76bfb999f..394ad2feea 100644 --- a/app/Support/Binder/JournalList.php +++ b/app/Support/Binder/JournalList.php @@ -39,7 +39,7 @@ class JournalList implements BinderInterface public static function routeBinder(string $value, Route $route): array { if (auth()->check()) { - $list = self::parseList($value); + $list = self::parseList($value); // get the journals by using the collector. /** @var GroupCollectorInterface $collector */ @@ -48,11 +48,11 @@ class JournalList implements BinderInterface TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ]); $collector->withCategoryInformation()->withBudgetInformation()->withTagInformation()->withAccountInformation(); $collector->setJournalIds($list); - $result = $collector->getExtractedJournals(); + $result = $collector->getExtractedJournals(); if (0 === count($result)) { throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/TagList.php b/app/Support/Binder/TagList.php index 3fd514a654..7d6e3900e2 100644 --- a/app/Support/Binder/TagList.php +++ b/app/Support/Binder/TagList.php @@ -44,7 +44,7 @@ class TagList implements BinderInterface if ('allTags' === $value) { return auth()->user()->tags()->orderBy('tag', 'ASC')->get(); } - $list = array_unique(array_map(\strtolower(...), explode(',', $value))); + $list = array_unique(array_map(\strtolower(...), explode(',', $value))); Log::debug('List of tags is', $list); if (0 === count($list)) { // @phpstan-ignore-line @@ -56,7 +56,7 @@ class TagList implements BinderInterface /** @var TagRepositoryInterface $repository */ $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $allTags = $repository->get(); + $allTags = $repository->get(); $collection = $allTags->filter(static function (Tag $tag) use ($list): bool { if (in_array(strtolower($tag->tag), $list, true)) { diff --git a/app/Support/Binder/TagOrId.php b/app/Support/Binder/TagOrId.php index 48f766a3d5..64f9aa0dbe 100644 --- a/app/Support/Binder/TagOrId.php +++ b/app/Support/Binder/TagOrId.php @@ -41,7 +41,7 @@ class TagOrId implements BinderInterface $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $result = $repository->findByTag($value); + $result = $repository->findByTag($value); if (null === $result) { $result = $repository->find((int) $value); } diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index ebb2381982..2dd4415a2c 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -91,7 +91,7 @@ class CacheProperties private function hash(): void { - $content = ''; + $content = ''; foreach ($this->properties as $property) { try { $content = sprintf('%s%s', $content, json_encode($property, JSON_THROW_ON_ERROR)); diff --git a/app/Support/Calendar/Calculator.php b/app/Support/Calendar/Calculator.php index 6fd2361ee4..02b4f7ce84 100644 --- a/app/Support/Calendar/Calculator.php +++ b/app/Support/Calendar/Calculator.php @@ -33,10 +33,10 @@ use SplObjectStorage; */ class Calculator { - public const int DEFAULT_INTERVAL = 1; + public const int DEFAULT_INTERVAL = 1; - private static null|SplObjectStorage $intervalMap = null; // @phpstan-ignore-line - private static array $intervals = []; + private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line + private static array $intervals = []; private function containsInterval(Periodicity $periodicity): bool { @@ -50,7 +50,7 @@ class Calculator } self::$intervalMap = new SplObjectStorage(); foreach (Periodicity::cases() as $interval) { - $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name); + $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name); self::$intervals[] = $interval->name; self::$intervalMap->attach($interval, new $periodicityClass()); } diff --git a/app/Support/Chart/Budget/FrontpageChartGenerator.php b/app/Support/Chart/Budget/FrontpageChartGenerator.php index 7c20dc5dc5..2c18fe3abd 100644 --- a/app/Support/Chart/Budget/FrontpageChartGenerator.php +++ b/app/Support/Chart/Budget/FrontpageChartGenerator.php @@ -40,7 +40,7 @@ use Illuminate\Support\Facades\Log; */ class FrontpageChartGenerator { - public bool $convertToPrimary = false; + public bool $convertToPrimary = false; public TransactionCurrency $default; protected OperationsRepositoryInterface $opsRepository; private readonly BudgetLimitRepositoryInterface $blRepository; @@ -55,8 +55,8 @@ class FrontpageChartGenerator public function __construct() { $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); } /** @@ -71,7 +71,7 @@ class FrontpageChartGenerator $data = [ ['label' => (string) trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], ['label' => (string) trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], - ['label' => (string) trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'] + ['label' => (string) trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'], ]; // loop al budgets: @@ -103,7 +103,7 @@ class FrontpageChartGenerator $this->blRepository->setUser($user); $this->opsRepository->setUser($user); - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); } @@ -133,7 +133,7 @@ class FrontpageChartGenerator /** @var array $entry */ foreach ($spent as $entry) { - $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); + $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); $data[0]['entries'][$title] = bcmul((string) $entry['sum'], '-1'); // spent $data[1]['entries'][$title] = 0; // left to spend $data[2]['entries'][$title] = 0; // overspent @@ -181,7 +181,7 @@ class FrontpageChartGenerator Log::debug(sprintf('Processing limit #%d with %s %s', $limit->id, $limit->transactionCurrency->code, $limit->amount)); } - $spent = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); + $spent = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); Log::debug(sprintf('Spent array has %d entries.', count($spent))); /** @var array $entry */ @@ -208,7 +208,7 @@ class FrontpageChartGenerator */ private function processRow(array $data, Budget $budget, BudgetLimit $limit, array $entry): array { - $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); + $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); Log::debug(sprintf('Title is "%s"', $title)); if ($limit->start_date->startOfDay()->ne($this->start->startOfDay()) || $limit->end_date->startOfDay()->ne($this->end->startOfDay())) { $title = sprintf( @@ -219,15 +219,15 @@ class FrontpageChartGenerator $limit->end_date->isoFormat($this->monthAndDayFormat) ); } - $usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id; - $amount = $limit->amount; + $usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id; + $amount = $limit->amount; Log::debug(sprintf('Amount is "%s".', $amount)); if ($usePrimary && $limit->transaction_currency_id !== $this->default->id) { $amount = $limit->native_amount; Log::debug(sprintf('Amount is now "%s".', $amount)); } - $amount ??= '0'; - $sumSpent = bcmul((string) $entry['sum'], '-1'); // spent + $amount ??= '0'; + $sumSpent = bcmul((string) $entry['sum'], '-1'); // spent $data[0]['entries'][$title] ??= '0'; $data[1]['entries'][$title] ??= '0'; $data[2]['entries'][$title] ??= '0'; diff --git a/app/Support/Chart/Category/FrontpageChartGenerator.php b/app/Support/Chart/Category/FrontpageChartGenerator.php index 775ac9e7d6..e1daae4c2a 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; @@ -57,31 +57,31 @@ class FrontpageChartGenerator private Carbon $start, private Carbon $end ) { - $this->repository = app(CategoryRepositoryInterface::class); + $this->repository = app(CategoryRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class); - $this->opsRepos = app(OperationsRepositoryInterface::class); - $this->noCatRepos = app(NoCategoryRepositoryInterface::class); + $this->opsRepos = app(OperationsRepositoryInterface::class); + $this->noCatRepos = app(NoCategoryRepositoryInterface::class); } public function generate(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $categories = $this->repository->getCategories(); - $accounts = $this->accountRepos->getAccountsByType([ + $categories = $this->repository->getCategories(); + $accounts = $this->accountRepos->getAccountsByType([ AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::ASSET->value, - AccountTypeEnum::DEFAULT->value + AccountTypeEnum::DEFAULT->value, ]); - $collection = $this->collectExpensesAll($categories, $accounts); + $collection = $this->collectExpensesAll($categories, $accounts); // collect for no-category: - $noCategory = $this->collectNoCatExpenses($accounts); - $collection = array_merge($collection, $noCategory); + $noCategory = $this->collectNoCatExpenses($accounts); + $collection = array_merge($collection, $noCategory); // sort temp array by amount. - $amounts = array_column($collection, 'sum_float'); + $amounts = array_column($collection, 'sum_float'); array_multisort($amounts, SORT_ASC, $collection); $currencyData = $this->createCurrencyGroups($collection); @@ -98,7 +98,7 @@ class FrontpageChartGenerator 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'] + 'currency_decimal_places' => $currency['currency_decimal_places'], ]; } @@ -118,7 +118,7 @@ class FrontpageChartGenerator 'name' => $category->name, 'sum' => $currency['sum'], 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places']), - 'currency_id' => (int) $currency['currency_id'] + 'currency_id' => (int) $currency['currency_id'], ]; } } @@ -133,10 +133,10 @@ class FrontpageChartGenerator foreach ($noCatExp as $currency) { $this->addCurrency($currency); $tempData[] = [ - 'name' => trans('firefly.no_category'), - 'sum' => $currency['sum'], - 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places'] ?? 2), // intentional float - 'currency_id' => (int) $currency['currency_id'] + 'name' => trans('firefly.no_category'), + 'sum' => $currency['sum'], + 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places'] ?? 2), // intentional float + 'currency_id' => (int) $currency['currency_id'], ]; } @@ -152,12 +152,12 @@ class FrontpageChartGenerator * @var array $currency */ foreach ($this->currencies as $currencyId => $currency) { - $key = sprintf('spent-%d', $currencyId); + $key = sprintf('spent-%d', $currencyId); $return[$key] = [ 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currency['currency_name']), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], - 'entries' => $names + 'entries' => $names, ]; } @@ -168,10 +168,10 @@ class FrontpageChartGenerator { /** @var array $array */ foreach ($monetaryData as $array) { - $direction = $array['sum_float'] < 0 ? 'spent' : 'earned'; - $key = sprintf('%s-%d', $direction, $array['currency_id']); - $category = $array['name']; - $amount = $array['sum_float'] < 0 ? $array['sum_float'] * -1 : $array['sum_float']; + $direction = $array['sum_float'] < 0 ? 'spent' : 'earned'; + $key = sprintf('%s-%d', $direction, $array['currency_id']); + $category = $array['name']; + $amount = $array['sum_float'] < 0 ? $array['sum_float'] * -1 : $array['sum_float']; $currencyData[$key]['entries'][$category] = $amount; } diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php index 8557528b8a..14bca78ac9 100644 --- a/app/Support/Chart/Category/WholePeriodChartGenerator.php +++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php @@ -42,74 +42,74 @@ class WholePeriodChartGenerator public function generate(Category $category, Carbon $start, Carbon $end): array { - $collection = new Collection()->push($category); + $collection = new Collection()->push($category); /** @var OperationsRepositoryInterface $opsRepository */ - $opsRepository = app(OperationsRepositoryInterface::class); + $opsRepository = app(OperationsRepositoryInterface::class); /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); - $types = [ + $types = [ AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]; - $accounts = $accountRepository->getAccountsByType($types); - $step = $this->calculateStep($start, $end); - $chartData = []; - $spent = []; - $earned = []; + $accounts = $accountRepository->getAccountsByType($types); + $step = $this->calculateStep($start, $end); + $chartData = []; + $spent = []; + $earned = []; - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $key = $current->format('Y-m-d'); - $currentEnd = Navigation::endOfPeriod($current, $step); - $spent[$key] = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection); + $key = $current->format('Y-m-d'); + $currentEnd = Navigation::endOfPeriod($current, $step); + $spent[$key] = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection); $earned[$key] = $opsRepository->sumIncome($current, $currentEnd, $accounts, $collection); - $current = Navigation::addPeriod($current, $step); + $current = Navigation::addPeriod($current, $step); } - $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned); + $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned); // generate chart data (for each currency) /** @var array $currency */ foreach ($currencies as $currency) { - $code = $currency['currency_code']; - $name = $currency['currency_name']; - $chartData[sprintf('spent-in-%s', $code)] = [ + $code = $currency['currency_code']; + $name = $currency['currency_name']; + $chartData[sprintf('spent-in-%s', $code)] = [ 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', - 'backgroundColor' => 'rgba(219, 68, 55, 0.5)' // red + 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red ]; $chartData[sprintf('earned-in-%s', $code)] = [ 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', - 'backgroundColor' => 'rgba(0, 141, 76, 0.5)' // green + 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green ]; } - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $key = $current->format('Y-m-d'); - $label = Navigation::periodShow($current, $step); + $key = $current->format('Y-m-d'); + $label = Navigation::periodShow($current, $step); /** @var array $currency */ foreach ($currencies as $currency) { - $code = $currency['currency_code']; - $currencyId = $currency['currency_id']; - $spentInfoKey = sprintf('spent-in-%s', $code); - $earnedInfoKey = sprintf('earned-in-%s', $code); - $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; - $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; - $chartData[$spentInfoKey]['entries'][$label] = Steam::bcround($spentAmount, $currency['currency_decimal_places']); + $code = $currency['currency_code']; + $currencyId = $currency['currency_id']; + $spentInfoKey = sprintf('spent-in-%s', $code); + $earnedInfoKey = sprintf('earned-in-%s', $code); + $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; + $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; + $chartData[$spentInfoKey]['entries'][$label] = Steam::bcround($spentAmount, $currency['currency_decimal_places']); $chartData[$earnedInfoKey]['entries'][$label] = Steam::bcround($earnedAmount, $currency['currency_decimal_places']); } $current = Navigation::addPeriod($current, $step); @@ -152,7 +152,7 @@ class WholePeriodChartGenerator 'currency_name' => $currencyRow['currency_name'], 'currency_symbol' => $currencyRow['currency_symbol'], 'currency_code' => $currencyRow['currency_code'], - 'currency_decimal_places' => $currencyRow['currency_decimal_places'] + 'currency_decimal_places' => $currencyRow['currency_decimal_places'], ]; } } diff --git a/app/Support/Chart/ChartData.php b/app/Support/Chart/ChartData.php index 2de1fe0fae..756ca62e3c 100644 --- a/app/Support/Chart/ChartData.php +++ b/app/Support/Chart/ChartData.php @@ -44,7 +44,7 @@ class ChartData if (array_key_exists('primary_currency_id', $data)) { $data['primary_currency_id'] = (string) $data['primary_currency_id']; } - $required = ['start', 'date', 'end', 'entries']; + $required = ['start', 'date', 'end', 'entries']; foreach ($required as $field) { if (!array_key_exists($field, $data)) { throw new FireflyException(sprintf('Data-set is missing the "%s"-variable.', $field)); diff --git a/app/Support/ChartColour.php b/app/Support/ChartColour.php index 464037126d..e90b5c4a41 100644 --- a/app/Support/ChartColour.php +++ b/app/Support/ChartColour.php @@ -48,13 +48,13 @@ class ChartColour [92, 107, 192], [240, 98, 146], [0, 121, 107], - [194, 24, 91] + [194, 24, 91], ]; public static function getColour(int $index): string { $index %= count(self::$colours); - $row = self::$colours[$index]; + $row = self::$colours[$index]; return sprintf('rgba(%d, %d, %d, 0.7)', $row[0], $row[1], $row[2]); } diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index cddaae44c1..b8de7d8b63 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -34,10 +34,10 @@ abstract class AbstractCronjob public bool $jobErrored = false; public bool $jobFired = false; public bool $jobSucceeded = false; - public null|string $message = null; + public ?string $message = null; public int $timeBetweenRuns = 43200; protected Carbon $date; - protected bool $force = false; + protected bool $force = false; /** * AbstractCronjob constructor. @@ -51,7 +51,7 @@ abstract class AbstractCronjob final public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $this->date = $newDate; } diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php index 3112ee29b5..9023fce8f7 100644 --- a/app/Support/Cronjobs/AutoBudgetCronjob.php +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -71,15 +71,15 @@ class AutoBudgetCronjob extends AbstractCronjob Log::info(sprintf('Will now fire auto budget cron job task for date "%s".', $this->date->format('Y-m-d'))); /** @var CreateAutoBudgetLimits $job */ - $job = app(CreateAutoBudgetLimits::class, [$this->date]); + $job = app(CreateAutoBudgetLimits::class, [$this->date]); $job->setDate($this->date); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Auto-budget cron job fired successfully.'; + $this->message = 'Auto-budget cron job fired successfully.'; FireflyConfig::set('last_ab_job', (int) $this->date->format('U')); Log::info('Done with auto budget cron job task.'); diff --git a/app/Support/Cronjobs/BillWarningCronjob.php b/app/Support/Cronjobs/BillWarningCronjob.php index 00989aaca8..c37f2ff54c 100644 --- a/app/Support/Cronjobs/BillWarningCronjob.php +++ b/app/Support/Cronjobs/BillWarningCronjob.php @@ -58,9 +58,9 @@ class BillWarningCronjob extends AbstractCronjob Log::info(sprintf('It has been %s since the bill notification cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been %s since the bill notification cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been %s since the bill notification cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -83,16 +83,16 @@ class BillWarningCronjob extends AbstractCronjob Log::info(sprintf('Will now fire bill notification job task for date "%s".', $this->date->format('Y-m-d H:i:s'))); /** @var WarnAboutBills $job */ - $job = app(WarnAboutBills::class); + $job = app(WarnAboutBills::class); $job->setDate($this->date); $job->setForce($this->force); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Bill notification cron job fired successfully.'; + $this->message = 'Bill notification cron job fired successfully.'; FireflyConfig::set('last_bw_job', (int) $this->date->format('U')); Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); diff --git a/app/Support/Cronjobs/ExchangeRatesCronjob.php b/app/Support/Cronjobs/ExchangeRatesCronjob.php index 63e100e5c0..c80b0e4fb5 100644 --- a/app/Support/Cronjobs/ExchangeRatesCronjob.php +++ b/app/Support/Cronjobs/ExchangeRatesCronjob.php @@ -72,15 +72,15 @@ class ExchangeRatesCronjob extends AbstractCronjob Log::info(sprintf('Will now fire exchange rates cron job task for date "%s".', $this->date->format('Y-m-d'))); /** @var DownloadExchangeRates $job */ - $job = app(DownloadExchangeRates::class); + $job = app(DownloadExchangeRates::class); $job->setDate($this->date); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Exchange rates cron job fired successfully.'; + $this->message = 'Exchange rates cron job fired successfully.'; FireflyConfig::set('last_cer_job', (int) $this->date->format('U')); Log::info('Done with exchange rates job task.'); diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index fe0de200e7..7c8f6c95ee 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -58,9 +58,9 @@ class RecurringCronjob extends AbstractCronjob Log::info(sprintf('It has been "%s" since the recurring transactions cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been "%s" since the recurring transactions cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been "%s" since the recurring transactions cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -81,15 +81,15 @@ class RecurringCronjob extends AbstractCronjob { Log::info(sprintf('Will now fire recurring cron job task for date "%s".', $this->date->format('Y-m-d H:i:s'))); - $job = new CreateRecurringTransactions($this->date); + $job = new CreateRecurringTransactions($this->date); $job->setForce($this->force); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Recurring transactions cron job fired successfully.'; + $this->message = 'Recurring transactions cron job fired successfully.'; FireflyConfig::set('last_rt_job', (int) $this->date->format('U')); Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); diff --git a/app/Support/Cronjobs/UpdateCheckCronjob.php b/app/Support/Cronjobs/UpdateCheckCronjob.php index 8d9a4b1cf0..4c39ea5cf8 100644 --- a/app/Support/Cronjobs/UpdateCheckCronjob.php +++ b/app/Support/Cronjobs/UpdateCheckCronjob.php @@ -41,31 +41,31 @@ class UpdateCheckCronjob extends AbstractCronjob Log::debug('Now in checkForUpdates()'); // should not check for updates: - $permission = FireflyConfig::get('permission_update_check', -1); - $value = (int) $permission->data; + $permission = FireflyConfig::get('permission_update_check', -1); + $value = (int) $permission->data; if (1 !== $value) { Log::debug('Update check is not enabled.'); // get stuff from job: - $this->jobFired = false; - $this->jobErrored = false; + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'The update check is not enabled.'; + $this->message = 'The update check is not enabled.'; return; } // TODO this is duplicate. /** @var Configuration $lastCheckTime */ - $lastCheckTime = FireflyConfig::get('last_update_check', Carbon::now()->getTimestamp()); - $now = Carbon::now()->getTimestamp(); - $diff = $now - $lastCheckTime->data; + $lastCheckTime = FireflyConfig::get('last_update_check', Carbon::now()->getTimestamp()); + $now = Carbon::now()->getTimestamp(); + $diff = $now - $lastCheckTime->data; Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); if ($diff < 604800 && false === $this->force) { // get stuff from job: - $this->jobFired = false; - $this->jobErrored = false; + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = sprintf( + $this->message = sprintf( 'Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s') ); @@ -74,20 +74,20 @@ class UpdateCheckCronjob extends AbstractCronjob } // last check time was more than a week ago. Log::debug('Have not checked for a new version in a week!'); - $release = $this->getLatestRelease(); + $release = $this->getLatestRelease(); if ('error' === $release['level']) { // get stuff from job: - $this->jobFired = true; - $this->jobErrored = true; + $this->jobFired = true; + $this->jobErrored = true; $this->jobSucceeded = false; - $this->message = $release['message']; + $this->message = $release['message']; return; } // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = false; - $this->message = $release['message']; + $this->message = $release['message']; } } diff --git a/app/Support/Cronjobs/WebhookCronjob.php b/app/Support/Cronjobs/WebhookCronjob.php index 21c82dab8c..be1801e997 100644 --- a/app/Support/Cronjobs/WebhookCronjob.php +++ b/app/Support/Cronjobs/WebhookCronjob.php @@ -58,9 +58,9 @@ class WebhookCronjob extends AbstractCronjob Log::info(sprintf('It has been %s since the webhook cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been %s since the webhook cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been %s since the webhook cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -86,10 +86,10 @@ class WebhookCronjob extends AbstractCronjob event(new RequestedSendWebhookMessages()); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Send webhook messages cron job fired successfully.'; + $this->message = 'Send webhook messages cron job fired successfully.'; FireflyConfig::set('last_webhook_job', (int) $this->date->format('U')); Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); diff --git a/app/Support/Debug/Timer.php b/app/Support/Debug/Timer.php index b2d58f4353..a38e32a79d 100644 --- a/app/Support/Debug/Timer.php +++ b/app/Support/Debug/Timer.php @@ -28,8 +28,8 @@ use Illuminate\Support\Facades\Log; class Timer { - private static null|Timer $instance = null; - private array $times = []; + private static ?Timer $instance = null; + private array $times = []; private function __construct() { diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index a83a9b6184..a01e0a93c6 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -42,13 +42,13 @@ class ExpandedForm * * @throws FireflyException */ - public function amountNoCurrency(string $name, $value = null, null|array $options = null): string + public function amountNoCurrency(string $name, $value = null, ?array $options = null): string { $options ??= []; - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; unset($options['currency'], $options['placeholder']); @@ -62,7 +62,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); @@ -79,21 +79,21 @@ class ExpandedForm * * @throws FireflyException */ - public function checkbox(string $name, null|int $value = null, $checked = null, null|array $options = null): string + public function checkbox(string $name, ?int $value = null, $checked = null, ?array $options = null): string { $options ??= []; $value ??= 1; $options['checked'] = true === $checked; if (app('session')->has('preFilled')) { - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); $options['checked'] = $preFilled[$name] ?? $options['checked']; } - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); unset($options['placeholder'], $options['autocomplete'], $options['class']); @@ -103,7 +103,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); @@ -120,7 +120,7 @@ class ExpandedForm * * @throws FireflyException */ - public function date(string $name, $value = null, null|array $options = null): string + public function date(string $name, $value = null, ?array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -143,7 +143,7 @@ class ExpandedForm /** * @throws FireflyException */ - public function file(string $name, null|array $options = null): string + public function file(string $name, ?array $options = null): string { $options ??= []; $label = $this->label($name, $options); @@ -167,9 +167,9 @@ class ExpandedForm * * @throws FireflyException */ - public function integer(string $name, $value = null, null|array $options = null): string + public function integer(string $name, $value = null, ?array $options = null): string { - $options ??= []; + $options ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -182,7 +182,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render integer(): %s', $e->getMessage())); @@ -199,7 +199,7 @@ class ExpandedForm * * @throws FireflyException */ - public function location(string $name, $value = null, null|array $options = null): string + public function location(string $name, $value = null, ?array $options = null): string { $options ??= []; $label = $this->label($name, $options); @@ -213,7 +213,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render location(): %s', $e->getMessage())); @@ -227,16 +227,16 @@ class ExpandedForm public function makeSelectListWithEmpty(Collection $set): array { - $selectList = []; + $selectList = []; $selectList[0] = '(none)'; - $fields = ['title', 'name', 'description']; + $fields = ['title', 'name', 'description']; /** @var Model $entry */ foreach ($set as $entry) { // All Eloquent models have an ID - $entryId = $entry->id; - $current = $entry->toArray(); - $title = null; + $entryId = $entry->id; + $current = $entry->toArray(); + $title = null; foreach ($fields as $field) { if (array_key_exists($field, $current) && null === $title) { $title = $current[$field]; @@ -253,13 +253,13 @@ class ExpandedForm * * @throws FireflyException */ - public function objectGroup($value = null, null|array $options = null): string + public function objectGroup($value = null, ?array $options = null): string { - $name = 'object_group'; - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $name = 'object_group'; + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['rows'] = 4; if (null === $value) { @@ -272,7 +272,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); @@ -304,7 +304,7 @@ class ExpandedForm /** * @throws FireflyException */ - public function password(string $name, null|array $options = null): string + public function password(string $name, ?array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -325,7 +325,7 @@ class ExpandedForm /** * @throws FireflyException */ - public function passwordWithValue(string $name, string $value, null|array $options = null): string + public function passwordWithValue(string $name, string $value, ?array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -337,7 +337,7 @@ class ExpandedForm 'value' => $value, 'name' => $name, 'label' => $label, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); @@ -356,12 +356,12 @@ class ExpandedForm * * @throws FireflyException */ - public function percentage(string $name, $value = null, null|array $options = null): string + public function percentage(string $name, $value = null, ?array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; unset($options['placeholder']); @@ -371,7 +371,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render percentage(): %s', $e->getMessage())); @@ -388,7 +388,7 @@ class ExpandedForm * * @throws FireflyException */ - public function staticText(string $name, $value, null|array $options = null): string + public function staticText(string $name, $value, ?array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -411,7 +411,7 @@ class ExpandedForm * * @throws FireflyException */ - public function text(string $name, $value = null, null|array $options = null): string + public function text(string $name, $value = null, ?array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -435,12 +435,12 @@ class ExpandedForm * * @throws FireflyException */ - public function textarea(string $name, $value = null, null|array $options = null): string + public function textarea(string $name, $value = null, ?array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['rows'] = 4; if (null === $value) { @@ -453,7 +453,7 @@ class ExpandedForm 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render textarea(): %s', $e->getMessage())); diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index be93d46414..30107f2c8f 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -77,15 +77,15 @@ class ExportDataGenerator private Collection $accounts; private Carbon $end; - 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 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 @@ -93,9 +93,9 @@ class ExportDataGenerator public function __construct() { $this->accounts = new Collection(); - $this->start = today(config('app.timezone')); + $this->start = today(config('app.timezone')); $this->start->subYear(); - $this->end = today(config('app.timezone')); + $this->end = today(config('app.timezone')); } /** @@ -232,7 +232,7 @@ class ExportDataGenerator */ private function exportAccounts(): string { - $header = [ + $header = [ 'user_id', 'account_id', 'created_at', @@ -249,18 +249,18 @@ class ExportDataGenerator 'cc_payment_date', 'in_net_worth', 'interest', - 'interest_period' + 'interest_period', ]; /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); $allAccounts = $repository->getAccountsByType([]); $records = []; /** @var Account $account */ foreach ($allAccounts as $account) { - $currency = $repository->getAccountCurrency($account); + $currency = $repository->getAccountCurrency($account); $records[] = [ $this->user->id, $account->id, @@ -278,12 +278,12 @@ class ExportDataGenerator $repository->getMetaValue($account, 'cc_monthly_payment_date'), $repository->getMetaValue($account, 'include_net_worth'), $repository->getMetaValue($account, 'interest'), - $repository->getMetaValue($account, 'interest_period') + $repository->getMetaValue($account, 'interest_period'), ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -316,8 +316,8 @@ class ExportDataGenerator /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($this->user); - $bills = $repository->getBills(); - $header = [ + $bills = $repository->getBills(); + $header = [ 'user_id', 'bill_id', 'created_at', @@ -329,9 +329,9 @@ class ExportDataGenerator 'date', 'repeat_freq', 'skip', - 'active' + 'active', ]; - $records = []; + $records = []; /** @var Bill $bill */ foreach ($bills as $bill) { @@ -347,12 +347,12 @@ class ExportDataGenerator $bill->date->format('Y-m-d'), $bill->repeat_freq, $bill->skip, - $bill->active + $bill->active, ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -382,13 +382,13 @@ class ExportDataGenerator */ private function exportBudgets(): string { - $header = ['user_id', 'budget_id', 'name', 'active', 'order', 'start_date', 'end_date', 'currency_code', 'amount']; + $header = ['user_id', 'budget_id', 'name', 'active', 'order', 'start_date', 'end_date', 'currency_code', 'amount']; $budgetRepos = app(BudgetRepositoryInterface::class); $budgetRepos->setUser($this->user); - $limitRepos = app(BudgetLimitRepositoryInterface::class); - $budgets = $budgetRepos->getBudgets(); - $records = []; + $limitRepos = app(BudgetLimitRepositoryInterface::class); + $budgets = $budgetRepos->getBudgets(); + $records = []; /** @var Budget $budget */ foreach ($budgets as $budget) { @@ -405,13 +405,13 @@ class ExportDataGenerator $limit->start_date->format('Y-m-d'), $limit->end_date->format('Y-m-d'), $limit->transactionCurrency->code, - $limit->amount + $limit->amount, ]; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -441,10 +441,10 @@ class ExportDataGenerator */ private function exportCategories(): string { - $header = ['user_id', 'category_id', 'created_at', 'updated_at', 'name']; + $header = ['user_id', 'category_id', 'created_at', 'updated_at', 'name']; /** @var CategoryRepositoryInterface $catRepos */ - $catRepos = app(CategoryRepositoryInterface::class); + $catRepos = app(CategoryRepositoryInterface::class); $catRepos->setUser($this->user); $records = []; @@ -456,7 +456,7 @@ class ExportDataGenerator } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -487,14 +487,14 @@ class ExportDataGenerator private function exportPiggies(): string { /** @var PiggyBankRepositoryInterface $piggyRepos */ - $piggyRepos = app(PiggyBankRepositoryInterface::class); + $piggyRepos = app(PiggyBankRepositoryInterface::class); $piggyRepos->setUser($this->user); /** @var AccountRepositoryInterface $accountRepos */ $accountRepos = app(AccountRepositoryInterface::class); $accountRepos->setUser($this->user); - $header = [ + $header = [ 'user_id', 'piggy_bank_id', 'created_at', @@ -508,16 +508,16 @@ class ExportDataGenerator 'start_date', 'target_date', 'order', - 'active' + 'active', ]; - $records = []; - $piggies = $piggyRepos->getPiggyBanks(); + $records = []; + $piggies = $piggyRepos->getPiggyBanks(); /** @var PiggyBank $piggy */ foreach ($piggies as $piggy) { $repetition = $piggyRepos->getRepetition($piggy); $currency = $accountRepos->getAccountCurrency($piggy->account); - $records[] = [ + $records[] = [ $this->user->id, $piggy->id, $piggy->created_at->toAtomString(), @@ -531,12 +531,12 @@ class ExportDataGenerator $piggy->start_date?->format('Y-m-d'), $piggy->target_date?->format('Y-m-d'), $piggy->order, - $piggy->active + $piggy->active, ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -569,7 +569,7 @@ class ExportDataGenerator /** @var RecurringRepositoryInterface $recurringRepos */ $recurringRepos = app(RecurringRepositoryInterface::class); $recurringRepos->setUser($this->user); - $header = [ + $header = [ // recurrence: 'user_id', 'recurrence_id', @@ -603,10 +603,10 @@ class ExportDataGenerator 'category', 'budget', 'piggy_bank', - 'tags' + 'tags', ]; - $records = []; - $recurrences = $recurringRepos->get(); + $records = []; + $recurrences = $recurringRepos->get(); /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { @@ -625,7 +625,7 @@ class ExportDataGenerator $recurrence->latest_date?->format('Y-m-d'), $recurrence->repetitions, $recurrence->apply_rules, - $recurrence->active + $recurrence->active, ]; // add new row for each repetition @@ -652,7 +652,7 @@ class ExportDataGenerator $repetition->repetition_type, $repetition->repetition_moment, $repetition->repetition_skip, - $repetition->weekend + $repetition->weekend, ]; } @@ -663,7 +663,7 @@ class ExportDataGenerator $piggyBankId = $recurringRepos->getPiggyBank($transaction); $tags = $recurringRepos->getTags($transaction); - $records[] = [ + $records[] = [ // recurrence $this->user->id, $recurrence->id, @@ -698,12 +698,12 @@ class ExportDataGenerator $categoryName, $budgetId, $piggyBankId, - implode(',', $tags) + implode(',', $tags), ]; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -755,16 +755,16 @@ class ExportDataGenerator 'action_value', 'action_order', 'action_active', - 'action_stop_processing' + 'action_stop_processing', ]; $ruleRepos = app(RuleRepositoryInterface::class); $ruleRepos->setUser($this->user); - $rules = $ruleRepos->getAll(); - $records = []; + $rules = $ruleRepos->getAll(); + $records = []; /** @var Rule $rule */ foreach ($rules as $rule) { - $entry = [ + $entry = [ $this->user->id, $rule->id, 'rule', @@ -786,13 +786,13 @@ class ExportDataGenerator null, null, null, - null + null, ]; $records[] = $entry; /** @var RuleTrigger $trigger */ foreach ($rule->ruleTriggers as $trigger) { - $entry = [ + $entry = [ $this->user->id, $rule->id, 'trigger', @@ -814,14 +814,14 @@ class ExportDataGenerator null, null, null, - null + null, ]; $records[] = $entry; } /** @var RuleAction $action */ foreach ($rule->ruleActions as $action) { - $entry = [ + $entry = [ $this->user->id, $rule->id, 'action', @@ -843,14 +843,14 @@ class ExportDataGenerator $action->action_value, $action->order, $action->active, - $action->stop_processing + $action->stop_processing, ]; $records[] = $entry; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -882,12 +882,12 @@ class ExportDataGenerator */ private function exportTags(): string { - $header = ['user_id', 'tag_id', 'created_at', 'updated_at', 'tag', 'date', 'description', 'latitude', 'longitude', 'zoom_level']; + $header = ['user_id', 'tag_id', 'created_at', 'updated_at', 'tag', 'date', 'description', 'latitude', 'longitude', 'zoom_level']; $tagRepos = app(TagRepositoryInterface::class); $tagRepos->setUser($this->user); - $tags = $tagRepos->get(); - $records = []; + $tags = $tagRepos->get(); + $records = []; /** @var Tag $tag */ foreach ($tags as $tag) { @@ -901,12 +901,12 @@ class ExportDataGenerator $tag->description, $tag->latitude, $tag->longitude, - $tag->zoomLevel + $tag->zoomLevel, ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -938,7 +938,7 @@ class ExportDataGenerator { Log::debug('Will now export transactions.'); // TODO better place for keys? - $header = [ + $header = [ 'user_id', 'group_id', 'journal_id', @@ -966,14 +966,14 @@ class ExportDataGenerator 'budget', 'bill', 'tags', - 'notes' + 'notes', ]; $metaFields = config('firefly.journal_meta_fields'); $header = array_merge($header, $metaFields); $primary = Amount::getPrimaryCurrency(); - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user); $collector ->setRange($this->start, $this->end) @@ -982,18 +982,19 @@ class ExportDataGenerator ->withBillInformation() ->withBudgetInformation() ->withTagInformation() - ->withNotes(); + ->withNotes() + ; if (0 !== $this->accounts->count()) { $collector->setAccounts($this->accounts); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // get repository for meta data: $repository = app(TransactionGroupRepositoryInterface::class); $repository->setUser($this->user); - $records = []; + $records = []; /** @var array $journal */ foreach ($journals as $journal) { @@ -1033,7 +1034,7 @@ class ExportDataGenerator : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places); } - $records[] = [ + $records[] = [ $journal['user_id'], $journal['transaction_group_id'], $journal['transaction_journal_id'], @@ -1096,12 +1097,12 @@ class ExportDataGenerator // recurring transactions $metaData['recurrence_total'], - $metaData['recurrence_count'] + $metaData['recurrence_count'], ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index 46fdeda41f..94f004ab5c 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -39,7 +39,7 @@ class FireflyConfig { public function delete(string $name): void { - $fullName = 'ff3-config-' . $name; + $fullName = 'ff3-config-'.$name; if (Cache::has($fullName)) { Cache::forget($fullName); } @@ -51,9 +51,9 @@ class FireflyConfig * * @throws FireflyException */ - public function get(string $name, mixed $default = null): null|Configuration + public function get(string $name, mixed $default = null): ?Configuration { - $fullName = 'ff3-config-' . $name; + $fullName = 'ff3-config-'.$name; if (Cache::has($fullName)) { return Cache::get($fullName); } @@ -78,7 +78,7 @@ class FireflyConfig return $this->set($name, $default); } - public function getEncrypted(string $name, mixed $default = null): null|Configuration + public function getEncrypted(string $name, mixed $default = null): ?Configuration { $result = $this->get($name, $default); if (!$result instanceof Configuration) { @@ -101,7 +101,7 @@ class FireflyConfig return $result; } - public function getFresh(string $name, mixed $default = null): null|Configuration + public function getFresh(string $name, mixed $default = null): ?Configuration { $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); if (null !== $config) { @@ -134,7 +134,7 @@ class FireflyConfig $config = Configuration::whereName($name)->whereNull('deleted_at')->first(); } catch (QueryException $e) { Log::error($e->getMessage()); - $item = new Configuration(); + $item = new Configuration(); $item->name = $name; $item->data = $value; @@ -142,17 +142,17 @@ class FireflyConfig } if (null === $config) { - $item = new Configuration(); + $item = new Configuration(); $item->name = $name; $item->data = $value; $item->save(); - Cache::forget('ff3-config-' . $name); + Cache::forget('ff3-config-'.$name); return $item; } $config->data = $value; $config->save(); - Cache::forget('ff3-config-' . $name); + Cache::forget('ff3-config-'.$name); return $config; } diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index f5663024c0..d4e5d0e25e 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -46,19 +46,19 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. */ - public function activeDepositDestinations(string $name, mixed $value = null, null|array $options = null): string + public function activeDepositDestinations(string $name, mixed $value = null, ?array $options = null): string { - $types = [ + $types = [ AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; - $repository = $this->getAccountRepository(); - $grouped = $this->getAccountsGrouped($types, $repository); - $cash = $repository->getCashAccount(); - $key = (string) trans('firefly.cash_account_type'); + $repository = $this->getAccountRepository(); + $grouped = $this->getAccountsGrouped($types, $repository); + $cash = $repository->getCashAccount(); + $key = (string) trans('firefly.cash_account_type'); $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); @@ -67,20 +67,20 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. */ - public function activeWithdrawalDestinations(string $name, mixed $value = null, null|array $options = null): string + public function activeWithdrawalDestinations(string $name, mixed $value = null, ?array $options = null): string { - $types = [ + $types = [ AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, - AccountTypeEnum::EXPENSE->value + AccountTypeEnum::EXPENSE->value, ]; - $repository = $this->getAccountRepository(); - $grouped = $this->getAccountsGrouped($types, $repository); + $repository = $this->getAccountRepository(); + $grouped = $this->getAccountsGrouped($types, $repository); - $cash = $repository->getCashAccount(); - $key = (string) trans('firefly.cash_account_type'); + $cash = $repository->getCashAccount(); + $key = (string) trans('firefly.cash_account_type'); $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); @@ -91,23 +91,23 @@ class AccountForm * * @throws FireflyException */ - public function assetAccountCheckList(string $name, null|array $options = null): string + public function assetAccountCheckList(string $name, ?array $options = null): string { - $options ??= []; + $options ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); $selected = request()->old($name) ?? []; // get all asset accounts: - $types = [ + $types = [ AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::DEBT->value + AccountTypeEnum::DEBT->value, ]; - $grouped = $this->getAccountsGrouped($types); + $grouped = $this->getAccountsGrouped($types); unset($options['class']); @@ -118,7 +118,7 @@ class AccountForm 'name' => $name, 'label' => $label, 'options' => $options, - 'grouped' => $grouped + 'grouped' => $grouped, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); @@ -135,7 +135,7 @@ class AccountForm * * @param mixed $value */ - public function assetAccountList(string $name, $value = null, null|array $options = null): string + public function assetAccountList(string $name, $value = null, ?array $options = null): string { $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]; $grouped = $this->getAccountsGrouped($types); @@ -148,14 +148,14 @@ class AccountForm * * @param mixed $value */ - public function assetLiabilityMultiAccountList(string $name, $value = null, null|array $options = null): string + public function assetLiabilityMultiAccountList(string $name, $value = null, ?array $options = null): string { $types = [ AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::LOAN->value + AccountTypeEnum::LOAN->value, ]; $grouped = $this->getAccountsGrouped($types); @@ -167,21 +167,21 @@ class AccountForm * * @param mixed $value */ - public function longAccountList(string $name, $value = null, null|array $options = null): string + public function longAccountList(string $name, $value = null, ?array $options = null): string { $types = [ AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::LOAN->value + AccountTypeEnum::LOAN->value, ]; $grouped = $this->getAccountsGrouped($types); return $this->select($name, $grouped, $value, $options); } - private function getAccountsGrouped(array $types, null|AccountRepositoryInterface $repository = null): array + private function getAccountsGrouped(array $types, ?AccountRepositoryInterface $repository = null): array { if (!$repository instanceof AccountRepositoryInterface) { $repository = $this->getAccountRepository(); @@ -192,7 +192,7 @@ class AccountForm /** @var Account $account */ foreach ($accountList as $account) { - $role = (string) $repository->getMetaValue($account, 'account_role'); + $role = (string) $repository->getMetaValue($account, 'account_role'); if (in_array($account->accountType->type, $liabilityTypes, true)) { $role = sprintf('l_%s', $account->accountType->type); } @@ -205,7 +205,7 @@ class AccountForm $role = 'revenue_account'; } } - $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = $account->name; } diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index cbb198ec58..f8d346df55 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -47,7 +47,7 @@ class CurrencyForm * * @throws FireflyException */ - public function amount(string $name, $value = null, null|array $options = null): string + public function amount(string $name, $value = null, ?array $options = null): string { return $this->currencyField($name, 'amount', $value, $options); } @@ -59,7 +59,7 @@ class CurrencyForm * * @throws FireflyException */ - public function balanceAll(string $name, $value = null, null|array $options = null): string + public function balanceAll(string $name, $value = null, ?array $options = null): string { return $this->allCurrencyField($name, 'balance', $value, $options); } @@ -69,18 +69,18 @@ class CurrencyForm * * @param mixed $value */ - public function currencyList(string $name, $value = null, null|array $options = null): string + public function currencyList(string $name, $value = null, ?array $options = null): string { /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); // get all currencies: - $list = $currencyRepos->get(); - $array = []; + $list = $currencyRepos->get(); + $array = []; /** @var TransactionCurrency $currency */ foreach ($list as $currency) { - $array[$currency->id] = $currency->name . ' (' . $currency->symbol . ')'; + $array[$currency->id] = $currency->name.' ('.$currency->symbol.')'; } return $this->select($name, $array, $value, $options); @@ -91,18 +91,18 @@ class CurrencyForm * * @param mixed $value */ - public function currencyListEmpty(string $name, $value = null, null|array $options = null): string + public function currencyListEmpty(string $name, $value = null, ?array $options = null): string { /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); // get all currencies: - $list = $currencyRepos->get(); - $array = [0 => (string) trans('firefly.no_currency')]; + $list = $currencyRepos->get(); + $array = [0 => (string) trans('firefly.no_currency')]; /** @var TransactionCurrency $currency */ foreach ($list as $currency) { - $array[$currency->id] = $currency->name . ' (' . $currency->symbol . ')'; + $array[$currency->id] = $currency->name.' ('.$currency->symbol.')'; } return $this->select($name, $array, $value, $options); @@ -115,26 +115,26 @@ class CurrencyForm * * @throws FireflyException */ - protected function allCurrencyField(string $name, string $view, $value = null, null|array $options = null): string + protected function allCurrencyField(string $name, string $view, $value = null, ?array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; $primaryCurrency = $options['currency'] ?? Amount::getPrimaryCurrency(); /** @var Collection $currencies */ - $currencies = Amount::getAllCurrencies(); + $currencies = Amount::getAllCurrencies(); unset($options['currency'], $options['placeholder']); // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); if (!is_array($preFilled)) { $preFilled = []; } - $key = 'amount_currency_id_' . $name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; + $key = 'amount_currency_id_'.$name; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -154,14 +154,14 @@ class CurrencyForm } try { - $html = view('form.' . $view, [ + $html = view('form.'.$view, [ 'primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); @@ -176,25 +176,25 @@ class CurrencyForm /** * @throws FireflyException */ - protected function currencyField(string $name, string $view, mixed $value = null, null|array $options = null): string + protected function currencyField(string $name, string $view, mixed $value = null, ?array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; $primaryCurrency = $options['currency'] ?? Amount::getPrimaryCurrency(); /** @var Collection $currencies */ - $currencies = Amount::getCurrencies(); + $currencies = Amount::getCurrencies(); unset($options['currency'], $options['placeholder']); // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); if (!is_array($preFilled)) { $preFilled = []; } - $key = 'amount_currency_id_' . $name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; + $key = 'amount_currency_id_'.$name; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -214,14 +214,14 @@ class CurrencyForm } try { - $html = view('form.' . $view, [ + $html = view('form.'.$view, [ 'primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, - 'options' => $options + 'options' => $options, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index ba2fa555ff..1dbd4e6074 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -35,9 +35,9 @@ use Throwable; */ trait FormSupport { - public function multiSelect(string $name, null|array $list = null, mixed $selected = null, null|array $options = null): string + public function multiSelect(string $name, ?array $list = null, mixed $selected = null, ?array $options = null): string { - $list ??= []; + $list ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -52,7 +52,7 @@ trait FormSupport 'label' => $label, 'selected' => $selected, 'options' => $options, - 'list' => $list + 'list' => $list, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render multi-select(): %s', $e->getMessage())); @@ -65,9 +65,9 @@ trait FormSupport /** * @param mixed $selected */ - public function select(string $name, null|array $list = null, $selected = null, null|array $options = null): string + public function select(string $name, ?array $list = null, $selected = null, ?array $options = null): string { - $list ??= []; + $list ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -81,7 +81,7 @@ trait FormSupport 'label' => $label, 'selected' => $selected, 'options' => $options, - 'list' => $list + 'list' => $list, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); @@ -94,14 +94,14 @@ trait FormSupport /** * @param mixed $label */ - protected function expandOptionArray(string $name, $label, null|array $options = null): array + protected function expandOptionArray(string $name, $label, ?array $options = null): array { $options ??= []; - $name = str_replace('[]', '', $name); - $options['class'] = 'form-control'; - $options['id'] = 'ffInput_' . $name; + $name = str_replace('[]', '', $name); + $options['class'] = 'form-control'; + $options['id'] = 'ffInput_'.$name; $options['autocomplete'] = 'off'; - $options['placeholder'] = ucfirst((string) $label); + $options['placeholder'] = ucfirst((string) $label); return $options; } @@ -152,7 +152,7 @@ trait FormSupport return 'form-group'; } - protected function label(string $name, null|array $options = null): string + protected function label(string $name, ?array $options = null): string { $options ??= []; if (array_key_exists('label', $options)) { @@ -160,6 +160,6 @@ trait FormSupport } $name = str_replace('[]', '', $name); - return (string) trans('form.' . $name); + return (string) trans('form.'.$name); } } diff --git a/app/Support/Form/PiggyBankForm.php b/app/Support/Form/PiggyBankForm.php index 27e2324b49..6a72123acf 100644 --- a/app/Support/Form/PiggyBankForm.php +++ b/app/Support/Form/PiggyBankForm.php @@ -41,7 +41,7 @@ class PiggyBankForm * * @param mixed $value */ - public function piggyBankList(string $name, $value = null, null|array $options = null): string + public function piggyBankList(string $name, $value = null, ?array $options = null): string { // make repositories /** @var PiggyBankRepositoryInterface $repository */ @@ -53,9 +53,9 @@ class PiggyBankForm /** @var PiggyBank $piggy */ foreach ($piggyBanks as $piggy) { - $group = $piggy->objectGroups->first(); - $groupTitle = null; - $groupOrder = 0; + $group = $piggy->objectGroups->first(); + $groupTitle = null; + $groupOrder = 0; if (null !== $group) { $groupTitle = $group->title; $groupOrder = $group->order; @@ -65,7 +65,7 @@ class PiggyBankForm } ksort($subList); foreach ($subList as $info) { - $groupTitle = $info['group']['title']; + $groupTitle = $info['group']['title']; $array[$groupTitle] = $info['piggies']; } diff --git a/app/Support/Form/RuleForm.php b/app/Support/Form/RuleForm.php index b84d4e6ad0..0f9cff55c3 100644 --- a/app/Support/Form/RuleForm.php +++ b/app/Support/Form/RuleForm.php @@ -35,14 +35,14 @@ class RuleForm { use FormSupport; - public function ruleGroupList(string $name, mixed $value = null, null|array $options = null): string + public function ruleGroupList(string $name, mixed $value = null, ?array $options = null): string { /** @var RuleGroupRepositoryInterface $groupRepos */ $groupRepos = app(RuleGroupRepositoryInterface::class); // get all currencies: - $list = $groupRepos->get(); - $array = []; + $list = $groupRepos->get(); + $array = []; /** @var RuleGroup $group */ foreach ($list as $group) { @@ -52,17 +52,17 @@ class RuleForm return $this->select($name, $array, $value, $options); } - public function ruleGroupListWithEmpty(string $name, $value = null, null|array $options = null): string + public function ruleGroupListWithEmpty(string $name, $value = null, ?array $options = null): string { $options ??= []; $options['class'] = 'form-control'; /** @var RuleGroupRepositoryInterface $groupRepos */ - $groupRepos = app(RuleGroupRepositoryInterface::class); + $groupRepos = app(RuleGroupRepositoryInterface::class); // get all currencies: - $list = $groupRepos->get(); - $array = [0 => (string) trans('firefly.none_in_select_list')]; + $list = $groupRepos->get(); + $array = [0 => (string) trans('firefly.none_in_select_list')]; /** @var RuleGroup $group */ foreach ($list as $group) { diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.php index 170d314b2c..3d2594a0d6 100644 --- a/app/Support/Http/Api/AccountBalanceGrouped.php +++ b/app/Support/Http/Api/AccountBalanceGrouped.php @@ -45,7 +45,7 @@ class AccountBalanceGrouped private array $currencies = []; private array $data = []; private Carbon $end; - private array $journals = []; + private array $journals = []; private string $preferredRange; private TransactionCurrency $primary; private Carbon $start; @@ -66,7 +66,7 @@ class AccountBalanceGrouped /** @var array $currency */ foreach ($this->data as $currency) { // income and expense array prepped: - $income = [ + $income = [ 'label' => 'earned', 'currency_id' => (string) $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -83,9 +83,9 @@ class AccountBalanceGrouped 'type' => 'line', 'period' => $this->preferredRange, 'entries' => [], - 'pc_entries' => [] + 'pc_entries' => [], ]; - $expense = [ + $expense = [ 'label' => 'spent', 'currency_id' => (string) $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -102,27 +102,27 @@ class AccountBalanceGrouped 'yAxisID' => 0, 'period' => $this->preferredRange, 'entries' => [], - 'pc_entries' => [] + 'pc_entries' => [], ]; // loop all possible periods between $start and $end, and add them to the correct dataset. $currentStart = clone $this->start; while ($currentStart <= $this->end) { - $key = $currentStart->format($this->carbonFormat); - $label = $currentStart->toAtomString(); + $key = $currentStart->format($this->carbonFormat); + $label = $currentStart->toAtomString(); // normal entries - $income['entries'][$label] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']); - $expense['entries'][$label] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']); + $income['entries'][$label] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']); + $expense['entries'][$label] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']); // converted entries - $income['pc_entries'][$label] = Steam::bcround($currency[$key]['pc_earned'] ?? '0', $currency['primary_currency_decimal_places']); + $income['pc_entries'][$label] = Steam::bcround($currency[$key]['pc_earned'] ?? '0', $currency['primary_currency_decimal_places']); $expense['pc_entries'][$label] = Steam::bcround($currency[$key]['pc_spent'] ?? '0', $currency['primary_currency_decimal_places']); // next loop - $currentStart = Navigation::addPeriod($currentStart, $this->preferredRange, 0); + $currentStart = Navigation::addPeriod($currentStart, $this->preferredRange, 0); } - $chartData[] = $income; - $chartData[] = $expense; + $chartData[] = $income; + $chartData[] = $expense; } return $chartData; @@ -163,14 +163,14 @@ class AccountBalanceGrouped public function setPreferredRange(string $preferredRange): void { $this->preferredRange = $preferredRange; - $this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange); + $this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange); } public function setPrimary(TransactionCurrency $primary): void { - $this->primary = $primary; - $primaryCurrencyId = $primary->id; - $this->currencies = [$primary->id => $primary]; // currency cache + $this->primary = $primary; + $primaryCurrencyId = $primary->id; + $this->currencies = [$primary->id => $primary]; // currency cache $this->data[$primaryCurrencyId] = [ 'currency_id' => (string) $primaryCurrencyId, 'currency_symbol' => $primary->symbol, @@ -181,7 +181,7 @@ class AccountBalanceGrouped 'primary_currency_symbol' => $primary->symbol, 'primary_currency_code' => $primary->code, 'primary_currency_name' => $primary->name, - 'primary_currency_decimal_places' => $primary->decimal_places + 'primary_currency_decimal_places' => $primary->decimal_places, ]; } @@ -194,16 +194,16 @@ class AccountBalanceGrouped { $currencyId = (int) $journal['currency_id']; $this->data[$currencyId] ??= [ - 'currency_id' => (string) $currencyId, - 'currency_symbol' => $journal['currency_symbol'], - 'currency_code' => $journal['currency_code'], - 'currency_name' => $journal['currency_name'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_id' => (string) $currencyId, + 'currency_symbol' => $journal['currency_symbol'], + 'currency_code' => $journal['currency_code'], + 'currency_name' => $journal['currency_name'], + 'currency_decimal_places' => $journal['currency_decimal_places'], // primary currency info (could be the same) 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_code' => $this->primary->code, 'primary_currency_symbol' => $this->primary->symbol, - 'primary_currency_decimal_places' => $this->primary->decimal_places + 'primary_currency_decimal_places' => $this->primary->decimal_places, ]; } @@ -258,9 +258,9 @@ class AccountBalanceGrouped private function processJournal(array $journal): void { // format the date according to the period - $period = $journal['date']->format($this->carbonFormat); - $currencyId = (int) $journal['currency_id']; - $currency = $this->findCurrency($currencyId); + $period = $journal['date']->format($this->carbonFormat); + $currencyId = (int) $journal['currency_id']; + $currency = $this->findCurrency($currencyId); // set the array with monetary info, if it does not exist. $this->createDefaultDataEntry($journal); @@ -268,12 +268,12 @@ class AccountBalanceGrouped $this->createDefaultPeriodEntry($journal); // is this journal's amount in- our outgoing? - $key = $this->getDataKey($journal); - $amount = 'spent' === $key ? Steam::negative($journal['amount']) : Steam::positive($journal['amount']); + $key = $this->getDataKey($journal); + $amount = 'spent' === $key ? Steam::negative($journal['amount']) : Steam::positive($journal['amount']); // get conversion rate - $rate = $this->getRate($currency, $journal['date']); - $amountConverted = bcmul($amount, $rate); + $rate = $this->getRate($currency, $journal['date']); + $amountConverted = bcmul($amount, $rate); // perhaps transaction already has the foreign amount in the primary currency. if ((int) $journal['foreign_currency_id'] === $this->primary->id) { @@ -282,10 +282,10 @@ class AccountBalanceGrouped } // add normal entry - $this->data[$currencyId][$period][$key] = bcadd((string) $this->data[$currencyId][$period][$key], $amount); + $this->data[$currencyId][$period][$key] = bcadd((string) $this->data[$currencyId][$period][$key], $amount); // add converted entry - $convertedKey = sprintf('pc_%s', $key); + $convertedKey = sprintf('pc_%s', $key); $this->data[$currencyId][$period][$convertedKey] = bcadd((string) $this->data[$currencyId][$period][$convertedKey], $amountConverted); } } diff --git a/app/Support/Http/Api/AccountFilter.php b/app/Support/Http/Api/AccountFilter.php index c08ea05aff..538e229cdf 100644 --- a/app/Support/Http/Api/AccountFilter.php +++ b/app/Support/Http/Api/AccountFilter.php @@ -44,7 +44,7 @@ trait AccountFilter AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ], 'normal' => [ AccountTypeEnum::ASSET->value, @@ -52,7 +52,7 @@ trait AccountFilter AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ], 'asset' => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], 'cash' => [AccountTypeEnum::CASH->value], @@ -62,24 +62,24 @@ trait AccountFilter AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, - AccountTypeEnum::RECONCILIATION->value + AccountTypeEnum::RECONCILIATION->value, ], 'hidden' => [ AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, - AccountTypeEnum::RECONCILIATION->value + AccountTypeEnum::RECONCILIATION->value, ], 'liability' => [ AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value + AccountTypeEnum::CREDITCARD->value, ], 'liabilities' => [ AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value + AccountTypeEnum::CREDITCARD->value, ], AccountTypeEnum::DEFAULT->value => [AccountTypeEnum::DEFAULT->value], AccountTypeEnum::CASH->value => [AccountTypeEnum::CASH->value], @@ -108,7 +108,7 @@ trait AccountFilter 'credit card' => [AccountTypeEnum::CREDITCARD->value], 'credit-card' => [AccountTypeEnum::CREDITCARD->value], 'creditcard' => [AccountTypeEnum::CREDITCARD->value], - 'cc' => [AccountTypeEnum::CREDITCARD->value] + 'cc' => [AccountTypeEnum::CREDITCARD->value], ]; /** diff --git a/app/Support/Http/Api/CleansChartData.php b/app/Support/Http/Api/CleansChartData.php index f5c2f22ae1..0a352a6fd9 100644 --- a/app/Support/Http/Api/CleansChartData.php +++ b/app/Support/Http/Api/CleansChartData.php @@ -47,7 +47,7 @@ trait CleansChartData * @var array $array */ foreach ($data as $index => $array) { - $array = $this->cleanSingleArray($index, $array); + $array = $this->cleanSingleArray($index, $array); $return[] = $array; } diff --git a/app/Support/Http/Api/CollectsAccountsFromFilter.php b/app/Support/Http/Api/CollectsAccountsFromFilter.php index 0b87003b0f..0baeaa9098 100644 --- a/app/Support/Http/Api/CollectsAccountsFromFilter.php +++ b/app/Support/Http/Api/CollectsAccountsFromFilter.php @@ -56,7 +56,8 @@ trait CollectsAccountsFromFilter $defaultSet = $this->repository ->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]) ->pluck('id') - ->toArray(); + ->toArray() + ; $frontpage = Preferences::get('frontpageAccounts', $defaultSet); if (!(is_array($frontpage->data) && count($frontpage->data) > 0)) { @@ -74,7 +75,7 @@ trait CollectsAccountsFromFilter AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); } if ('assets' === $queryParameters['preselected'] || 'Asset account' === $queryParameters['preselected']) { diff --git a/app/Support/Http/Api/ExchangeRateConverter.php b/app/Support/Http/Api/ExchangeRateConverter.php index 6d8b5b9400..a198913941 100644 --- a/app/Support/Http/Api/ExchangeRateConverter.php +++ b/app/Support/Http/Api/ExchangeRateConverter.php @@ -129,7 +129,7 @@ class ExchangeRateConverter if ($cache->has()) { return (int) $cache->get(); } - $euro = Amount::getTransactionCurrencyByCode('EUR'); + $euro = Amount::getTransactionCurrencyByCode('EUR'); ++$this->queryCount; $cache->store($euro->id); @@ -145,13 +145,13 @@ class ExchangeRateConverter if ($euroId === $currency->id) { return '1'; } - $rate = $this->getFromDB($currency->id, $euroId, $date->format('Y-m-d')); + $rate = $this->getFromDB($currency->id, $euroId, $date->format('Y-m-d')); if (null !== $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')); + $rate = $this->getFromDB($euroId, $currency->id, $date->format('Y-m-d')); if (null !== $rate) { return bcdiv('1', $rate); @@ -171,14 +171,14 @@ class ExchangeRateConverter return '0'; } - private function getFromDB(int $from, int $to, string $date): null|string + private function getFromDB(int $from, int $to, string $date): ?string { if ($from === $to) { Log::debug('ExchangeRateConverter: From and to are the same, return "1".'); return '1'; } - $key = sprintf('cer-%d-%d-%s', $from, $to, $date); + $key = sprintf('cer-%d-%d-%s', $from, $to, $date); // perhaps the rate has been cached during this particular run $preparedRate = $this->prepared[$date][$from][$to] ?? null; @@ -188,7 +188,7 @@ class ExchangeRateConverter return $preparedRate; } - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($key); if ($cache->has()) { $rate = $cache->get(); @@ -201,15 +201,16 @@ class ExchangeRateConverter } /** @var null|CurrencyExchangeRate $result */ - $result = $this->userGroup + $result = $this->userGroup ->currencyExchangeRates() ->where('from_currency_id', $from) ->where('to_currency_id', $to) ->where('date', '<=', $date) ->orderBy('date', 'DESC') - ->first(); + ->first() + ; ++$this->queryCount; - $rate = (string) $result?->rate; + $rate = (string) $result?->rate; if ('' === $rate) { Log::debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date)); @@ -237,8 +238,8 @@ class ExchangeRateConverter */ private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string { - $key = $this->getCacheKey($from, $to, $date); - $res = Cache::get($key); + $key = $this->getCacheKey($from, $to, $date); + $res = Cache::get($key); // find in cache if (null !== $res) { @@ -248,7 +249,7 @@ class ExchangeRateConverter } // find in database - $rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d')); + $rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d')); if (null !== $rate) { Cache::forever($key, $rate); Log::debug(sprintf('ExchangeRateConverter: Return DB rate from %s to %s on %s.', $from->code, $to->code, $date->format('Y-m-d'))); @@ -257,7 +258,7 @@ class ExchangeRateConverter } // find reverse in database - $rate = $this->getFromDB($to->id, $from->id, $date->format('Y-m-d')); + $rate = $this->getFromDB($to->id, $from->id, $date->format('Y-m-d')); if (null !== $rate) { $rate = bcdiv('1', $rate); Cache::forever($key, $rate); diff --git a/app/Support/Http/Api/SummaryBalanceGrouped.php b/app/Support/Http/Api/SummaryBalanceGrouped.php index c69c6f7766..220793da4e 100644 --- a/app/Support/Http/Api/SummaryBalanceGrouped.php +++ b/app/Support/Http/Api/SummaryBalanceGrouped.php @@ -31,13 +31,13 @@ use Illuminate\Support\Facades\Log; class SummaryBalanceGrouped { - private const string SUM = 'sum'; + private const string SUM = 'sum'; private array $amounts = []; private array $currencies = []; private readonly CurrencyRepositoryInterface $currencyRepository; private TransactionCurrency $default; - private array $keys = [self::SUM]; + private array $keys = [self::SUM]; public function __construct() { @@ -47,13 +47,13 @@ class SummaryBalanceGrouped public function groupData(): array { Log::debug('Now going to group data.'); - $return = []; + $return = []; foreach ($this->keys as $key) { - $title = match ($key) { - 'sum' => 'balance', + $title = match ($key) { + 'sum' => 'balance', 'expense' => 'spent', - 'income' => 'earned', - default => 'something' + 'income' => 'earned', + default => 'something' }; $return[] = [ @@ -62,7 +62,7 @@ class SummaryBalanceGrouped 'currency_id' => (string) $this->default->id, 'currency_code' => $this->default->code, 'currency_symbol' => $this->default->symbol, - 'currency_decimal_places' => $this->default->decimal_places + 'currency_decimal_places' => $this->default->decimal_places, ]; } // loop 3: format amounts: @@ -72,16 +72,16 @@ class SummaryBalanceGrouped // skip primary entries. continue; } - $currencyId = (int) $currencyId; - $currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId); + $currencyId = (int) $currencyId; + $currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId); $this->currencies[$currencyId] = $currency; // create objects for big array. foreach ($this->keys as $key) { - $title = match ($key) { - 'sum' => 'balance', + $title = match ($key) { + 'sum' => 'balance', 'expense' => 'spent', - 'income' => 'earned', - default => 'something' + 'income' => 'earned', + default => 'something' }; $return[] = [ 'key' => sprintf('%s-in-%s', $title, $currency->code), @@ -89,7 +89,7 @@ class SummaryBalanceGrouped 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; } } @@ -101,34 +101,34 @@ class SummaryBalanceGrouped { Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); Log::debug(sprintf('Now in groupTransactions with key "%s" and %d journal(s)', $key, count($journals))); - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $this->keys[] = $key; - $multiplier = 'income' === $key ? '-1' : '1'; + $multiplier = 'income' === $key ? '-1' : '1'; /** @var array $journal */ foreach ($journals as $journal) { // transaction info: - $currencyId = (int) $journal['currency_id']; - $amount = bcmul((string) $journal['amount'], $multiplier); - $currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId); - $this->currencies[$currencyId] = $currency; - $pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount); + $currencyId = (int) $journal['currency_id']; + $amount = bcmul((string) $journal['amount'], $multiplier); + $currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId); + $this->currencies[$currencyId] = $currency; + $pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount); if ((int) $journal['foreign_currency_id'] === $this->default->id) { // use foreign amount instead $pcAmount = $journal['foreign_amount']; } // prep the arrays - $this->amounts[$key] ??= []; - $this->amounts[$key][$currencyId] ??= '0'; - $this->amounts[$key]['primary'] ??= '0'; + $this->amounts[$key] ??= []; + $this->amounts[$key][$currencyId] ??= '0'; + $this->amounts[$key]['primary'] ??= '0'; $this->amounts[self::SUM][$currencyId] ??= '0'; - $this->amounts[self::SUM]['primary'] ??= '0'; + $this->amounts[self::SUM]['primary'] ??= '0'; // add values: - $this->amounts[$key][$currencyId] = bcadd((string) $this->amounts[$key][$currencyId], $amount); + $this->amounts[$key][$currencyId] = bcadd((string) $this->amounts[$key][$currencyId], $amount); $this->amounts[self::SUM][$currencyId] = bcadd((string) $this->amounts[self::SUM][$currencyId], $amount); - $this->amounts[$key]['primary'] = bcadd((string) $this->amounts[$key]['primary'], (string) $pcAmount); - $this->amounts[self::SUM]['primary'] = bcadd((string) $this->amounts[self::SUM]['primary'], (string) $pcAmount); + $this->amounts[$key]['primary'] = bcadd((string) $this->amounts[$key]['primary'], (string) $pcAmount); + $this->amounts[self::SUM]['primary'] = bcadd((string) $this->amounts[self::SUM]['primary'], (string) $pcAmount); } $converter->summarize(); } diff --git a/app/Support/Http/Api/TransactionFilter.php b/app/Support/Http/Api/TransactionFilter.php index fb6802347e..107159fc98 100644 --- a/app/Support/Http/Api/TransactionFilter.php +++ b/app/Support/Http/Api/TransactionFilter.php @@ -37,7 +37,7 @@ trait TransactionFilter TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::OPENING_BALANCE->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ], TransactionTypeEnum::WITHDRAWAL->value => [TransactionTypeEnum::WITHDRAWAL->value], 'withdrawal' => [TransactionTypeEnum::WITHDRAWAL->value], @@ -61,8 +61,8 @@ trait TransactionFilter 'default' => [ TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, - TransactionTypeEnum::TRANSFER->value - ] + TransactionTypeEnum::TRANSFER->value, + ], ]; /** diff --git a/app/Support/Http/Api/ValidatesUserGroupTrait.php b/app/Support/Http/Api/ValidatesUserGroupTrait.php index a0423d7683..1b67e01658 100644 --- a/app/Support/Http/Api/ValidatesUserGroupTrait.php +++ b/app/Support/Http/Api/ValidatesUserGroupTrait.php @@ -59,8 +59,8 @@ trait ValidatesUserGroupTrait } /** @var User $user */ - $user = auth()->user(); - $groupId = 0; + $user = auth()->user(); + $groupId = 0; if (!$request->has('user_group_id')) { $groupId = (int) $user->user_group_id; Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $groupId)); @@ -71,7 +71,7 @@ trait ValidatesUserGroupTrait } /** @var UserGroupRepositoryInterface $repository */ - $repository = app(UserGroupRepositoryInterface::class); + $repository = app(UserGroupRepositoryInterface::class); $repository->setUser($user); $memberships = $repository->getMembershipsFromGroupId($groupId); @@ -82,14 +82,14 @@ trait ValidatesUserGroupTrait } // need to get the group from the membership: - $group = $repository->getById($groupId); + $group = $repository->getById($groupId); if (null === $group) { Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $groupId)); throw new AuthorizationException((string) trans('validation.belongs_user_or_user_group')); } Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $groupId, $group->title)); - $roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line + $roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line if (0 === count($roles)) { Log::debug('validateUserGroup: no roles defined, so no access.'); @@ -102,7 +102,7 @@ trait ValidatesUserGroupTrait if ($user->hasRoleInGroupOrOwner($group, $role)) { Log::debug(sprintf('validateUserGroup: User has role "%s" in group #%d, return the group.', $role->value, $groupId)); $this->userGroup = $group; - $this->user = $user; + $this->user = $user; return $group; } diff --git a/app/Support/Http/Controllers/AugumentData.php b/app/Support/Http/Controllers/AugumentData.php index 903eddee56..c8f0097643 100644 --- a/app/Support/Http/Controllers/AugumentData.php +++ b/app/Support/Http/Controllers/AugumentData.php @@ -56,10 +56,10 @@ trait AugumentData /** @var Account $expenseAccount */ foreach ($accounts as $expenseAccount) { - $collection = new Collection(); + $collection = new Collection(); $collection->push($expenseAccount); - $revenue = $repository->findByName($expenseAccount->name, [AccountTypeEnum::REVENUE->value]); + $revenue = $repository->findByName($expenseAccount->name, [AccountTypeEnum::REVENUE->value]); if (null !== $revenue) { $collection->push($revenue); } @@ -113,7 +113,7 @@ trait AugumentData AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::EXPENSE->value, - AccountTypeEnum::CASH->value + AccountTypeEnum::CASH->value, ]); $grouped = $accounts->groupBy('id')->toArray(); $return = []; @@ -124,7 +124,7 @@ trait AugumentData $return[$accountId] = $grouped[$accountId][0]['name']; } } - $return[0] = '(no name)'; + $return[0] = '(no name)'; return $return; } @@ -144,7 +144,7 @@ trait AugumentData $return[$budgetId] = $grouped[$budgetId][0]['name']; } } - $return[0] = (string) trans('firefly.no_budget'); + $return[0] = (string) trans('firefly.no_budget'); return $return; } @@ -166,7 +166,7 @@ trait AugumentData $return[$categoryId] = $grouped[$categoryId][0]['name']; } } - $return[0] = (string) trans('firefly.no_category'); + $return[0] = (string) trans('firefly.no_category'); return $return; } @@ -179,14 +179,14 @@ trait AugumentData Log::debug('In getLimits'); /** @var OperationsRepositoryInterface $opsRepository */ - $opsRepository = app(OperationsRepositoryInterface::class); + $opsRepository = app(OperationsRepositoryInterface::class); /** @var BudgetLimitRepositoryInterface $blRepository */ - $blRepository = app(BudgetLimitRepositoryInterface::class); + $blRepository = app(BudgetLimitRepositoryInterface::class); $end->endOfMonth(); // properties for cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($budget->id); @@ -197,39 +197,39 @@ trait AugumentData return $cache->get(); } - $set = $blRepository->getBudgetLimits($budget, $start, $end); + $set = $blRepository->getBudgetLimits($budget, $start, $end); $budgetCollection = new Collection()->push($budget); // merge sets based on a key, in case of convert to primary currency - $limits = new Collection(); + $limits = new Collection(); /** @var BudgetLimit $entry */ foreach ($set as $entry) { Log::debug(sprintf('Now at budget limit #%d', $entry->id)); - $currency = $entry->transactionCurrency; + $currency = $entry->transactionCurrency; if ($this->convertToPrimary) { // the sumExpenses method already handles this. $currency = $this->primaryCurrency; } // clone because these objects change each other. - $currentStart = clone $entry->start_date; - $currentEnd = null === $entry->end_date ? null : clone $entry->end_date; + $currentStart = clone $entry->start_date; + $currentEnd = null === $entry->end_date ? null : clone $entry->end_date; if (null === $currentEnd) { $currentEnd = clone $currentStart; $currentEnd->addMonth(); } // primary currency amount. - $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToPrimary); - $spent = $expenses[$currency->id]['sum'] ?? '0'; + $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToPrimary); + $spent = $expenses[$currency->id]['sum'] ?? '0'; $entry->pc_spent = $spent; // normal amount: - $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency); - $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; - $entry->spent = $spent; + $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency); + $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; + $entry->spent = $spent; $limits->push($entry); } @@ -248,7 +248,7 @@ trait AugumentData /** @var array $journal */ foreach ($array as $journal) { - $name = '(no name)'; + $name = '(no name)'; if (TransactionTypeEnum::WITHDRAWAL->value === $journal['transaction_type_type']) { $name = $journal['destination_account_name']; } @@ -271,13 +271,13 @@ trait AugumentData /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $total = $assets->merge($opposing); + $total = $assets->merge($opposing); $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setAccounts($total); - $journals = $collector->getExtractedJournals(); - $sum = ['grand_sum' => '0', 'per_currency' => []]; + $journals = $collector->getExtractedJournals(); + $sum = ['grand_sum' => '0', 'per_currency' => []]; // loop to support multi currency foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; // if not set, set to zero: if (!array_key_exists($currencyId, $sum['per_currency'])) { @@ -286,14 +286,14 @@ trait AugumentData 'currency' => [ 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], - 'decimal_places' => $journal['currency_decimal_places'] - ] + 'decimal_places' => $journal['currency_decimal_places'], + ], ]; } // add amount $sum['per_currency'][$currencyId]['sum'] = bcadd($sum['per_currency'][$currencyId]['sum'], (string) $journal['amount']); - $sum['grand_sum'] = bcadd($sum['grand_sum'], (string) $journal['amount']); + $sum['grand_sum'] = bcadd($sum['grand_sum'], (string) $journal['amount']); } return $sum; diff --git a/app/Support/Http/Controllers/BasicDataSupport.php b/app/Support/Http/Controllers/BasicDataSupport.php index 77b8a17420..702b1bbc4c 100644 --- a/app/Support/Http/Controllers/BasicDataSupport.php +++ b/app/Support/Http/Controllers/BasicDataSupport.php @@ -46,7 +46,7 @@ trait BasicDataSupport /** * Find the ID in a given array. Return null if not there (amount). */ - protected function isInArrayDate(array $array, int $entryId): null|Carbon + protected function isInArrayDate(array $array, int $entryId): ?Carbon { return $array[$entryId] ?? null; } diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index de2be2f248..087eefe316 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -59,44 +59,44 @@ trait ChartGeneration return $cache->get(); } Log::debug('Regenerate chart.account.account-balance-chart from scratch.'); - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); /** @var GeneratorInterface $generator */ - $generator = app(GeneratorInterface::class); + $generator = app(GeneratorInterface::class); /** @var AccountRepositoryInterface $accountRepos */ - $accountRepos = app(AccountRepositoryInterface::class); + $accountRepos = app(AccountRepositoryInterface::class); - $primary = Amount::getPrimaryCurrency(); - $chartData = []; + $primary = Amount::getPrimaryCurrency(); + $chartData = []; Log::debug(sprintf('Start of accountBalanceChart(list, %s, %s)', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); /** @var Account $account */ foreach ($accounts as $account) { Log::debug(sprintf('Now at account #%d ("%s)', $account->id, $account->name)); - $currency = $accountRepos->getAccountCurrency($account) ?? $primary; - $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $field = $convertToPrimary ? 'pc_balance' : 'balance'; - $currency = $usePrimary ? $primary : $currency; + $currency = $accountRepos->getAccountCurrency($account) ?? $primary; + $usePrimary = $convertToPrimary && $primary->id !== $currency->id; + $field = $convertToPrimary ? 'pc_balance' : 'balance'; + $currency = $usePrimary ? $primary : $currency; Log::debug(sprintf('Will use field %s', $field)); - $currentSet = ['label' => $account->name, 'currency_symbol' => $currency->symbol, 'entries' => []]; + $currentSet = ['label' => $account->name, 'currency_symbol' => $currency->symbol, 'entries' => []]; $currentStart = clone $start; $range = Steam::finalAccountBalanceInRange($account, clone $start, clone $end, $this->convertToPrimary); $previous = array_values($range)[0]; Log::debug(sprintf('Start balance for account #%d ("%s) is', $account->id, $account->name), $previous); while ($currentStart <= $end) { - $format = $currentStart->format('Y-m-d'); - $label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale))); - $balance = $range[$format] ?? $previous; - $previous = $balance; + $format = $currentStart->format('Y-m-d'); + $label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale))); + $balance = $range[$format] ?? $previous; + $previous = $balance; $currentStart->addDay(); $currentSet['entries'][$label] = $balance[$field] ?? '0'; } - $chartData[] = $currentSet; + $chartData[] = $currentSet; } - $data = $generator->multiSet($chartData); + $data = $generator->multiSet($chartData); $cache->store($data); return $data; diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index e26076f379..bea31d1b61 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -57,7 +57,7 @@ trait CreateStuff 'account_role' => 'defaultAsset', 'opening_balance' => $request->input('bank_balance'), 'opening_balance_date' => new Carbon(), - 'currency_id' => $currency->id + 'currency_id' => $currency->id, ]; $repository->store($assetAccount); @@ -82,7 +82,7 @@ trait CreateStuff 'account_role' => 'cashWalletAsset', 'opening_balance' => null, 'opening_balance_date' => null, - 'currency_id' => $currency->id + 'currency_id' => $currency->id, ]; $repository->store($assetAccount); @@ -101,7 +101,7 @@ trait CreateStuff return; } - $key = RSA::createKey(4096); + $key = RSA::createKey(4096); Log::alert('NO OAuth keys were found. They have been created.'); @@ -126,7 +126,7 @@ trait CreateStuff 'account_role' => 'savingAsset', 'opening_balance' => $request->input('savings_balance'), 'opening_balance_date' => new Carbon(), - 'currency_id' => $currency->id + 'currency_id' => $currency->id, ]; $repository->store($savingsAccount); diff --git a/app/Support/Http/Controllers/CronRunner.php b/app/Support/Http/Controllers/CronRunner.php index a25277c105..5087de1a94 100644 --- a/app/Support/Http/Controllers/CronRunner.php +++ b/app/Support/Http/Controllers/CronRunner.php @@ -54,7 +54,7 @@ trait CronRunner 'job_fired' => $billWarning->jobFired, 'job_succeeded' => $billWarning->jobSucceeded, 'job_errored' => $billWarning->jobErrored, - 'message' => $billWarning->message + 'message' => $billWarning->message, ]; } @@ -75,7 +75,7 @@ trait CronRunner 'job_fired' => $exchangeRates->jobFired, 'job_succeeded' => $exchangeRates->jobSucceeded, 'job_errored' => $exchangeRates->jobErrored, - 'message' => $exchangeRates->message + 'message' => $exchangeRates->message, ]; } @@ -96,7 +96,7 @@ trait CronRunner 'job_fired' => $autoBudget->jobFired, 'job_succeeded' => $autoBudget->jobSucceeded, 'job_errored' => $autoBudget->jobErrored, - 'message' => $autoBudget->message + 'message' => $autoBudget->message, ]; } @@ -117,7 +117,7 @@ trait CronRunner 'job_fired' => $recurring->jobFired, 'job_succeeded' => $recurring->jobSucceeded, 'job_errored' => $recurring->jobErrored, - 'message' => $recurring->message + 'message' => $recurring->message, ]; } @@ -138,7 +138,7 @@ trait CronRunner 'job_fired' => $webhook->jobFired, 'job_succeeded' => $webhook->jobSucceeded, 'job_errored' => $webhook->jobErrored, - 'message' => $webhook->message + 'message' => $webhook->message, ]; } } diff --git a/app/Support/Http/Controllers/DateCalculation.php b/app/Support/Http/Controllers/DateCalculation.php index fdf1bceea3..a149261ae1 100644 --- a/app/Support/Http/Controllers/DateCalculation.php +++ b/app/Support/Http/Controllers/DateCalculation.php @@ -91,23 +91,23 @@ trait DateCalculation protected function getNextPeriods(Carbon $date, string $range): array { // select thing for next 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = Navigation::startOfPeriod($date, $range); $current = Navigation::endOfPeriod($current, $range); $current->addDay(); - $count = 0; + $count = 0; while ($count < 12) { $current = Navigation::endOfPeriod($current, $range); $currentStart = Navigation::startOfPeriod($current, $range); - $loop[] = [ + $loop[] = [ 'label' => $current->format('Y-m-d'), 'title' => Navigation::periodShow($current, $range), 'start' => clone $currentStart, - 'end' => clone $current + 'end' => clone $current, ]; ++$count; $current->addDay(); @@ -123,7 +123,7 @@ trait DateCalculation protected function getPreviousPeriods(Carbon $date, string $range): array { // select thing for last 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = Navigation::startOfPeriod($date, $range); @@ -132,11 +132,11 @@ trait DateCalculation $current->subDay(); $current = Navigation::startOfPeriod($current, $range); $currentEnd = Navigation::endOfPeriod($current, $range); - $loop[] = [ + $loop[] = [ 'label' => $current->format('Y-m-d'), 'title' => Navigation::periodShow($current, $range), 'start' => clone $current, - 'end' => clone $currentEnd + 'end' => clone $currentEnd, ]; ++$count; } diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index 400003f0ca..e3fcf19f5e 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -46,7 +46,7 @@ trait GetConfigurationData E_ALL => 'E_ALL', E_ALL & ~E_DEPRECATED => 'E_ALL & ~E_DEPRECATED ', E_ALL & ~E_NOTICE => 'E_ALL & ~E_NOTICE', - E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR' + E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', ]; return $array[$value] ?? (string) $value; @@ -62,13 +62,13 @@ trait GetConfigurationData $steps = []; if (is_array($elements) && count($elements) > 0) { foreach ($elements as $key => $options) { - $currentStep = $options; + $currentStep = $options; // get the text: - $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $key); + $currentStep['intro'] = (string) trans('intro.'.$route.'_'.$key); // save in array: - $steps[] = $currentStep; + $steps[] = $currentStep; } } Log::debug(sprintf('Total basic steps for %s is %d', $routeKey, count($steps))); @@ -83,23 +83,23 @@ trait GetConfigurationData */ protected function getDateRangeConfig(): array // get configuration + get preferences. { - $viewRange = Navigation::getViewRange(false); + $viewRange = Navigation::getViewRange(false); Log::debug(sprintf('dateRange: the view range is "%s"', $viewRange)); /** @var Carbon $start */ - $start = session('start'); + $start = session('start'); /** @var Carbon $end */ - $end = session('end'); + $end = session('end'); /** @var Carbon $first */ - $first = session('first'); - $title = sprintf('%s - %s', $start->isoFormat($this->monthAndDayFormat), $end->isoFormat($this->monthAndDayFormat)); - $isCustom = true === session('is_custom_range', false); - $today = today(config('app.timezone')); - $ranges = [// first range is the current range: - $title => [$start, $end]]; + $first = session('first'); + $title = sprintf('%s - %s', $start->isoFormat($this->monthAndDayFormat), $end->isoFormat($this->monthAndDayFormat)); + $isCustom = true === session('is_custom_range', false); + $today = today(config('app.timezone')); + $ranges = [// first range is the current range: + $title => [$start, $end]]; Log::debug(sprintf('dateRange: the date range in the session is"%s" - "%s"', $start->format('Y-m-d'), $end->format('Y-m-d'))); // when current range is a custom range, add the current period as the next range. @@ -107,61 +107,61 @@ trait GetConfigurationData $index = Navigation::periodShow($start, $viewRange); $customPeriodStart = Navigation::startOfPeriod($start, $viewRange); $customPeriodEnd = Navigation::endOfPeriod($customPeriodStart, $viewRange); - $ranges[$index] = [$customPeriodStart, $customPeriodEnd]; + $ranges[$index] = [$customPeriodStart, $customPeriodEnd]; } // then add previous range and next range, but skip this for the lastX and YTD stuff. if (!in_array($viewRange, config('firefly.dynamic_date_ranges', []), true)) { - $previousDate = Navigation::subtractPeriod($start, $viewRange); - $index = Navigation::periodShow($previousDate, $viewRange); - $previousStart = Navigation::startOfPeriod($previousDate, $viewRange); - $previousEnd = Navigation::endOfPeriod($previousStart, $viewRange); + $previousDate = Navigation::subtractPeriod($start, $viewRange); + $index = Navigation::periodShow($previousDate, $viewRange); + $previousStart = Navigation::startOfPeriod($previousDate, $viewRange); + $previousEnd = Navigation::endOfPeriod($previousStart, $viewRange); $ranges[$index] = [$previousStart, $previousEnd]; - $nextDate = Navigation::addPeriod($start, $viewRange); - $index = Navigation::periodShow($nextDate, $viewRange); - $nextStart = Navigation::startOfPeriod($nextDate, $viewRange); - $nextEnd = Navigation::endOfPeriod($nextStart, $viewRange); + $nextDate = Navigation::addPeriod($start, $viewRange); + $index = Navigation::periodShow($nextDate, $viewRange); + $nextStart = Navigation::startOfPeriod($nextDate, $viewRange); + $nextEnd = Navigation::endOfPeriod($nextStart, $viewRange); $ranges[$index] = [$nextStart, $nextEnd]; } // today: /** @var Carbon $todayStart */ - $todayStart = Navigation::startOfPeriod($today, $viewRange); + $todayStart = Navigation::startOfPeriod($today, $viewRange); /** @var Carbon $todayEnd */ - $todayEnd = Navigation::endOfPeriod($todayStart, $viewRange); + $todayEnd = Navigation::endOfPeriod($todayStart, $viewRange); if ($todayStart->ne($start) || $todayEnd->ne($end)) { $ranges[ucfirst((string) trans('firefly.today'))] = [$todayStart, $todayEnd]; } // last seven days: - $seven = today(config('app.timezone'))->subDays(7); - $index = (string) trans('firefly.last_seven_days'); + $seven = today(config('app.timezone'))->subDays(7); + $index = (string) trans('firefly.last_seven_days'); $ranges[$index] = [$seven, new Carbon()]; // last 30 days: - $thirty = today(config('app.timezone'))->subDays(30); - $index = (string) trans('firefly.last_thirty_days'); + $thirty = today(config('app.timezone'))->subDays(30); + $index = (string) trans('firefly.last_thirty_days'); $ranges[$index] = [$thirty, new Carbon()]; // month to date: - $monthBegin = today(config('app.timezone'))->startOfMonth(); - $index = (string) trans('firefly.month_to_date'); + $monthBegin = today(config('app.timezone'))->startOfMonth(); + $index = (string) trans('firefly.month_to_date'); $ranges[$index] = [$monthBegin, new Carbon()]; // year to date: - $yearBegin = today(config('app.timezone'))->startOfYear(); - $index = (string) trans('firefly.year_to_date'); + $yearBegin = today(config('app.timezone'))->startOfYear(); + $index = (string) trans('firefly.year_to_date'); $ranges[$index] = [$yearBegin, new Carbon()]; // previous year: - $yearBegin = today(config('app.timezone'))->subYear()->startOfYear(); - $index = (string) trans('firefly.previous_year', ['year' => $yearBegin->year]); + $yearBegin = today(config('app.timezone'))->subYear()->startOfYear(); + $index = (string) trans('firefly.previous_year', ['year' => $yearBegin->year]); $ranges[$index] = [$yearBegin, $yearBegin->clone()->endOfYear()]; // everything - $index = (string) trans('firefly.everything'); + $index = (string) trans('firefly.everything'); $ranges[$index] = [$first, new Carbon()]; return [ @@ -174,8 +174,8 @@ trait GetConfigurationData 'customRange' => (string) trans('firefly.customRange'), 'start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d'), - 'ranges' => $ranges - ] + 'ranges' => $ranges, + ], ]; } @@ -190,16 +190,16 @@ trait GetConfigurationData // user is on page with specific instructions: if ('' !== $specificPage) { $routeKey = str_replace('.', '_', $route); - $elements = config(sprintf('intro.%s', $routeKey . '_' . $specificPage)); + $elements = config(sprintf('intro.%s', $routeKey.'_'.$specificPage)); if (is_array($elements) && count($elements) > 0) { foreach ($elements as $key => $options) { - $currentStep = $options; + $currentStep = $options; // get the text: - $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $specificPage . '_' . $key); + $currentStep['intro'] = (string) trans('intro.'.$route.'_'.$specificPage.'_'.$key); // save in array: - $steps[] = $currentStep; + $steps[] = $currentStep; } } } diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 5cfb0bbc11..c6c70eea62 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -52,7 +52,7 @@ trait ModelInformation 'oldAction' => 'link_to_bill', 'oldValue' => $bill->name, 'oldChecked' => false, - 'count' => 1 + 'count' => 1, ])->render(); } catch (Throwable $e) { Log::error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); @@ -73,21 +73,21 @@ trait ModelInformation protected function getLiabilityTypes(): array { /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); // types of liability: /** @var AccountType $debt */ - $debt = $repository->getAccountTypeByType(AccountTypeEnum::DEBT->value); + $debt = $repository->getAccountTypeByType(AccountTypeEnum::DEBT->value); /** @var AccountType $loan */ - $loan = $repository->getAccountTypeByType(AccountTypeEnum::LOAN->value); + $loan = $repository->getAccountTypeByType(AccountTypeEnum::LOAN->value); /** @var AccountType $mortgage */ $mortgage = $repository->getAccountTypeByType(AccountTypeEnum::MORTGAGE->value); $liabilityTypes = [ $debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::DEBT->value)), $loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::LOAN->value)), - $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)) + $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)), ]; asort($liabilityTypes); @@ -112,8 +112,8 @@ trait ModelInformation protected function getTriggersForBill(Bill $bill): array // get info and argument { // TODO duplicate code - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); @@ -131,7 +131,7 @@ trait ModelInformation 'oldValue' => $values[$index], 'oldChecked' => false, 'count' => $index + 1, - 'triggers' => $triggers + 'triggers' => $triggers, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); @@ -155,8 +155,8 @@ trait ModelInformation private function getTriggersForJournal(TransactionJournal $journal): array { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); @@ -164,79 +164,79 @@ trait ModelInformation } asort($triggers); - $result = []; - $journalTriggers = []; - $values = []; - $index = 0; + $result = []; + $journalTriggers = []; + $values = []; + $index = 0; // amount, description, category, budget, tags, source, destination, notes, currency type // ,type /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destination */ - $destination = $journal->transactions()->where('amount', '>', 0)->first(); + $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $destination || null === $source) { return $result; } // type $journalTriggers[$index] = 'transaction_type'; - $values[$index] = $journal->transactionType->type; + $values[$index] = $journal->transactionType->type; ++$index; // currency $journalTriggers[$index] = 'currency_is'; - $values[$index] = sprintf('%s (%s)', $journal->transactionCurrency?->name, $journal->transactionCurrency?->code); + $values[$index] = sprintf('%s (%s)', $journal->transactionCurrency?->name, $journal->transactionCurrency?->code); ++$index; // amount_exactly: $journalTriggers[$index] = 'amount_is'; - $values[$index] = $destination->amount; + $values[$index] = $destination->amount; ++$index; // description_is: $journalTriggers[$index] = 'description_is'; - $values[$index] = $journal->description; + $values[$index] = $journal->description; ++$index; // from_account_is $journalTriggers[$index] = 'source_account_is'; - $values[$index] = $source->account->name; + $values[$index] = $source->account->name; ++$index; // to_account_is $journalTriggers[$index] = 'destination_account_is'; - $values[$index] = $destination->account->name; + $values[$index] = $destination->account->name; ++$index; // category (if) - $category = $journal->categories()->first(); + $category = $journal->categories()->first(); if (null !== $category) { $journalTriggers[$index] = 'category_is'; - $values[$index] = $category->name; + $values[$index] = $category->name; ++$index; } // budget (if) - $budget = $journal->budgets()->first(); + $budget = $journal->budgets()->first(); if (null !== $budget) { $journalTriggers[$index] = 'budget_is'; - $values[$index] = $budget->name; + $values[$index] = $budget->name; ++$index; } // tags (if) - $tags = $journal->tags()->get(); + $tags = $journal->tags()->get(); /** @var Tag $tag */ foreach ($tags as $tag) { $journalTriggers[$index] = 'tag_is'; - $values[$index] = $tag->tag; + $values[$index] = $tag->tag; ++$index; } // notes (if) - $notes = $journal->notes()->first(); + $notes = $journal->notes()->first(); if (null !== $notes) { $journalTriggers[$index] = 'notes_is'; - $values[$index] = $notes->text; + $values[$index] = $notes->text; } foreach ($journalTriggers as $ii => $trigger) { @@ -246,7 +246,7 @@ trait ModelInformation 'oldValue' => $values[$ii], 'oldChecked' => false, 'count' => $ii + 1, - 'triggers' => $triggers + 'triggers' => $triggers, ]; $string = view('rules.partials.trigger', $renderInfo)->render(); } catch (Throwable $e) { diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index 0d57b4eae1..b439d7c256 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -93,18 +93,18 @@ trait PeriodOverview protected function getAccountPeriodOverview(Account $account, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in getAccountPeriodOverview(#%d, %s %s)', $account->id, $start->format('Y-m-d H:i:s.u'), $end->format('Y-m-d H:i:s.u'))); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository->setUser($account->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($account, $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($account, $start, $end); - $entries = []; + $entries = []; Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { $entries[] = $this->getSingleModelPeriod($account, $currentDate['period'], $currentDate['start'], $currentDate['end']); @@ -140,18 +140,18 @@ trait PeriodOverview */ protected function getCategoryPeriodOverview(Category $category, Carbon $start, Carbon $end): array { - $this->categoryRepository = app(CategoryRepositoryInterface::class); + $this->categoryRepository = app(CategoryRepositoryInterface::class); $this->categoryRepository->setUser($category->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($category, $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($category, $start, $end); Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { @@ -172,14 +172,14 @@ trait PeriodOverview { Log::debug(sprintf('Now in getNoModelPeriodOverview(%s, %s %s)', $model, $start->format('Y-m-d'), $end->format('Y-m-d'))); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $entries = []; - $this->statistics = $this->periodStatisticRepo->allInRangeForPrefix(sprintf('no_%s', $model), $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $entries = []; + $this->statistics = $this->periodStatisticRepo->allInRangeForPrefix(sprintf('no_%s', $model), $start, $end); Log::debug(sprintf('Collected %d stats', $this->statistics->count())); foreach ($dates as $currentDate) { @@ -205,7 +205,7 @@ trait PeriodOverview case 'budget': // get all expenses without a budget. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->withoutBudget()->withAccountInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); $spent = $collector->getExtractedJournals(); $earned = []; @@ -216,23 +216,23 @@ trait PeriodOverview case 'category': // collect all expenses in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $earned = $collector->getExtractedJournals(); + $earned = $collector->getExtractedJournals(); // collect all income in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $spent = $collector->getExtractedJournals(); + $spent = $collector->getExtractedJournals(); // collect all transfers in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::TRANSFER->value]); @@ -244,9 +244,9 @@ trait PeriodOverview $groupedEarned = $this->groupByCurrency($earned); $groupedTransferred = $this->groupByCurrency($transferred); $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [ - $start->format('Y-m-d'), - $end->format('Y-m-d') - ]), 'total_transactions' => count($spent), 'spent' => $groupedSpent, 'earned' => $groupedEarned, 'transferred' => $groupedTransferred]; + $start->format('Y-m-d'), + $end->format('Y-m-d'), + ]), 'total_transactions' => count($spent), 'spent' => $groupedSpent, 'earned' => $groupedEarned, 'transferred' => $groupedTransferred]; $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'spent', $groupedSpent); $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'earned', $groupedEarned); $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'transferred', $groupedTransferred); @@ -255,17 +255,17 @@ trait PeriodOverview } Log::debug(sprintf('Found %d statistics in period %s - %s.', count($statistics), $start->format('Y-m-d'), $end->format('Y-m-d'))); - $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [ - $start->format('Y-m-d'), - $end->format('Y-m-d') - ]), 'total_transactions' => 0, 'spent' => [], 'earned' => [], 'transferred' => []]; - $grouped = []; + $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [ + $start->format('Y-m-d'), + $end->format('Y-m-d'), + ]), 'total_transactions' => 0, 'spent' => [], 'earned' => [], 'transferred' => []]; + $grouped = []; /** @var PeriodStatistic $statistic */ foreach ($statistics as $statistic) { - $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type); - $id = (int) $statistic->transaction_currency_id; - $currency = Amount::getTransactionCurrencyById($id); + $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type); + $id = (int) $statistic->transaction_currency_id; + $currency = Amount::getTransactionCurrencyById($id); $grouped[$type]['count'] ??= 0; $grouped[$type][$id] = [ 'amount' => (string) $statistic->amount, @@ -274,11 +274,11 @@ trait PeriodOverview 'currency_name' => $currency->name, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; $grouped[$type]['count'] += (int) $statistic->count; } - $types = ['spent', 'earned', 'transferred']; + $types = ['spent', 'earned', 'transferred']; foreach ($types as $type) { if (array_key_exists($type, $grouped)) { $entry['total_transactions'] += $grouped[$type]['count']; @@ -293,19 +293,19 @@ trait PeriodOverview protected function getSingleModelPeriod(Model $model, string $period, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in getSingleModelPeriod(%s #%d, %s %s)', $model::class, $model->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - $types = ['spent', 'earned', 'transferred_in', 'transferred_away']; - $return = [ + $types = ['spent', 'earned', 'transferred_in', 'transferred_away']; + $return = [ 'title' => Navigation::periodShow($start, $period), 'route' => route(sprintf('%s.show', strtolower(Str::plural(class_basename($model)))), [ $model->id, $start->format('Y-m-d'), - $end->format('Y-m-d') + $end->format('Y-m-d'), ]), - 'total_transactions' => 0 + 'total_transactions' => 0, ]; $this->transactions = []; foreach ($types as $type) { - $set = $this->getSingleModelPeriodByType($model, $start, $end, $type); + $set = $this->getSingleModelPeriodByType($model, $start, $end, $type); $return['total_transactions'] += $set['count']; unset($set['count']); $return[$type] = $set; @@ -323,7 +323,7 @@ trait PeriodOverview } return $this->statistics->filter( - static fn(PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type + static fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type ); } @@ -336,7 +336,7 @@ trait PeriodOverview } return $this->statistics->filter( - static fn(PeriodStatistic $statistic): bool => ( + static fn (PeriodStatistic $statistic): bool => ( $statistic->start->eq($start) && $statistic->end->eq($end) && str_starts_with($statistic->type, $prefix) @@ -413,12 +413,12 @@ trait PeriodOverview return $grouped; } - $grouped = ['count' => 0]; + $grouped = ['count' => 0]; /** @var PeriodStatistic $statistic */ foreach ($statistics as $statistic) { - $id = (int) $statistic->transaction_currency_id; - $currency = Amount::getTransactionCurrencyById($id); + $id = (int) $statistic->transaction_currency_id; + $currency = Amount::getTransactionCurrencyById($id); $grouped[$id] = [ 'amount' => (string) $statistic->amount, 'count' => (int) $statistic->count, @@ -426,7 +426,7 @@ trait PeriodOverview 'currency_name' => $currency->name, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places + 'currency_decimal_places' => $currency->decimal_places, ]; $grouped['count'] += (int) $statistic->count; } @@ -441,18 +441,18 @@ trait PeriodOverview */ protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array { // period overview for tags. - $this->tagRepository = app(TagRepositoryInterface::class); + $this->tagRepository = app(TagRepositoryInterface::class); $this->tagRepository->setUser($tag->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($tag, $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($tag, $start, $end); Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { @@ -467,12 +467,12 @@ trait PeriodOverview */ protected function getTransactionPeriodOverview(string $transactionType, Carbon $start, Carbon $end): array { - $range = Navigation::getViewRange(true); - $types = config(sprintf('firefly.transactionTypesByType.%s', $transactionType)); + $range = Navigation::getViewRange(true); + $types = config(sprintf('firefly.transactionTypesByType.%s', $transactionType)); [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; // properties for cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('transactions-period-entries'); @@ -482,19 +482,19 @@ trait PeriodOverview } /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - $spent = []; - $earned = []; - $transferred = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + $spent = []; + $earned = []; + $transferred = []; // collect all journals in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes($types)->setRange($start, $end); - $genericSet = $collector->getExtractedJournals(); - $loops = 0; + $genericSet = $collector->getExtractedJournals(); + $loops = 0; foreach ($dates as $currentDate) { - $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); + $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); if ($loops < 10) { // set to correct array @@ -513,12 +513,12 @@ trait PeriodOverview 'route' => route('transactions.index', [ $transactionType, $currentDate['start']->format('Y-m-d'), - $currentDate['end']->format('Y-m-d') + $currentDate['end']->format('Y-m-d'), ]), 'total_transactions' => count($spent) + count($earned) + count($transferred), 'spent' => $this->groupByCurrency($spent), 'earned' => $this->groupByCurrency($earned), - 'transferred' => $this->groupByCurrency($transferred) + 'transferred' => $this->groupByCurrency($transferred), ]; ++$loops; } @@ -634,13 +634,13 @@ trait PeriodOverview /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; - $foreignCurrencyId = $journal['foreign_currency_id']; - $amount = (string) ($journal['amount'] ?? '0'); + $currencyId = (int) $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; + $foreignCurrencyId = $journal['foreign_currency_id']; + $amount = (string) ($journal['amount'] ?? '0'); if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId !== $this->primaryCurrency->id) { $amount = (string) ($journal['pc_amount'] ?? '0'); @@ -665,7 +665,7 @@ trait PeriodOverview 'currency_name' => $currencyName, 'currency_code' => $currencyCode, 'currency_symbol' => $currencySymbol, - 'currency_decimal_places' => $currencyDecimalPlaces + 'currency_decimal_places' => $currencyDecimalPlaces, ]; $return[$currencyId]['amount'] = bcadd((string) $return[$currencyId]['amount'], $amount); diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index 67ea7d42a7..07fba9873a 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -54,20 +54,20 @@ trait RenderPartialViews protected function budgetEntry(array $attributes): string // generate view for report. { /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); /** @var BudgetRepositoryInterface $budgetRepository */ $budgetRepository = app(BudgetRepositoryInterface::class); $budget = $budgetRepository->find((int) $attributes['budgetId']); - $accountRepos = app(AccountRepositoryInterface::class); - $account = $accountRepos->find((int) $attributes['accountId']); + $accountRepos = app(AccountRepositoryInterface::class); + $account = $accountRepos->find((int) $attributes['accountId']); if (null === $budget || null === $account) { throw new FireflyException('Could not render popup.report.balance-amount because budget or account is null.'); } - $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); + $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); try { $view = view('popup.report.balance-amount', ['journals' => $journals, 'budget' => $budget, 'account' => $account])->render(); @@ -115,14 +115,14 @@ trait RenderPartialViews $budgetRepository = app(BudgetRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); - $budget = $budgetRepository->find((int) $attributes['budgetId']); + $budget = $budgetRepository->find((int) $attributes['budgetId']); if (null === $budget) { // transactions without a budget. $budget = new Budget(); } - $journals = $popupHelper->byBudget($budget, $attributes); + $journals = $popupHelper->byBudget($budget, $attributes); try { $view = view('popup.report.budget-spent-amount', ['journals' => $journals, 'budget' => $budget])->render(); @@ -144,7 +144,7 @@ trait RenderPartialViews protected function categoryEntry(array $attributes): string // generate view for report. { /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); /** @var CategoryRepositoryInterface $categoryRepository */ $categoryRepository = app(CategoryRepositoryInterface::class); @@ -199,13 +199,13 @@ trait RenderPartialViews AccountTypeEnum::EXPENSE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); $revenue = $repository->getActiveAccountsByType([ AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]); $set = []; @@ -251,14 +251,14 @@ trait RenderPartialViews $accountRepository = app(AccountRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int) $attributes['accountId']); + $account = $accountRepository->find((int) $attributes['accountId']); if (null === $account) { return 'This is an unknown account. Apologies.'; } - $journals = $popupHelper->byExpenses($account, $attributes); + $journals = $popupHelper->byExpenses($account, $attributes); try { $view = view('popup.report.expense-entry', ['journals' => $journals, 'account' => $account])->render(); @@ -279,8 +279,8 @@ trait RenderPartialViews */ protected function getCurrentActions(Rule $rule): array // get info from object and present. { - $index = 0; - $actions = []; + $index = 0; + $actions = []; // must be repos $currentActions = $rule->ruleActions()->orderBy('order', 'ASC')->get(); @@ -293,7 +293,7 @@ trait RenderPartialViews 'oldAction' => $entry->action_type, 'oldValue' => $entry->action_value, 'oldChecked' => $entry->stop_processing, - 'count' => $count + 'count' => $count, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); @@ -316,8 +316,8 @@ trait RenderPartialViews protected function getCurrentTriggers(Rule $rule): array // get info from object and present. { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); @@ -335,7 +335,7 @@ trait RenderPartialViews $count = $index + 1; try { - $rootOperator = OperatorQuerySearch::getRootOperator((string) $entry->trigger_type); + $rootOperator = OperatorQuerySearch::getRootOperator((string) $entry->trigger_type); if (str_starts_with($rootOperator, '-')) { $rootOperator = substr($rootOperator, 1); } @@ -345,7 +345,7 @@ trait RenderPartialViews 'oldChecked' => $entry->stop_processing, 'oldProhibited' => str_starts_with((string) $entry->trigger_type, '-'), 'count' => $count, - 'triggers' => $triggers + 'triggers' => $triggers, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); @@ -372,14 +372,14 @@ trait RenderPartialViews $accountRepository = app(AccountRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int) $attributes['accountId']); + $popupHelper = app(PopupReportInterface::class); + $account = $accountRepository->find((int) $attributes['accountId']); if (null === $account) { return 'This is an unknown category. Apologies.'; } - $journals = $popupHelper->byIncome($account, $attributes); + $journals = $popupHelper->byIncome($account, $attributes); try { $view = view('popup.report.income-entry', ['journals' => $journals, 'account' => $account])->render(); @@ -423,11 +423,11 @@ trait RenderPartialViews $repository = app(TagRepositoryInterface::class); $tags = $repository->get(); - $grouped = []; + $grouped = []; /** @var Tag $tag */ foreach ($tags as $tag) { - $year = (int) $tag->date?->year; + $year = (int) $tag->date?->year; $grouped[$year] ??= ['tags' => [], 'year' => 0 === $year ? trans('firefly.no_date') : $year]; $grouped[$year]['tags'][] = $tag; } diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index bdd31f80e5..f1c60166b0 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -80,13 +80,13 @@ trait RequestInformation $data = $request->get('triggers'); if (is_array($data)) { foreach ($data as $triggerInfo) { - $current = [ + $current = [ 'type' => $triggerInfo['type'] ?? '', 'value' => $triggerInfo['value'] ?? '', 'prohibited' => $triggerInfo['prohibited'] ?? false, - 'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0') + 'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0'), ]; - $current = RuleFormRequest::replaceAmountTrigger($current); + $current = RuleFormRequest::replaceAmountTrigger($current); $triggers[] = $current; } } @@ -102,13 +102,13 @@ trait RequestInformation $page = $this->getPageName(); $specificPage = $this->getSpecificPageName(); // indicator if user has seen the help for this page ( + special page): - $key = sprintf('shown_demo_%s%s', $page, $specificPage); + $key = sprintf('shown_demo_%s%s', $page, $specificPage); // is there an intro for this route? $intro = config(sprintf('intro.%s', $page)) ?? []; $specialIntro = config(sprintf('intro.%s%s', $page, $specificPage)) ?? []; // some routes have a "what" parameter, which indicates a special page: - $shownDemo = true; + $shownDemo = true; // both must be array and either must be > 0 if (count($intro) > 0 || count($specialIntro) > 0) { $shownDemo = Preferences::get($key, false)->data; @@ -129,7 +129,7 @@ trait RequestInformation $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) { return true; } @@ -144,20 +144,20 @@ trait RequestInformation final protected function parseAttributes(array $attributes): array // parse input + return result { $attributes['location'] ??= ''; - $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); - $date = Carbon::createFromFormat('Ymd', $attributes['startDate']); + $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); + $date = Carbon::createFromFormat('Ymd', $attributes['startDate']); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $date->startOfMonth(); $attributes['startDate'] = $date; - $date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']); + $date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']); if (!$date2 instanceof Carbon) { $date2 = today(config('app.timezone')); } $date2->endOfDay(); - $attributes['endDate'] = $date2; + $attributes['endDate'] = $date2; return $attributes; } @@ -187,7 +187,7 @@ trait RequestInformation { return Validator::make($data, [ 'email' => 'required|string|email|max:255|unique:users', - 'password' => 'required|string|min:16|secure_password|confirmed' + 'password' => 'required|string|min:16|secure_password|confirmed', ]); } } diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index 4b3048f044..bf3d48c735 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -51,7 +51,7 @@ trait RuleManagement 'oldAction' => $oldAction['type'], 'oldValue' => $oldAction['value'] ?? '', 'oldChecked' => 1 === (int) ($oldAction['stop_processing'] ?? '0'), - 'count' => $index + 1 + 'count' => $index + 1, ])->render(); } catch (Throwable $e) { Log::error(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); @@ -72,8 +72,8 @@ trait RuleManagement protected function getPreviousTriggers(Request $request): array { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); @@ -93,7 +93,7 @@ trait RuleManagement 'oldChecked' => 1 === (int) ($oldTrigger['stop_processing'] ?? '0'), 'oldProhibited' => 1 === (int) ($oldTrigger['prohibited'] ?? '0'), 'count' => $index + 1, - 'triggers' => $triggers + 'triggers' => $triggers, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); @@ -124,7 +124,7 @@ trait RuleManagement } asort($triggers); - $index = 0; + $index = 0; foreach ($submittedOperators as $operator) { $rootOperator = OperatorQuerySearch::getRootOperator($operator['type']); $needsContext = (bool) config(sprintf('search.operators.%s.needs_context', $rootOperator)); @@ -136,7 +136,7 @@ trait RuleManagement 'oldChecked' => false, 'oldProhibited' => $operator['prohibited'] ?? false, 'count' => $index + 1, - 'triggers' => $triggers + 'triggers' => $triggers, ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); @@ -158,7 +158,7 @@ trait RuleManagement $data = [ 'title' => (string) trans('firefly.default_rule_group_name'), 'description' => (string) trans('firefly.default_rule_group_description'), - 'active' => true + 'active' => true, ]; $repository->store($data); diff --git a/app/Support/Http/Controllers/TransactionCalculation.php b/app/Support/Http/Controllers/TransactionCalculation.php index f341b43d7b..0d7d362160 100644 --- a/app/Support/Http/Controllers/TransactionCalculation.php +++ b/app/Support/Http/Controllers/TransactionCalculation.php @@ -39,7 +39,7 @@ trait TransactionCalculation */ protected function getExpensesForOpposing(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): array { - $total = $accounts->merge($opposing); + $total = $accounts->merge($opposing); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -61,7 +61,8 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setTags($tags) - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } @@ -78,7 +79,8 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setBudgets($budgets) - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } @@ -95,7 +97,8 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($categories) - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } @@ -112,7 +115,8 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($categories) - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } @@ -122,7 +126,7 @@ trait TransactionCalculation */ protected function getIncomeForOpposing(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): array { - $total = $accounts->merge($opposing); + $total = $accounts->merge($opposing); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -143,7 +147,8 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) ->setTags($tags) - ->withAccountInformation(); + ->withAccountInformation() + ; return $collector->getExtractedJournals(); } diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index 4b5fb087f8..acdfe20e77 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -68,7 +68,7 @@ trait UserNavigation AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]; $type = $account->accountType->type; @@ -78,7 +78,7 @@ trait UserNavigation final protected function isEditableGroup(TransactionGroup $group): bool { /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); + $journal = $group->transactionJournals()->first(); if (null === $journal) { return false; } @@ -87,7 +87,7 @@ trait UserNavigation TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::DEPOSIT->value, - TransactionTypeEnum::RECONCILIATION->value + TransactionTypeEnum::RECONCILIATION->value, ]; return in_array($type, $editable, true); @@ -111,10 +111,10 @@ trait UserNavigation return redirect(route('index')); } - $journal = $transaction->transactionJournal; + $journal = $transaction->transactionJournal; /** @var null|Transaction $other */ - $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); + $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); if (null === $other) { 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')); @@ -131,7 +131,7 @@ trait UserNavigation final protected function redirectGroupToAccount(TransactionGroup $group): Redirector|RedirectResponse { /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); + $journal = $group->transactionJournals()->first(); if (null === $journal) { Log::error(sprintf('No journals in group #%d', $group->id)); @@ -143,7 +143,7 @@ trait UserNavigation AccountTypeEnum::REVENUE->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::RECONCILIATION->value, - AccountTypeEnum::INITIAL_BALANCE->value + AccountTypeEnum::INITIAL_BALANCE->value, ]; /** @var Transaction $transaction */ @@ -157,7 +157,7 @@ trait UserNavigation return redirect(route('index')); } - final protected function rememberPreviousUrl(string $identifier): null|string + final protected function rememberPreviousUrl(string $identifier): ?string { $return = Steam::getSafePreviousUrl(); session()->put($identifier, $return); diff --git a/app/Support/JsonApi/Enrichments/AccountEnrichment.php b/app/Support/JsonApi/Enrichments/AccountEnrichment.php index 437e085133..a44823e2e9 100644 --- a/app/Support/JsonApi/Enrichments/AccountEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AccountEnrichment.php @@ -53,14 +53,14 @@ use Override; */ class AccountEnrichment implements EnrichmentInterface { - private array $accountTypeIds = []; - private array $accountTypes = []; - private array $balances = []; + private array $accountTypeIds = []; + private array $accountTypes = []; + private array $balances = []; private Collection $collection; private readonly bool $convertToPrimary; private array $currencies = []; - private null|Carbon $date = null; - private null|Carbon $end = null; + private ?Carbon $date = null; + private ?Carbon $end = null; private array $endBalances = []; private array $ids = []; private array $lastActivities = []; @@ -71,9 +71,9 @@ class AccountEnrichment implements EnrichmentInterface private array $objectGroups = []; private array $openingBalances = []; private readonly TransactionCurrency $primaryCurrency; - private array $sort = []; - private null|Carbon $start = null; - private array $startBalances = []; + private array $sort = []; + private ?Carbon $start = null; + private array $startBalances = []; private User $user; private UserGroup $userGroup; @@ -82,7 +82,7 @@ class AccountEnrichment implements EnrichmentInterface */ public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -130,7 +130,7 @@ class AccountEnrichment implements EnrichmentInterface return $this->date; } - public function setDate(null|Carbon $date): void + public function setDate(?Carbon $date): void { if ($date instanceof Carbon) { $date->endOfDay(); @@ -139,7 +139,7 @@ class AccountEnrichment implements EnrichmentInterface $this->date = $date; } - public function setEnd(null|Carbon $end): void + public function setEnd(?Carbon $end): void { $this->end = $end; } @@ -149,14 +149,14 @@ class AccountEnrichment implements EnrichmentInterface $this->sort = $sort; } - public function setStart(null|Carbon $start): void + public function setStart(?Carbon $start): void { $this->start = $start; } public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } @@ -168,9 +168,9 @@ class AccountEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $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 = [ + $id = (int) $item->id; + $item->full_account_type = $this->accountTypes[(int) $item->account_type_id] ?? null; + $meta = [ 'currency' => null, 'location' => ['latitude' => null, 'longitude' => null, 'zoom_level' => null], 'object_group_id' => null, @@ -180,13 +180,13 @@ class AccountEnrichment implements EnrichmentInterface 'opening_balance_amount' => null, 'account_number' => null, 'notes' => $this->notes[$id] ?? null, - 'last_activity' => $this->lastActivities[$id] ?? null + 'last_activity' => $this->lastActivities[$id] ?? null, ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } @@ -202,44 +202,44 @@ class AccountEnrichment implements EnrichmentInterface } // also add currency, if present. if (array_key_exists('currency_id', $meta)) { - $currencyId = (int) $meta['currency_id']; + $currencyId = (int) $meta['currency_id']; $meta['currency'] = $this->currencies[$currencyId]; } if (array_key_exists($id, $this->openingBalances)) { - $meta['opening_balance_date'] = $this->openingBalances[$id]['date']; + $meta['opening_balance_date'] = $this->openingBalances[$id]['date']; $meta['opening_balance_amount'] = $this->openingBalances[$id]['amount']; } // add balances // get currencies: - $currency = $this->primaryCurrency; // assume primary currency + $currency = $this->primaryCurrency; // assume primary currency if (null !== $meta['currency']) { $currency = $meta['currency']; } // get the current balance: - $date = $this->getDate(); + $date = $this->getDate(); // $finalBalance = Steam::finalAccountBalance($item, $date, $this->primaryCurrency, $this->convertToPrimary); - $finalBalance = $this->balances[$id]; - $balanceDifference = $this->getBalanceDifference($id, $currency); + $finalBalance = $this->balances[$id]; + $balanceDifference = $this->getBalanceDifference($id, $currency); Log::debug( sprintf('Call finalAccountBalance(%s) with date/time "%s"', var_export($this->convertToPrimary, true), $date->toIso8601String()), $finalBalance ); // collect current balances: - $currentBalance = Steam::bcround($finalBalance[$currency->code] ?? '0', $currency->decimal_places); - $openingBalance = Steam::bcround($meta['opening_balance_amount'] ?? '0', $currency->decimal_places); - $virtualBalance = Steam::bcround($item->virtual_balance ?? '0', $currency->decimal_places); - $debtAmount = $meta['current_debt'] ?? null; + $currentBalance = Steam::bcround($finalBalance[$currency->code] ?? '0', $currency->decimal_places); + $openingBalance = Steam::bcround($meta['opening_balance_amount'] ?? '0', $currency->decimal_places); + $virtualBalance = Steam::bcround($item->virtual_balance ?? '0', $currency->decimal_places); + $debtAmount = $meta['current_debt'] ?? null; // set some pc_ default values to NULL: - $pcCurrentBalance = null; - $pcOpeningBalance = null; - $pcVirtualBalance = null; - $pcDebtAmount = null; - $pcBalanceDifference = null; + $pcCurrentBalance = null; + $pcOpeningBalance = null; + $pcVirtualBalance = null; + $pcDebtAmount = null; + $pcBalanceDifference = null; // convert to primary currency if needed: if ($this->convertToPrimary && $currency->id !== $this->primaryCurrency->id) { @@ -265,7 +265,7 @@ class AccountEnrichment implements EnrichmentInterface $pcOpeningBalance = null; } $meta['current_balance_date'] = $this->getDate(); - $meta['balances'] = [ + $meta['balances'] = [ 'current_balance' => $currentBalance, 'pc_current_balance' => $pcCurrentBalance, 'opening_balance' => $openingBalance, @@ -275,10 +275,10 @@ class AccountEnrichment implements EnrichmentInterface 'debt_amount' => $debtAmount, 'pc_debt_amount' => $pcDebtAmount, 'balance_difference' => $balanceDifference, - 'pc_balance_difference' => $pcBalanceDifference + 'pc_balance_difference' => $pcBalanceDifference, ]; // end add balances - $item->meta = $meta; + $item->meta = $meta; return $item; }); @@ -302,10 +302,10 @@ class AccountEnrichment implements EnrichmentInterface { /** @var Account $account */ foreach ($this->collection as $account) { - $this->ids[] = (int) $account->id; + $this->ids[] = (int) $account->id; $this->accountTypeIds[] = (int) $account->account_type_id; } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); $this->accountTypeIds = array_unique($this->accountTypeIds); } @@ -320,12 +320,13 @@ class AccountEnrichment implements EnrichmentInterface ->whereIn('locatable_id', $this->ids) ->where('locatable_type', Account::class) ->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level']) - ->toArray(); + ->toArray() + ; foreach ($locations as $location) { $this->locations[(int) $location['locatable_id']] = [ 'latitude' => (float) $location['latitude'], 'longitude' => (float) $location['longitude'], - 'zoom_level' => (int) $location['zoom_level'] + 'zoom_level' => (int) $location['zoom_level'], ]; } Log::debug(sprintf('Enrich with %d locations(s)', count($this->locations))); @@ -333,7 +334,7 @@ class AccountEnrichment implements EnrichmentInterface private function collectMetaData(): void { - $set = AccountMeta::whereIn('name', [ + $set = AccountMeta::whereIn('name', [ 'is_multi_currency', 'include_net_worth', 'currency_id', @@ -343,11 +344,12 @@ class AccountEnrichment implements EnrichmentInterface 'liability_direction', 'interest', 'interest_period', - 'current_debt' + 'current_debt', ]) ->whereIn('account_id', $this->ids) ->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data']) - ->toArray(); + ->toArray() + ; /** @var array $entry */ foreach ($set as $entry) { @@ -378,7 +380,8 @@ class AccountEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', Account::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -387,12 +390,13 @@ class AccountEnrichment implements EnrichmentInterface private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', Account::class) - ->get(['object_groupable_id', 'object_group_id']); + ->get(['object_groupable_id', 'object_group_id']) + ; - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; @@ -400,8 +404,8 @@ class AccountEnrichment implements EnrichmentInterface $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int) $group['id']; - $group['order'] = (int) $group['order']; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; $this->objectGroups[(int) $group['id']] = $group; } } @@ -416,10 +420,11 @@ class AccountEnrichment implements EnrichmentInterface ->setUserGroup($this->userGroup) ->setAccounts($this->collection) ->withAccountInformation() - ->setTypes([TransactionTypeEnum::OPENING_BALANCE->value]); - $journals = $collector->getExtractedJournals(); + ->setTypes([TransactionTypeEnum::OPENING_BALANCE->value]) + ; + $journals = $collector->getExtractedJournals(); foreach ($journals as $journal) { - $this->openingBalances[(int) $journal['source_account_id']] = ['amount' => Steam::negative($journal['amount']), 'date' => $journal['date']]; + $this->openingBalances[(int) $journal['source_account_id']] = ['amount' => Steam::negative($journal['amount']), 'date' => $journal['date']]; $this->openingBalances[(int) $journal['destination_account_id']] = ['amount' => Steam::positive($journal['amount']), 'date' => $journal['date']]; } } @@ -434,7 +439,7 @@ class AccountEnrichment implements EnrichmentInterface } } - private function getBalanceDifference(int $id, TransactionCurrency $currency): null|string + private function getBalanceDifference(int $id, TransactionCurrency $currency): ?string { if (!$this->start instanceof Carbon || !$this->end instanceof Carbon) { return null; @@ -444,8 +449,8 @@ class AccountEnrichment implements EnrichmentInterface if (0 === count($startBalance) || 0 === count($endBalance)) { return null; } - $start = $startBalance[$currency->code] ?? '0'; - $end = $endBalance[$currency->code] ?? '0'; + $start = $startBalance[$currency->code] ?? '0'; + $end = $endBalance[$currency->code] ?? '0'; return bcsub($end, $start); } @@ -467,7 +472,7 @@ class AccountEnrichment implements EnrichmentInterface case 'current_balance': case 'pc_current_balance': $this->collection = $this->collection->sortBy( - static fn(Account $account) => $account->meta['balances'][$parameter[0]] ?? '0', + static fn (Account $account) => $account->meta['balances'][$parameter[0]] ?? '0', SORT_NUMERIC, 'desc' === $parameter[1] ); diff --git a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php index 5558ce620a..a0ce1f289b 100644 --- a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php @@ -42,24 +42,24 @@ class AvailableBudgetEnrichment implements EnrichmentInterface { private Collection $collection; // @phpstan-ignore-line private readonly bool $convertToPrimary; // @phpstan-ignore-line - private array $currencies = []; - private array $currencyIds = []; - private array $ids = []; + private array $currencies = []; + private array $currencyIds = []; + private array $ids = []; private readonly NoBudgetRepositoryInterface $noBudgetRepository; private readonly OperationsRepositoryInterface $opsRepository; private array $pcSpentInBudgets = []; private array $pcSpentOutsideBudgets = []; private readonly BudgetRepositoryInterface $repository; - private array $spentInBudgets = []; - private array $spentOutsideBudgets = []; + private array $spentInBudgets = []; + private array $spentOutsideBudgets = []; public function __construct() { // $this->primaryCurrency = Amount::getPrimaryCurrency(); - $this->convertToPrimary = Amount::convertToPrimary(); + $this->convertToPrimary = Amount::convertToPrimary(); $this->noBudgetRepository = app(NoBudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(BudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); } #[Override] @@ -111,7 +111,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface 'spent_in_budgets' => $this->spentInBudgets[$id] ?? [], 'pc_spent_in_budgets' => $this->pcSpentInBudgets[$id] ?? [], 'spent_outside_budgets' => $this->spentOutsideBudgets[$id] ?? [], - 'pc_spent_outside_budgets' => $this->pcSpentOutsideBudgets[$id] ?? [] + 'pc_spent_outside_budgets' => $this->pcSpentOutsideBudgets[$id] ?? [], ]; $item->meta = $meta; @@ -132,7 +132,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface { /** @var AvailableBudget $availableBudget */ foreach ($this->collection as $availableBudget) { - $this->ids[] = (int) $availableBudget->id; + $this->ids[] = (int) $availableBudget->id; $this->currencyIds[(int) $availableBudget->id] = (int) $availableBudget->transaction_currency_id; } $this->ids = array_unique($this->ids); @@ -146,40 +146,40 @@ class AvailableBudgetEnrichment implements EnrichmentInterface $spentInBudgets = $this->opsRepository->collectExpenses($start, $end, null, $allActive); $spentOutsideBudgets = $this->noBudgetRepository->collectExpenses($start, $end); foreach ($this->collection as $availableBudget) { - $id = (int) $availableBudget->id; - $currencyId = $this->currencyIds[$id]; - $currency = $this->currencies[$currencyId]; - $filteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( + $id = (int) $availableBudget->id; + $currencyId = $this->currencyIds[$id]; + $currency = $this->currencies[$currencyId]; + $filteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( $spentInBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency ); - $filteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( + $filteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( $spentOutsideBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency ); - $this->spentInBudgets[$id] = array_values($filteredSpentInBudgets); + $this->spentInBudgets[$id] = array_values($filteredSpentInBudgets); $this->spentOutsideBudgets[$id] = array_values($filteredSpentOutsideBudgets); if ($this->convertToPrimary) { - $pcFilteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( + $pcFilteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( $spentInBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true ); - $pcFilteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( + $pcFilteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( $spentOutsideBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true ); - $this->pcSpentInBudgets[$id] = array_values($pcFilteredSpentInBudgets); + $this->pcSpentInBudgets[$id] = array_values($pcFilteredSpentInBudgets); $this->pcSpentOutsideBudgets[$id] = array_values($pcFilteredSpentOutsideBudgets); } } diff --git a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php index 3053b17bf4..12386b34b0 100644 --- a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php @@ -39,17 +39,17 @@ use Illuminate\Support\Facades\Log; class BudgetEnrichment implements EnrichmentInterface { - private array $autoBudgets = []; + private array $autoBudgets = []; private Collection $collection; private array $currencies = []; - private null|Carbon $end = null; + private ?Carbon $end = null; private array $ids = []; private array $mappedObjects = []; private array $notes = []; private array $objectGroups = []; private array $pcSpent = []; private array $spent = []; - private null|Carbon $start = null; + private ?Carbon $start = null; private User $user; private UserGroup $userGroup; @@ -76,12 +76,12 @@ class BudgetEnrichment implements EnrichmentInterface return $collection->first(); } - public function setEnd(null|Carbon $end): void + public function setEnd(?Carbon $end): void { $this->end = $end; } - public function setStart(null|Carbon $start): void + public function setStart(?Carbon $start): void { $this->start = $start; } @@ -100,8 +100,8 @@ class BudgetEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Budget $item): Budget { - $id = (int) $item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'object_group_id' => null, 'object_group_order' => null, 'object_group_title' => null, @@ -109,13 +109,13 @@ class BudgetEnrichment implements EnrichmentInterface 'currency' => $this->currencies[$id] ?? null, 'auto_budget' => $this->autoBudgets[$id] ?? null, 'spent' => $this->spent[$id] ?? null, - 'pc_spent' => $this->pcSpent[$id] ?? null + 'pc_spent' => $this->pcSpent[$id] ?? null, ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } @@ -132,13 +132,13 @@ class BudgetEnrichment implements EnrichmentInterface /** @var AutoBudget $autoBudget */ foreach ($set as $autoBudget) { - $budgetId = (int) $autoBudget->budget_id; - $this->currencies[$budgetId] = $autoBudget->transactionCurrency; + $budgetId = (int) $autoBudget->budget_id; + $this->currencies[$budgetId] = $autoBudget->transactionCurrency; $this->autoBudgets[$budgetId] = [ 'type' => (int) $autoBudget->auto_budget_type, 'period' => $autoBudget->period, 'amount' => $autoBudget->amount, - 'pc_amount' => $autoBudget->native_amount + 'pc_amount' => $autoBudget->native_amount, ]; } } @@ -152,10 +152,10 @@ class BudgetEnrichment implements EnrichmentInterface $opsRepository->setUserGroup($this->userGroup); // $spent = $this->beautify(); // $set = $this->opsRepository->sumExpenses($start, $end, null, new Collection()->push($budget)) - $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); + $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); foreach ($this->collection as $item) { - $id = (int) $item->id; - $this->spent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item)); + $id = (int) $item->id; + $this->spent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item)); $this->pcSpent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item, true)); } } @@ -178,7 +178,8 @@ class BudgetEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', Budget::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -187,12 +188,13 @@ class BudgetEnrichment implements EnrichmentInterface private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', Budget::class) - ->get(['object_groupable_id', 'object_group_id']); + ->get(['object_groupable_id', 'object_group_id']) + ; - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; @@ -200,8 +202,8 @@ class BudgetEnrichment implements EnrichmentInterface $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int) $group['id']; - $group['order'] = (int) $group['order']; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; $this->objectGroups[(int) $group['id']] = $group; } } diff --git a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php index 865df49bd3..7834c19f67 100644 --- a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php @@ -44,10 +44,10 @@ class BudgetLimitEnrichment implements EnrichmentInterface private array $currencies = []; private array $currencyIds = []; private Carbon $end; - private array $expenses = []; - private array $ids = []; - private array $notes = []; - private array $pcExpenses = []; + private array $expenses = []; + private array $ids = []; + private array $notes = []; + private array $pcExpenses = []; private readonly TransactionCurrency $primaryCurrency; private Carbon $start; private User $user; @@ -55,7 +55,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface public function __construct() { $this->convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); } public function enrich(Collection $collection): Collection @@ -85,9 +85,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface $this->user = $user; } - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} private function appendCollectedData(): void { @@ -97,11 +95,11 @@ class BudgetLimitEnrichment implements EnrichmentInterface if (0 === $currencyId) { $currencyId = $this->primaryCurrency->id; } - $meta = [ + $meta = [ 'notes' => $this->notes[$id] ?? null, 'spent' => $this->expenses[$id] ?? [], 'pc_spent' => $this->pcExpenses[$id] ?? [], - 'currency' => $this->currencies[$currencyId] + 'currency' => $this->currencies[$currencyId], ]; $item->meta = $meta; @@ -111,22 +109,23 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function collectBudgets(): void { - $budgetIds = $this->collection + $budgetIds = $this->collection ->pluck('budget_id') ->unique() - ->toArray(); - $budgets = Budget::whereIn('id', $budgetIds)->get(); + ->toArray() + ; + $budgets = Budget::whereIn('id', $budgetIds)->get(); $repository = app(OperationsRepository::class); $repository->setUser($this->user); - $expenses = $repository->collectExpenses($this->start, $this->end, null, $budgets); + $expenses = $repository->collectExpenses($this->start, $this->end, null, $budgets); /** @var BudgetLimit $budgetLimit */ foreach ($this->collection as $budgetLimit) { Log::debug(sprintf('Filtering expenses for budget limit #%d (budget #%d)', $budgetLimit->id, $budgetLimit->budget_id)); - $id = (int) $budgetLimit->id; - $filteredExpenses = $this->filterToBudget($expenses, $budgetLimit->budget_id); - $filteredExpenses = $repository->sumCollectedExpenses( + $id = (int) $budgetLimit->id; + $filteredExpenses = $this->filterToBudget($expenses, $budgetLimit->budget_id); + $filteredExpenses = $repository->sumCollectedExpenses( $filteredExpenses, $budgetLimit->start_date, $budgetLimit->end_date, @@ -135,7 +134,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface $this->expenses[$id] = array_values($filteredExpenses); if ($this->convertToPrimary && $budgetLimit->transactionCurrency->id !== $this->primaryCurrency->id) { - $pcFilteredExpenses = $repository->sumCollectedExpenses( + $pcFilteredExpenses = $repository->sumCollectedExpenses( $expenses, $budgetLimit->start_date, $budgetLimit->end_date, @@ -153,7 +152,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function collectCurrencies(): void { $this->currencies[$this->primaryCurrency->id] = $this->primaryCurrency; - $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->whereNot('id', $this->primaryCurrency->id)->get(); + $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->whereNot('id', $this->primaryCurrency->id)->get(); foreach ($currencies as $currency) { $this->currencies[(int) $currency->id] = $currency; } @@ -161,21 +160,21 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function collectIds(): void { - $this->start = $this->collection->min('start_date') ?? Carbon::now()->startOfMonth(); - $this->end = $this->collection->max('end_date') ?? Carbon::now()->endOfMonth(); + $this->start = $this->collection->min('start_date') ?? Carbon::now()->startOfMonth(); + $this->end = $this->collection->max('end_date') ?? Carbon::now()->endOfMonth(); // #11096 make sure that the max end date is also at the end of the day, $this->end->endOfDay(); /** @var BudgetLimit $limit */ foreach ($this->collection as $limit) { - $id = (int) $limit->id; + $id = (int) $limit->id; $this->ids[] = $id; if (0 !== (int) $limit->transaction_currency_id) { $this->currencyIds[$id] = (int) $limit->transaction_currency_id; } } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); $this->currencyIds = array_unique($this->currencyIds); } @@ -187,7 +186,8 @@ class BudgetLimitEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', BudgetLimit::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -196,7 +196,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function filterToBudget(array $expenses, int $budget): array { - $result = array_filter($expenses, static fn(array $item): bool => (int) $item['budget_id'] === $budget); + $result = array_filter($expenses, static 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; @@ -204,13 +204,13 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function stringifyIds(): void { - $this->expenses = array_map(static fn($first): array => array_map(static function (array $second): array { + $this->expenses = array_map(static fn ($first): array => array_map(static function (array $second): array { $second['currency_id'] = (string) ($second['currency_id'] ?? 0); return $second; }, $first), $this->expenses); - $this->pcExpenses = array_map(static fn(array $first): array => array_map(static function (array $second): array { + $this->pcExpenses = array_map(static fn (array $first): array => array_map(static function (array $second): array { $second['currency_id'] ??= 0; return $second; diff --git a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php index c232b6a403..04f334946d 100644 --- a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php +++ b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php @@ -38,14 +38,14 @@ class CategoryEnrichment implements EnrichmentInterface { private Collection $collection; private array $earned = []; - private null|Carbon $end = null; + private ?Carbon $end = null; private array $ids = []; private array $notes = []; private array $pcEarned = []; private array $pcSpent = []; private array $pcTransfers = []; private array $spent = []; - private null|Carbon $start = null; + private ?Carbon $start = null; private array $transfers = []; private User $user; private UserGroup $userGroup; @@ -70,12 +70,12 @@ class CategoryEnrichment implements EnrichmentInterface return $collection->first(); } - public function setEnd(null|Carbon $end): void + public function setEnd(?Carbon $end): void { $this->end = $end; } - public function setStart(null|Carbon $start): void + public function setStart(?Carbon $start): void { $this->start = $start; } @@ -94,15 +94,15 @@ class CategoryEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Category $item): Category { - $id = (int) $item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'notes' => $this->notes[$id] ?? null, 'spent' => $this->spent[$id] ?? null, 'pc_spent' => $this->pcSpent[$id] ?? null, 'earned' => $this->earned[$id] ?? null, 'pc_earned' => $this->pcEarned[$id] ?? null, 'transfers' => $this->transfers[$id] ?? null, - 'pc_transfers' => $this->pcTransfers[$id] ?? null + 'pc_transfers' => $this->pcTransfers[$id] ?? null, ]; $item->meta = $meta; @@ -127,7 +127,8 @@ class CategoryEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', Category::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -141,16 +142,16 @@ class CategoryEnrichment implements EnrichmentInterface $opsRepository = app(OperationsRepositoryInterface::class); $opsRepository->setUser($this->user); $opsRepository->setUserGroup($this->userGroup); - $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); - $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection); - $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection); + $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); + $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection); + $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection); foreach ($this->collection as $item) { - $id = (int) $item->id; - $this->spent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative')); - $this->pcSpent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative', true)); - $this->earned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive')); - $this->pcEarned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive', true)); - $this->transfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive')); + $id = (int) $item->id; + $this->spent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative')); + $this->pcSpent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative', true)); + $this->earned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive')); + $this->pcEarned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive', true)); + $this->transfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive')); $this->pcTransfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive', true)); } } diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php index b0a02c7039..8cb9e0cebc 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php @@ -42,24 +42,24 @@ use Illuminate\Support\Facades\Log; class PiggyBankEnrichment implements EnrichmentInterface { - private array $accountIds = []; // @phpstan-ignore-line - private array $accounts = []; // @phpstan-ignore-line - private array $amounts = []; + private array $accountIds = []; // @phpstan-ignore-line + private array $accounts = []; // @phpstan-ignore-line + private array $amounts = []; private Collection $collection; - private array $currencies = []; - private array $currencyIds = []; - private array $ids = []; + private array $currencies = []; + private array $currencyIds = []; + private array $ids = []; // private array $accountCurrencies = []; private array $mappedObjects = []; private array $notes = []; private array $objectGroups = []; private readonly TransactionCurrency $primaryCurrency; - private null|Carbon $date; + private ?Carbon $date; public function __construct() { $this->primaryCurrency = Amount::getPrimaryCurrency(); - $this->date = now(config('app.timezone')); + $this->date = now(config('app.timezone')); } public function enrich(Collection $collection): Collection @@ -88,23 +88,21 @@ class PiggyBankEnrichment implements EnrichmentInterface $this->setUserGroup($user->userGroup); } - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} private function appendCollectedData(): void { $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; - $targetAmount = null; + $id = (int) $item->id; + $currencyId = (int) $item->transaction_currency_id; + $currency = $this->currencies[$currencyId] ?? $this->primaryCurrency; + $targetAmount = null; if (0 !== bccomp($item->target_amount, '0')) { $targetAmount = $item->target_amount; } - $meta = [ - 'notes' => $this->notes[$id] ?? null, - 'currency' => $this->currencies[$currencyId] ?? null, + $meta = [ + 'notes' => $this->notes[$id] ?? null, + 'currency' => $this->currencies[$currencyId] ?? null, // 'auto_budget' => $this->autoBudgets[$id] ?? null, // 'spent' => $this->spent[$id] ?? null, // 'pc_spent' => $this->pcSpent[$id] ?? null, @@ -121,31 +119,31 @@ class PiggyBankEnrichment implements EnrichmentInterface 'pc_left_to_save' => null, 'save_per_month' => null, 'pc_save_per_month' => null, - 'accounts' => [] + 'accounts' => [], ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } // add current amount(s). foreach ($this->amounts[$id] as $accountId => $row) { - $meta['accounts'][] = [ + $meta['accounts'][] = [ 'account_id' => (string) $accountId, 'name' => $this->accounts[$accountId]['name'] ?? '', 'current_amount' => Steam::bcround($row['current_amount'], $currency->decimal_places), - 'pc_current_amount' => Steam::bcround($row['pc_current_amount'], $this->primaryCurrency->decimal_places) + 'pc_current_amount' => Steam::bcround($row['pc_current_amount'], $this->primaryCurrency->decimal_places), ]; - $meta['current_amount'] = bcadd($meta['current_amount'], (string) $row['current_amount']); + $meta['current_amount'] = bcadd($meta['current_amount'], (string) $row['current_amount']); // only add pc_current_amount when the pc_current_amount is set $meta['pc_current_amount'] = null === $row['pc_current_amount'] ? null : bcadd((string) $meta['pc_current_amount'], (string) $row['pc_current_amount']); } - $meta['current_amount'] = Steam::bcround($meta['current_amount'], $currency->decimal_places); + $meta['current_amount'] = Steam::bcround($meta['current_amount'], $currency->decimal_places); // only round this number when pc_current_amount is set. $meta['pc_current_amount'] = null === $meta['pc_current_amount'] ? null @@ -153,14 +151,14 @@ class PiggyBankEnrichment implements EnrichmentInterface // calculate left to save, only when there is a target amount. if (null !== $targetAmount) { - $meta['left_to_save'] = bcsub((string) $meta['target_amount'], (string) $meta['current_amount']); + $meta['left_to_save'] = bcsub((string) $meta['target_amount'], (string) $meta['current_amount']); $meta['pc_left_to_save'] = null === $meta['pc_target_amount'] ? null : bcsub((string) $meta['pc_target_amount'], (string) $meta['pc_current_amount']); } // get suggested per month. - $meta['save_per_month'] = Steam::bcround( + $meta['save_per_month'] = Steam::bcround( $this->getSuggestedMonthlyAmount($this->date, $item->target_date, $meta['target_amount'], $meta['current_amount']), $currency->decimal_places ); @@ -171,13 +169,13 @@ class PiggyBankEnrichment implements EnrichmentInterface ); } - $item->meta = $meta; + $item->meta = $meta; return $item; }); } - public function setDate(null|Carbon $date): void + public function setDate(?Carbon $date): void { $this->date = $date; } @@ -186,11 +184,11 @@ class PiggyBankEnrichment implements EnrichmentInterface { /** @var PiggyBank $piggy */ foreach ($this->collection as $piggy) { - $id = (int) $piggy->id; - $this->ids[] = $id; + $id = (int) $piggy->id; + $this->ids[] = $id; $this->currencyIds[$id] = (int) $piggy->transaction_currency_id; } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); // collect currencies. $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->get(); @@ -199,15 +197,15 @@ class PiggyBankEnrichment implements EnrichmentInterface } // collect accounts - $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->ids)->get([ + $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->ids)->get([ 'piggy_bank_id', 'account_id', 'current_amount', - 'native_current_amount' + 'native_current_amount', ]); foreach ($set as $item) { - $id = (int) $item->piggy_bank_id; - $accountId = (int) $item->account_id; + $id = (int) $item->piggy_bank_id; + $accountId = (int) $item->account_id; $this->amounts[$id] ??= []; if (!array_key_exists($id, $this->accountIds)) { $this->accountIds[$id] = (int) $item->account_id; @@ -228,7 +226,7 @@ class PiggyBankEnrichment implements EnrichmentInterface } // get account currency preference for ALL. - $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); + $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($set as $item) { @@ -242,11 +240,11 @@ class PiggyBankEnrichment implements EnrichmentInterface } // get account info. - $set = Account::whereIn('id', array_values($this->accountIds))->get(); + $set = Account::whereIn('id', array_values($this->accountIds))->get(); /** @var Account $item */ foreach ($set as $item) { - $id = (int) $item->id; + $id = (int) $item->id; $this->accounts[$id] = ['id' => $id, 'name' => $item->name]; } } @@ -259,7 +257,8 @@ class PiggyBankEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', PiggyBank::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -268,12 +267,13 @@ class PiggyBankEnrichment implements EnrichmentInterface private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', PiggyBank::class) - ->get(['object_groupable_id', 'object_group_id']); + ->get(['object_groupable_id', 'object_group_id']) + ; - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; @@ -281,8 +281,8 @@ class PiggyBankEnrichment implements EnrichmentInterface $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int) $group['id']; - $group['order'] = (int) $group['order']; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; $this->objectGroups[(int) $group['id']] = $group; } } @@ -290,7 +290,7 @@ class PiggyBankEnrichment implements EnrichmentInterface /** * Returns the suggested amount the user should save per month, or "". */ - private function getSuggestedMonthlyAmount(null|Carbon $startDate, null|Carbon $targetDate, null|string $targetAmount, string $currentAmount): string + private function getSuggestedMonthlyAmount(?Carbon $startDate, ?Carbon $targetDate, ?string $targetAmount, string $currentAmount): string { if (null === $targetAmount || !$targetDate instanceof Carbon || !$startDate instanceof Carbon) { return '0'; diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php index 9c491f40ac..d15814f937 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php @@ -38,13 +38,13 @@ use Illuminate\Support\Facades\Log; class PiggyBankEventEnrichment implements EnrichmentInterface { private array $accountCurrencies = []; // @phpstan-ignore-line - private array $accountIds = []; // @phpstan-ignore-line + private array $accountIds = []; // @phpstan-ignore-line private Collection $collection; - private array $currencies = []; - private array $groupIds = []; - private array $ids = []; - private array $journalIds = []; - private array $piggyBankIds = []; + private array $currencies = []; + private array $groupIds = []; + private array $ids = []; + private array $journalIds = []; + private array $piggyBankIds = []; // private bool $convertToPrimary = false; // private TransactionCurrency $primaryCurrency; @@ -78,26 +78,24 @@ class PiggyBankEventEnrichment implements EnrichmentInterface $this->setUserGroup($user->userGroup); } - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} private function appendCollectedData(): void { $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; - $currency = null; + $id = (int) $item->id; + $piggyId = (int) $item->piggy_bank_id; + $journalId = (int) $item->transaction_journal_id; + $currency = null; if (array_key_exists($piggyId, $this->accountIds)) { $accountId = $this->accountIds[$piggyId]; if (array_key_exists($accountId, $this->accountCurrencies)) { $currency = $this->accountCurrencies[$accountId]; } } - $meta = [ + $meta = [ 'transaction_group_id' => array_key_exists($journalId, $this->groupIds) ? (string) $this->groupIds[$journalId] : null, - 'currency' => $currency + 'currency' => $currency, ]; $item->meta = $meta; @@ -109,13 +107,13 @@ class PiggyBankEventEnrichment implements EnrichmentInterface { /** @var PiggyBankEvent $event */ foreach ($this->collection as $event) { - $this->ids[] = (int) $event->id; - $this->journalIds[(int) $event->id] = (int) $event->transaction_journal_id; + $this->ids[] = (int) $event->id; + $this->journalIds[(int) $event->id] = (int) $event->transaction_journal_id; $this->piggyBankIds[(int) $event->id] = (int) $event->piggy_bank_id; } $this->ids = array_unique($this->ids); // collect groups with journal info. - $set = TransactionJournal::whereIn('id', $this->journalIds)->get(['id', 'transaction_group_id']); + $set = TransactionJournal::whereIn('id', $this->journalIds)->get(['id', 'transaction_group_id']); /** @var TransactionJournal $item */ foreach ($set as $item) { @@ -123,7 +121,7 @@ class PiggyBankEventEnrichment implements EnrichmentInterface } // collect account info. - $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->piggyBankIds)->get(['piggy_bank_id', 'account_id']); + $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->piggyBankIds)->get(['piggy_bank_id', 'account_id']); foreach ($set as $item) { $id = (int) $item->piggy_bank_id; if (!array_key_exists($id, $this->accountIds)) { @@ -132,12 +130,12 @@ class PiggyBankEventEnrichment implements EnrichmentInterface } // get account currency preference for ALL. - $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); + $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($set as $item) { - $accountId = (int) $item->account_id; - $currencyId = (int) $item->data; + $accountId = (int) $item->account_id; + $currencyId = (int) $item->data; if (!array_key_exists($currencyId, $this->currencies)) { $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId); } diff --git a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php index dba219d7a4..47efd78c75 100644 --- a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php +++ b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php @@ -55,18 +55,18 @@ use function Safe\json_decode; class RecurringEnrichment implements EnrichmentInterface { - private array $accounts = []; + private array $accounts = []; private Collection $collection; // private array $transactionTypeIds = []; // private array $transactionTypes = []; private readonly bool $convertToPrimary; - private array $currencies = []; - private array $currencyIds = []; - private array $destinationAccountIds = []; - private array $foreignCurrencyIds = []; - private array $ids = []; - private string $language = 'en_US'; - private array $notes = []; + private array $currencies = []; + private array $currencyIds = []; + private array $destinationAccountIds = []; + private array $foreignCurrencyIds = []; + private array $ids = []; + private string $language = 'en_US'; + private array $notes = []; private readonly TransactionCurrency $primaryCurrency; private array $recurrenceByTransaction = []; private array $repetitions = []; @@ -77,7 +77,7 @@ class RecurringEnrichment implements EnrichmentInterface public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -144,7 +144,7 @@ class RecurringEnrichment implements EnrichmentInterface ); } if ('ndom' === $repetition->repetition_type) { - $parts = explode(',', $repetition->repetition_moment); + $parts = explode(',', $repetition->repetition_moment); // first part is number of week, second is weekday. $dayOfWeek = trans(sprintf('config.dow_%s', $parts[1]), [], $this->language); if ($repetition->repetition_skip > 0) { @@ -165,7 +165,7 @@ class RecurringEnrichment implements EnrichmentInterface } // $diffInYears = (int)$today->diffInYears($repDate, true); // $repDate->addYears($diffInYears); // technically not necessary. - $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); + $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); return (string) trans('firefly.recurring_yearly', ['date' => $string], $this->language); } @@ -188,11 +188,11 @@ class RecurringEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Recurrence $item): Recurrence { - $id = (int) $item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'notes' => $this->notes[$id] ?? null, 'repetitions' => array_values($this->repetitions[$id] ?? []), - 'transactions' => $this->processTransactions(array_values($this->transactions[$id] ?? [])) + 'transactions' => $this->processTransactions(array_values($this->transactions[$id] ?? [])), ]; $item->meta = $meta; @@ -208,7 +208,7 @@ class RecurringEnrichment implements EnrichmentInterface /** @var Account $account */ foreach ($accounts as $account) { - $id = (int) $account->id; + $id = (int) $account->id; $this->accounts[$id] = $account; Log::debug(sprintf('Collected account #%d', $id)); } @@ -226,8 +226,8 @@ class RecurringEnrichment implements EnrichmentInterface $mapped[(int) $bill->id] = $bill; } foreach ($billIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['subscription_name'] = $mapped[$info['bill_id']]->name ?? ''; } } @@ -244,8 +244,8 @@ class RecurringEnrichment implements EnrichmentInterface $mapped[(int) $category->id] = $category; } foreach ($budgetIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['budget_name'] = $mapped[$info['budget_id']]->name ?? ''; } } @@ -262,8 +262,8 @@ class RecurringEnrichment implements EnrichmentInterface $mapped[(int) $category->id] = $category; } foreach ($categoryIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['category_name'] = $mapped[$info['category_id']]->name ?? ''; } } @@ -283,7 +283,7 @@ class RecurringEnrichment implements EnrichmentInterface $transactionId = $info['transaction_id']; $category = $factory->findOrCreate(null, $info['category_name']); if (null !== $category) { - $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string) $category->id; + $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string) $category->id; $this->transactions[$recurrenceId][$transactionId]['category_name'] = $category->name; } } @@ -294,7 +294,7 @@ class RecurringEnrichment implements EnrichmentInterface $all = array_merge(array_unique($this->currencyIds), array_unique($this->foreignCurrencyIds)); $currencies = TransactionCurrency::whereIn('id', array_unique($all))->get(); foreach ($currencies as $currency) { - $id = (int) $currency->id; + $id = (int) $currency->id; $this->currencies[$id] = $currency; Log::debug(sprintf('Collected currency #%d', $id)); } @@ -304,7 +304,7 @@ class RecurringEnrichment implements EnrichmentInterface { /** @var Recurrence $recurrence */ foreach ($this->collection as $recurrence) { - $id = (int) $recurrence->id; + $id = (int) $recurrence->id; $this->ids[] = $id; Log::debug(sprintf('Collected recurrence id #%d', $id)); } @@ -320,9 +320,10 @@ class RecurringEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', Recurrence::class) ->get(['notes.id', 'notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { - $notableId = (int) $note['noteable_id']; + $notableId = (int) $note['noteable_id']; $this->notes[$notableId] = (string) $note['text']; Log::debug(sprintf('Collected note #%d for recurrence #%d', $note['id'], $notableId)); } @@ -341,8 +342,8 @@ class RecurringEnrichment implements EnrichmentInterface $mapped[(int) $piggyBank->id] = $piggyBank; } foreach ($piggyBankIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['piggy_bank_name'] = $mapped[$info['piggy_bank_id']]->name ?? ''; } } @@ -352,21 +353,21 @@ class RecurringEnrichment implements EnrichmentInterface Log::debug('Start of enrichment: collectRepetitions()'); $repository = app(RecurringRepositoryInterface::class); $repository->setUserGroup($this->userGroup); - $set = RecurrenceRepetition::whereIn('recurrence_id', $this->ids)->get(); + $set = RecurrenceRepetition::whereIn('recurrence_id', $this->ids)->get(); /** @var RecurrenceRepetition $repetition */ foreach ($set as $repetition) { - $recurrence = $this->collection->filter(static fn(Recurrence $item): bool => (int) $item->id === (int) $repetition->recurrence_id)->first(); - $fromDate = clone ($recurrence->latest_date ?? $recurrence->first_date); - $recurrenceId = (int) $repetition->recurrence_id; - $repId = (int) $repetition->id; + $recurrence = $this->collection->filter(static fn (Recurrence $item): bool => (int) $item->id === (int) $repetition->recurrence_id)->first(); + $fromDate = clone ($recurrence->latest_date ?? $recurrence->first_date); + $recurrenceId = (int) $repetition->recurrence_id; + $repId = (int) $repetition->id; $this->repetitions[$recurrenceId] ??= []; Log::debug(sprintf('Collected repetition #%d of recurrence #%d.', $repId, $recurrenceId)); // get the (future) occurrences for this specific type of repetition: - $amount = 'daily' === $repetition->repetition_type ? 9 : 5; - $set = $repository->getXOccurrencesSince($repetition, $fromDate, now(config('app.timezone')), $amount); - $occurrences = []; + $amount = 'daily' === $repetition->repetition_type ? 9 : 5; + $set = $repository->getXOccurrencesSince($repetition, $fromDate, now(config('app.timezone')), $amount); + $occurrences = []; /** @var Carbon $carbon */ foreach ($set as $carbon) { @@ -381,7 +382,7 @@ class RecurringEnrichment implements EnrichmentInterface 'skip' => (int) $repetition->repetition_skip, 'weekend' => RecurrenceRepetitionWeekend::from((int) $repetition->weekend)->value, 'description' => $this->getRepetitionDescription($repetition), - 'occurrences' => $occurrences + 'occurrences' => $occurrences, ]; } Log::debug('End of enrichment: collectRepetitions()'); @@ -389,11 +390,11 @@ class RecurringEnrichment implements EnrichmentInterface private function collectTransactionMetaData(): void { - $rtIds = []; + $rtIds = []; foreach ($this->ids as $recurrenceId) { $rtIds = array_merge($rtIds, array_keys($this->transactions[$recurrenceId])); } - $meta = RecurrenceTransactionMeta::whereNull('deleted_at')->whereIn('rt_id', $rtIds)->get(); + $meta = RecurrenceTransactionMeta::whereNull('deleted_at')->whereIn('rt_id', $rtIds)->get(); // other meta-data to be collected: $billIds = []; $piggyBankIds = []; @@ -405,9 +406,9 @@ class RecurringEnrichment implements EnrichmentInterface $transactionId = (int) $entry->rt_id; // this should refer to another array, were rtIds can be used to find the recurrence. - $recurrenceId = $this->recurrenceByTransaction[$transactionId] ?? 0; + $recurrenceId = $this->recurrenceByTransaction[$transactionId] ?? 0; Log::debug(sprintf('Collecting meta data entry #%d for recurrence transaction #%d, for recurrence #%d ', $id, $transactionId, $recurrenceId)); - $name = (string) ($entry->name ?? ''); + $name = (string) ($entry->name ?? ''); if (0 === $recurrenceId) { Log::error(sprintf('Could not find recurrence ID for recurrence transaction ID #%d', $transactionId)); @@ -440,7 +441,7 @@ class RecurringEnrichment implements EnrichmentInterface $piggyBankIds[$id] = [ 'recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, - 'piggy_bank_id' => (int) $entry->value + 'piggy_bank_id' => (int) $entry->value, ]; } } @@ -454,7 +455,7 @@ class RecurringEnrichment implements EnrichmentInterface $categoryIds[$id] = [ 'recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, - 'category_id' => (int) $entry->value + 'category_id' => (int) $entry->value, ]; } } @@ -495,12 +496,12 @@ class RecurringEnrichment implements EnrichmentInterface /** @var RecurrenceTransaction $transaction */ foreach ($set as $transaction) { - $recurrenceId = (int) $transaction->recurrence_id; - $transactionId = (int) $transaction->id; - $this->recurrenceByTransaction[$transactionId] = $recurrenceId; + $recurrenceId = (int) $transaction->recurrence_id; + $transactionId = (int) $transaction->id; + $this->recurrenceByTransaction[$transactionId] = $recurrenceId; $this->transactions[$recurrenceId] ??= []; - $amount = $transaction->amount; - $foreignAmount = $transaction->foreign_amount; + $amount = $transaction->amount; + $foreignAmount = $transaction->foreign_amount; Log::debug(sprintf('Collected transaction #%d of recurrence #%d', $transactionId, $recurrenceId)); $this->transactions[$recurrenceId][$transactionId] = [ @@ -523,12 +524,12 @@ class RecurringEnrichment implements EnrichmentInterface 'piggy_bank_id' => null, 'piggy_bank_name' => null, 'subscription_id' => null, - 'subscription_name' => null + 'subscription_name' => null, ]; // collect all kinds of meta-data to be collected later. - $this->currencyIds[$transactionId] = (int) $transaction->transaction_currency_id; - $this->sourceAccountIds[$transactionId] = (int) $transaction->source_id; - $this->destinationAccountIds[$transactionId] = (int) $transaction->destination_id; + $this->currencyIds[$transactionId] = (int) $transaction->transaction_currency_id; + $this->sourceAccountIds[$transactionId] = (int) $transaction->source_id; + $this->destinationAccountIds[$transactionId] = (int) $transaction->destination_id; if (null !== $transaction->foreign_currency_id) { $this->foreignCurrencyIds[$transactionId] = (int) $transaction->foreign_currency_id; } @@ -538,12 +539,12 @@ class RecurringEnrichment implements EnrichmentInterface private function getLanguage(): void { /** @var Preference $preference */ - $preference = Preferences::getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); - $language = $preference->data; + $preference = Preferences::getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); + $language = $preference->data; if (is_array($language)) { $language = 'en_US'; } - $language = (string) $language; + $language = (string) $language; $this->language = $language; } @@ -552,9 +553,9 @@ class RecurringEnrichment implements EnrichmentInterface $return = []; $converter = new ExchangeRateConverter(); foreach ($transactions as $transaction) { - $currencyId = $transaction['transaction_currency_id']; - $pcAmount = null; - $pcForeignAmount = null; + $currencyId = $transaction['transaction_currency_id']; + $pcAmount = null; + $pcForeignAmount = null; // set the same amount in the primary currency, if both are the same anyway. if ($this->convertToPrimary && $currencyId === (int) $this->primaryCurrency->id) { $pcAmount = $transaction['amount']; @@ -575,48 +576,48 @@ class RecurringEnrichment implements EnrichmentInterface } } - $transaction['pc_amount'] = $pcAmount; - $transaction['pc_foreign_amount'] = $pcForeignAmount; + $transaction['pc_amount'] = $pcAmount; + $transaction['pc_foreign_amount'] = $pcForeignAmount; - $sourceId = $transaction['source_id']; - $transaction['source_name'] = $this->accounts[$sourceId]->name; - $transaction['source_iban'] = $this->accounts[$sourceId]->iban; - $transaction['source_type'] = $this->accounts[$sourceId]->accountType->type; - $transaction['source_id'] = (string) $transaction['source_id']; + $sourceId = $transaction['source_id']; + $transaction['source_name'] = $this->accounts[$sourceId]->name; + $transaction['source_iban'] = $this->accounts[$sourceId]->iban; + $transaction['source_type'] = $this->accounts[$sourceId]->accountType->type; + $transaction['source_id'] = (string) $transaction['source_id']; - $destId = $transaction['destination_id']; - $transaction['destination_name'] = $this->accounts[$destId]->name; - $transaction['destination_iban'] = $this->accounts[$destId]->iban; - $transaction['destination_type'] = $this->accounts[$destId]->accountType->type; - $transaction['destination_id'] = (string) $transaction['destination_id']; + $destId = $transaction['destination_id']; + $transaction['destination_name'] = $this->accounts[$destId]->name; + $transaction['destination_iban'] = $this->accounts[$destId]->iban; + $transaction['destination_type'] = $this->accounts[$destId]->accountType->type; + $transaction['destination_id'] = (string) $transaction['destination_id']; - $transaction['currency_id'] = (string) $currencyId; - $transaction['currency_name'] = $this->currencies[$currencyId]->name; - $transaction['currency_code'] = $this->currencies[$currencyId]->code; - $transaction['currency_symbol'] = $this->currencies[$currencyId]->symbol; - $transaction['currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; + $transaction['currency_id'] = (string) $currencyId; + $transaction['currency_name'] = $this->currencies[$currencyId]->name; + $transaction['currency_code'] = $this->currencies[$currencyId]->code; + $transaction['currency_symbol'] = $this->currencies[$currencyId]->symbol; + $transaction['currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; - $transaction['primary_currency_id'] = (string) $this->primaryCurrency->id; - $transaction['primary_currency_name'] = $this->primaryCurrency->name; - $transaction['primary_currency_code'] = $this->primaryCurrency->code; - $transaction['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $transaction['primary_currency_id'] = (string) $this->primaryCurrency->id; + $transaction['primary_currency_name'] = $this->primaryCurrency->name; + $transaction['primary_currency_code'] = $this->primaryCurrency->code; + $transaction['primary_currency_symbol'] = $this->primaryCurrency->symbol; $transaction['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; // $transaction['foreign_currency_id'] = null; - $transaction['foreign_currency_name'] = null; - $transaction['foreign_currency_code'] = null; - $transaction['foreign_currency_symbol'] = null; + $transaction['foreign_currency_name'] = null; + $transaction['foreign_currency_code'] = null; + $transaction['foreign_currency_symbol'] = null; $transaction['foreign_currency_decimal_places'] = null; if (null !== $transaction['foreign_currency_id']) { - $currencyId = $transaction['foreign_currency_id']; - $transaction['foreign_currency_id'] = (string) $currencyId; - $transaction['foreign_currency_name'] = $this->currencies[$currencyId]->name; - $transaction['foreign_currency_code'] = $this->currencies[$currencyId]->code; - $transaction['foreign_currency_symbol'] = $this->currencies[$currencyId]->symbol; + $currencyId = $transaction['foreign_currency_id']; + $transaction['foreign_currency_id'] = (string) $currencyId; + $transaction['foreign_currency_name'] = $this->currencies[$currencyId]->name; + $transaction['foreign_currency_code'] = $this->currencies[$currencyId]->code; + $transaction['foreign_currency_symbol'] = $this->currencies[$currencyId]->symbol; $transaction['foreign_currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; } unset($transaction['transaction_currency_id']); - $return[] = $transaction; + $return[] = $transaction; } return $return; diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php index 0651e10551..d66f0cd2cd 100644 --- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php +++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php @@ -48,21 +48,21 @@ class SubscriptionEnrichment implements EnrichmentInterface private BillDateCalculator $calculator; private Collection $collection; // @phpstan-ignore-line private readonly bool $convertToPrimary; - private null|Carbon $end = null; - private array $mappedObjects = []; - private array $notes = []; - private array $objectGroups = []; - private array $paidDates = []; - private array $payDates = []; + private ?Carbon $end = null; + private array $mappedObjects = []; + private array $notes = []; + private array $objectGroups = []; + private array $paidDates = []; + private array $payDates = []; private readonly TransactionCurrency $primaryCurrency; - private null|Carbon $start = null; + private ?Carbon $start = null; private array $subscriptionIds = []; private User $user; public function __construct() { $this->convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); } public function enrich(Collection $collection): Collection @@ -78,15 +78,15 @@ class SubscriptionEnrichment implements EnrichmentInterface // TODO clean me up. - $notes = $this->notes; - $paidDates = $this->paidDates; - $payDates = $this->payDates; + $notes = $this->notes; + $paidDates = $this->paidDates; + $payDates = $this->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] ?? []); + $id = (int) $item->id; + $currency = $item->transactionCurrency; + $nem = $this->getNextExpectedMatch($payDates[$id] ?? []); - $meta = [ + $meta = [ 'notes' => null, 'object_group_id' => null, 'object_group_title' => null, @@ -95,25 +95,25 @@ class SubscriptionEnrichment implements EnrichmentInterface 'paid_dates' => $this->filterPaidDates($paidDates[$id] ?? []), 'pay_dates' => $payDates[$id] ?? [], 'nem' => $nem, - 'nem_diff' => $this->getNextExpectedMatchDiff($nem, $payDates[$id] ?? []) + 'nem_diff' => $this->getNextExpectedMatchDiff($nem, $payDates[$id] ?? []), ]; - $amounts = [ + $amounts = [ 'amount_min' => Steam::bcround($item->amount_min, $currency->decimal_places), 'amount_max' => Steam::bcround($item->amount_max, $currency->decimal_places), 'average' => Steam::bcround(bcdiv(bcadd($item->amount_min, $item->amount_max), '2'), $currency->decimal_places), 'pc_amount_min' => null, 'pc_amount_max' => null, - 'pc_average' => null + 'pc_average' => null, ]; if ($this->convertToPrimary && $currency->id === $this->primaryCurrency->id) { $amounts['pc_amount_min'] = $amounts['amount_min']; $amounts['pc_amount_max'] = $amounts['amount_max']; - $amounts['pc_average'] = $amounts['average']; + $amounts['pc_average'] = $amounts['average']; } if ($this->convertToPrimary && $currency->id !== $this->primaryCurrency->id) { $amounts['pc_amount_min'] = Steam::bcround($item->native_amount_min, $this->primaryCurrency->decimal_places); $amounts['pc_amount_max'] = Steam::bcround($item->native_amount_max, $this->primaryCurrency->decimal_places); - $amounts['pc_average'] = Steam::bcround( + $amounts['pc_average'] = Steam::bcround( bcdiv(bcadd($item->native_amount_min, $item->native_amount_max), '2'), $this->primaryCurrency->decimal_places ); @@ -123,7 +123,7 @@ class SubscriptionEnrichment implements EnrichmentInterface if (array_key_exists($id, $this->mappedObjects)) { $key = $this->mappedObjects[$id]; if (array_key_exists($key, $this->objectGroups)) { - $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } @@ -135,7 +135,7 @@ class SubscriptionEnrichment implements EnrichmentInterface } $item->amounts = $amounts; - $item->meta = $meta; + $item->meta = $meta; return $item; }); @@ -152,12 +152,12 @@ class SubscriptionEnrichment implements EnrichmentInterface return $collection->first(); } - public function setEnd(null|Carbon $end): void + public function setEnd(?Carbon $end): void { $this->end = $end; } - public function setStart(null|Carbon $start): void + public function setStart(?Carbon $start): void { $this->start = $start; } @@ -167,22 +167,20 @@ class SubscriptionEnrichment implements EnrichmentInterface $this->user = $user; } - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} /** * Returns the latest date in the set, or start when set is empty. */ protected function lastPaidDate(Bill $subscription, Collection $dates, Carbon $default): Carbon { - $filtered = $dates->filter(static fn(TransactionJournal $journal): bool => (int) $journal->bill_id === (int) $subscription->id); + $filtered = $dates->filter(static 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; } - $latest = $filtered->first()->date; + $latest = $filtered->first()->date; /** @var TransactionJournal $journal */ foreach ($filtered as $journal) { @@ -202,7 +200,8 @@ class SubscriptionEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', Bill::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -211,12 +210,13 @@ class SubscriptionEnrichment implements EnrichmentInterface private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->subscriptionIds) ->where('object_groupable_type', Bill::class) - ->get(['object_groupable_id', 'object_group_id']); + ->get(['object_groupable_id', 'object_group_id']) + ; - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; @@ -224,8 +224,8 @@ class SubscriptionEnrichment implements EnrichmentInterface $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int) $group['id']; - $group['order'] = (int) $group['order']; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; $this->objectGroups[(int) $group['id']] = $group; } } @@ -244,13 +244,13 @@ class SubscriptionEnrichment implements EnrichmentInterface // 2023-07-18 this particular date is used to search for the last paid date. // 2023-07-18 the cloned $searchDate is used to grab the correct transactions. /** @var Carbon $start */ - $start = clone $this->start; - $searchStart = clone $start; + $start = clone $this->start; + $searchStart = clone $start; $start->subDay(); /** @var Carbon $end */ - $end = clone $this->end; - $searchEnd = clone $end; + $end = clone $this->end; + $searchEnd = clone $end; // move the search dates to the start of the day. $searchStart->startOfDay(); @@ -259,7 +259,7 @@ class SubscriptionEnrichment implements EnrichmentInterface Log::debug(sprintf('Search parameters are: start: %s, end: %s', $searchStart->format('Y-m-d H:i:s'), $searchEnd->format('Y-m-d H:i:s'))); // Get from database when bills were paid. - $set = $this->user + $set = $this->user ->transactionJournals() ->whereIn('bill_id', $this->subscriptionIds) ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') @@ -282,25 +282,26 @@ class SubscriptionEnrichment implements EnrichmentInterface 'foreign_currency.symbol AS foreign_currency_symbol', 'foreign_currency.decimal_places AS foreign_currency_decimal_places', 'transactions.amount', - 'transactions.foreign_amount' - ]); + 'transactions.foreign_amount', + ]) + ; Log::debug(sprintf('Count %d entries in set', $set->count())); // for each bill, do a loop. - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); /** @var Bill $subscription */ foreach ($this->collection as $subscription) { // Grab from array the most recent payment. If none exist, fall back to the start date and pretend *that* was the last paid date. Log::debug(sprintf('Grab last paid date from function, return %s if it comes up with nothing.', $start->format('Y-m-d'))); - $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); + $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); Log::debug(sprintf('Result of lastPaidDate is %s', $lastPaidDate->format('Y-m-d'))); // At this point the "next match" is exactly after the last time the bill was paid. - $result = []; - $filtered = $set->filter(static fn(TransactionJournal $journal): bool => (int) $journal->bill_id === (int) $subscription->id); + $result = []; + $filtered = $set->filter(static fn (TransactionJournal $journal): bool => (int) $journal->bill_id === (int) $subscription->id); foreach ($filtered as $entry) { - $array = [ + $array = [ 'transaction_group_id' => (string) $entry->transaction_group_id, 'transaction_journal_id' => (string) $entry->id, 'date' => $entry->date->toAtomString(), @@ -317,14 +318,14 @@ class SubscriptionEnrichment implements EnrichmentInterface 'amount' => Steam::bcround($entry->amount, $entry->transaction_currency_decimal_places), 'pc_amount' => null, 'foreign_amount' => null, - 'pc_foreign_amount' => null + 'pc_foreign_amount' => null, ]; if (null !== $entry->foreign_amount && null !== $entry->foreign_currency_code) { - $array['foreign_currency_id'] = (string) $entry->foreign_currency_id; - $array['foreign_currency_code'] = $entry->foreign_currency_code; - $array['foreign_currency_symbol'] = $entry->foreign_currency_symbol; + $array['foreign_currency_id'] = (string) $entry->foreign_currency_id; + $array['foreign_currency_code'] = $entry->foreign_currency_code; + $array['foreign_currency_symbol'] = $entry->foreign_currency_symbol; $array['foreign_currency_decimal_places'] = $entry->foreign_currency_decimal_places; - $array['foreign_amount'] = Steam::bcround((string) $entry->foreign_amount, $entry->foreign_currency_decimal_places); + $array['foreign_amount'] = Steam::bcround((string) $entry->foreign_amount, $entry->foreign_currency_decimal_places); } // convert to primary, but is already primary. if ($this->convertToPrimary && (int) $entry->transaction_currency_id === $this->primaryCurrency->id) { @@ -342,7 +343,7 @@ class SubscriptionEnrichment implements EnrichmentInterface if ($this->convertToPrimary && null !== $entry->foreign_currency_id && (int) $entry->foreign_currency_id !== $this->primaryCurrency->id) { // TODO this is very database intensive. /** @var TransactionCurrency $foreignCurrency */ - $foreignCurrency = Amount::getTransactionCurrencyById($entry->foreign_currency_id); + $foreignCurrency = Amount::getTransactionCurrencyById($entry->foreign_currency_id); $array['pc_foreign_amount'] = $converter->convert($foreignCurrency, $this->primaryCurrency, $entry->date, (string) $entry->amount); } $result[] = $array; @@ -361,9 +362,9 @@ class SubscriptionEnrichment implements EnrichmentInterface /** @var Bill $subscription */ foreach ($this->collection as $subscription) { - $id = (int) $subscription->id; - $lastPaidDate = $this->getLastPaidDate($this->paidDates[$id] ?? []); - $payDates = $this->calculator->getPayDates( + $id = (int) $subscription->id; + $lastPaidDate = $this->getLastPaidDate($this->paidDates[$id] ?? []); + $payDates = $this->calculator->getPayDates( $this->start, $this->end, $subscription->date, @@ -371,9 +372,9 @@ class SubscriptionEnrichment implements EnrichmentInterface $subscription->skip, $lastPaidDate ); - $payDatesFormatted = []; + $payDatesFormatted = []; foreach ($payDates as $string) { - $date = Carbon::createFromFormat('!Y-m-d', $string, config('app.timezone')); + $date = Carbon::createFromFormat('!Y-m-d', $string, config('app.timezone')); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } @@ -401,7 +402,7 @@ class SubscriptionEnrichment implements EnrichmentInterface }, $entries); } - private function getLastPaidDate(array $paidData): null|Carbon + private function getLastPaidDate(array $paidData): ?Carbon { // Log::debug('getLastPaidDate()'); $return = null; @@ -425,7 +426,7 @@ class SubscriptionEnrichment implements EnrichmentInterface return $return; } - private function getNextExpectedMatch(array $payDates): null|Carbon + private function getNextExpectedMatch(array $payDates): ?Carbon { // next expected match $nem = null; @@ -450,7 +451,7 @@ class SubscriptionEnrichment implements EnrichmentInterface return $nem; } - private function getNextExpectedMatchDiff(null|Carbon $nem, array $payDates): string + private function getNextExpectedMatchDiff(?Carbon $nem, array $payDates): string { if (!$nem instanceof Carbon) { return trans('firefly.not_expected_period'); diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php index 9f54fd6dfc..54ed349c65 100644 --- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php +++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php @@ -48,16 +48,16 @@ class TransactionGroupEnrichment implements EnrichmentInterface private array $attachmentCount = []; private Collection $collection; private readonly array $dateFields; - private array $journalIds = []; - private array $locations = []; - private array $metaData = []; - private array $notes = []; + private array $journalIds = []; + private array $locations = []; + private array $metaData = []; + private array $notes = []; private readonly TransactionCurrency $primaryCurrency; - private array $tags = []; // @phpstan-ignore-line + private array $tags = []; // @phpstan-ignore-line public function __construct() { - $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; + $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $this->primaryCurrency = Amount::getPrimaryCurrency(); } @@ -94,22 +94,18 @@ class TransactionGroupEnrichment implements EnrichmentInterface throw new FireflyException('Cannot enrich single model.'); } - public function setUser(User $user): void - { - } + public function setUser(User $user): void {} - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} private function appendCollectedData(): void { - $notes = $this->notes; - $tags = $this->tags; - $metaData = $this->metaData; - $locations = $this->locations; - $attachmentCount = $this->attachmentCount; - $primaryCurrency = $this->primaryCurrency; + $notes = $this->notes; + $tags = $this->tags; + $metaData = $this->metaData; + $locations = $this->locations; + $attachmentCount = $this->attachmentCount; + $primaryCurrency = $this->primaryCurrency; $this->collection = $this->collection->map(function (array $item) use ( $primaryCurrency, @@ -120,19 +116,19 @@ class TransactionGroupEnrichment implements EnrichmentInterface $attachmentCount ): array { foreach ($item['transactions'] as $index => $transaction) { - $journalId = (int) $transaction['transaction_journal_id']; + $journalId = (int) $transaction['transaction_journal_id']; // attach notes if they exist: - $item['transactions'][$index]['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] : []; + $item['transactions'][$index]['tags'] = array_key_exists($journalId, $tags) ? $tags[$journalId] : []; // attachment count $item['transactions'][$index]['attachment_count'] = array_key_exists($journalId, $attachmentCount) ? $attachmentCount[$journalId] : 0; // default location data - $item['transactions'][$index]['location'] = ['latitude' => null, 'longitude' => null, 'zoom_level' => null]; + $item['transactions'][$index]['location'] = ['latitude' => null, 'longitude' => null, 'zoom_level' => null]; // primary currency $item['transactions'][$index]['primary_currency'] = [ @@ -140,12 +136,12 @@ class TransactionGroupEnrichment implements EnrichmentInterface 'code' => $primaryCurrency->code, 'name' => $primaryCurrency->name, 'symbol' => $primaryCurrency->symbol, - 'decimal_places' => $primaryCurrency->decimal_places + 'decimal_places' => $primaryCurrency->decimal_places, ]; // append meta data - $item['transactions'][$index]['meta'] = []; - $item['transactions'][$index]['meta_date'] = []; + $item['transactions'][$index]['meta'] = []; + $item['transactions'][$index]['meta_date'] = []; if (array_key_exists($journalId, $metaData)) { // loop al meta data: foreach ($metaData[$journalId] as $name => $value) { @@ -177,7 +173,8 @@ class TransactionGroupEnrichment implements EnrichmentInterface ->where('attachable_type', TransactionJournal::class) ->groupBy('attachable_id') ->get(['attachable_id', DB::raw('COUNT(id) as nr_of_attachments')]) - ->toArray(); + ->toArray() + ; foreach ($attachments as $row) { $this->attachmentCount[(int) $row['attachable_id']] = (int) $row['nr_of_attachments']; } @@ -200,12 +197,13 @@ class TransactionGroupEnrichment implements EnrichmentInterface ->whereIn('locatable_id', $this->journalIds) ->where('locatable_type', TransactionJournal::class) ->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level']) - ->toArray(); + ->toArray() + ; foreach ($locations as $location) { $this->locations[(int) $location['locatable_id']] = [ 'latitude' => (float) $location['latitude'], 'longitude' => (float) $location['longitude'], - 'zoom_level' => (int) $location['zoom_level'] + 'zoom_level' => (int) $location['zoom_level'], ]; } Log::debug(sprintf('Enrich with %d locations(s)', count($this->locations))); @@ -215,8 +213,8 @@ class TransactionGroupEnrichment implements EnrichmentInterface { $set = TransactionJournalMeta::whereIn('transaction_journal_id', $this->journalIds)->get(['transaction_journal_id', 'name', 'data'])->toArray(); foreach ($set as $entry) { - $name = $entry['name']; - $data = (string) $entry['data']; + $name = $entry['name']; + $data = (string) $entry['data']; if ('' === $data) { continue; } @@ -239,7 +237,8 @@ class TransactionGroupEnrichment implements EnrichmentInterface ->where('notes.text', '!=', '') ->where('noteable_type', TransactionJournal::class) ->get(['notes.noteable_id', 'notes.text']) - ->toArray(); + ->toArray() + ; foreach ($notes as $note) { $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } @@ -251,9 +250,10 @@ class TransactionGroupEnrichment implements EnrichmentInterface $set = Tag::leftJoin('tag_transaction_journal', 'tags.id', '=', 'tag_transaction_journal.tag_id') ->whereIn('tag_transaction_journal.transaction_journal_id', $this->journalIds) ->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag']) - ->toArray(); + ->toArray() + ; foreach ($set as $item) { - $journalId = $item['transaction_journal_id']; + $journalId = $item['transaction_journal_id']; $this->tags[$journalId] ??= []; $this->tags[$journalId][] = $item['tag']; } diff --git a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php index 0eaa3c61cd..c477b23813 100644 --- a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php +++ b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php @@ -42,8 +42,8 @@ use stdClass; class WebhookEnrichment implements EnrichmentInterface { private Collection $collection; - private array $deliveries = []; // @phpstan-ignore-line - private array $ids = []; // @phpstan-ignore-line + private array $deliveries = []; // @phpstan-ignore-line + private array $ids = []; // @phpstan-ignore-line private array $responses = []; private array $triggers = []; private array $webhookDeliveries = []; @@ -72,21 +72,17 @@ class WebhookEnrichment implements EnrichmentInterface return $collection->first(); } - public function setUser(User $user): void - { - } + public function setUser(User $user): void {} - public function setUserGroup(UserGroup $userGroup): void - { - } + public function setUserGroup(UserGroup $userGroup): void {} private function appendCollectedInfo(): void { $this->collection = $this->collection->map(function (Webhook $item): Webhook { - $meta = [ + $meta = [ 'deliveries' => $this->webhookDeliveries[$item->id] ?? [], 'responses' => $this->webhookResponses[$item->id] ?? [], - 'triggers' => $this->webhookTriggers[$item->id] ?? [] + 'triggers' => $this->webhookTriggers[$item->id] ?? [], ]; $item->meta = $meta; @@ -131,8 +127,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $deliveryId = $item->webhook_delivery_id; + $id = $item->webhook_id; + $deliveryId = $item->webhook_delivery_id; $this->webhookDeliveries[$id][] = WebhookDeliveryEnum::from($this->deliveries[$deliveryId])->name; } @@ -140,8 +136,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $responseId = $item->webhook_response_id; + $id = $item->webhook_id; + $responseId = $item->webhook_response_id; $this->webhookResponses[$id][] = WebhookResponseEnum::from($this->responses[$responseId])->name; } @@ -149,8 +145,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $triggerId = $item->webhook_trigger_id; + $id = $item->webhook_id; + $triggerId = $item->webhook_trigger_id; $this->webhookTriggers[$id][] = WebhookTriggerEnum::from($this->triggers[$triggerId])->name; } } diff --git a/app/Support/Models/AccountBalanceCalculator.php b/app/Support/Models/AccountBalanceCalculator.php index f689e98a8f..3ef7b82311 100644 --- a/app/Support/Models/AccountBalanceCalculator.php +++ b/app/Support/Models/AccountBalanceCalculator.php @@ -70,17 +70,17 @@ class AccountBalanceCalculator return; } Log::debug(__METHOD__); - $object = new self(); + $object = new self(); - $set = []; + $set = []; foreach ($transactionJournal->transactions as $transaction) { $set[$transaction->account_id] = $transaction->account; } $accounts = new Collection()->push(...$set); // find meta value: - $date = $transactionJournal->date; - $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first(); + $date = $transactionJournal->date; + $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first(); Log::debug(sprintf('Date used is "%s"', $date->toW3cString())); if (null !== $meta) { $date = Carbon::parse($meta->data); @@ -90,14 +90,14 @@ class AccountBalanceCalculator $object->optimizedCalculation($accounts, $date); } - private function getLatestBalance(int $accountId, int $currencyId, null|Carbon $notBefore): string + private function getLatestBalance(int $accountId, int $currencyId, ?Carbon $notBefore): string { if (!$notBefore instanceof Carbon) { Log::debug(sprintf('Start balance for account #%d and currency #%d is 0.', $accountId, $currencyId)); return '0'; } - $query = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + $query = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->whereNull('transactions.deleted_at') ->where('transactions.transaction_currency_id', $currencyId) ->whereNull('transaction_journals.deleted_at') @@ -107,17 +107,18 @@ class AccountBalanceCalculator ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') ->orderBy('transactions.amount', 'DESC') - ->where('transactions.account_id', $accountId); + ->where('transactions.account_id', $accountId) + ; $query->where('transaction_journals.date', '<', $notBefore); - $first = $query->first([ + $first = $query->first([ 'transactions.id', 'transactions.balance_dirty', 'transactions.transaction_currency_id', 'transaction_journals.date', 'transactions.account_id', 'transactions.amount', - 'transactions.balance_after' + 'transactions.balance_after', ]); if (null === $first) { @@ -137,7 +138,7 @@ class AccountBalanceCalculator return $balance; } - private function optimizedCalculation(Collection $accounts, null|Carbon $notBefore = null): void + private function optimizedCalculation(Collection $accounts, ?Carbon $notBefore = null): void { if ($notBefore instanceof Carbon) { $notBefore->startOfDay(); @@ -158,7 +159,8 @@ class AccountBalanceCalculator ->orderBy('transaction_journals.order', 'desc') ->orderBy('transaction_journals.id', 'asc') ->orderBy('transaction_journals.description', 'asc') - ->orderBy('transactions.amount', 'asc'); + ->orderBy('transactions.amount', 'asc') + ; if ($accounts->count() > 0) { $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()); } @@ -166,13 +168,13 @@ class AccountBalanceCalculator $query->where('transaction_journals.date', '>=', $notBefore); } - $set = $query->get([ + $set = $query->get([ 'transactions.id', 'transactions.balance_dirty', 'transactions.transaction_currency_id', 'transaction_journals.date', 'transactions.account_id', - 'transactions.amount' + 'transactions.amount', ]); Log::debug(sprintf('Found %d transaction(s)', $set->count())); @@ -183,23 +185,23 @@ class AccountBalanceCalculator foreach ($set as $entry) { // Log::debug(sprintf('Processing transaction #%d with currency #%d and amount %s', $entry->id, $entry->transaction_currency_id, Steam::bcround($entry->amount, 2))); // start with empty array: - $balances[$entry->account_id] ??= []; + $balances[$entry->account_id] ??= []; $balances[$entry->account_id][$entry->transaction_currency_id] ??= [ $this->getLatestBalance($entry->account_id, $entry->transaction_currency_id, $notBefore), - null + null, ]; // before and after are easy: - $before = $balances[$entry->account_id][$entry->transaction_currency_id][0]; - $after = bcadd($before, (string) $entry->amount); + $before = $balances[$entry->account_id][$entry->transaction_currency_id][0]; + $after = bcadd($before, (string) $entry->amount); // Log::debug(sprintf('Before:%s, after:%s', Steam::bcround($before, 2), Steam::bcround($after, 2))); if (true === $entry->balance_dirty || $accounts->count() > 0) { // update the transaction: $entry->balance_before = $before; - $entry->balance_after = $after; - $entry->balance_dirty = false; + $entry->balance_after = $after; + $entry->balance_dirty = false; $entry->saveQuietly(); // do not observe this change, or we get stuck in a loop. ++$count; } @@ -243,17 +245,18 @@ class AccountBalanceCalculator } /** @var AccountBalance $object */ - $object = $account + $object = $account ->accountBalances() ->firstOrCreate([ 'title' => 'running_balance', 'balance' => '0', 'transaction_currency_id' => $currencyId, 'date' => $balance[1], - 'date_tz' => $balance[1]?->format('e') - ]); + 'date_tz' => $balance[1]?->format('e'), + ]) + ; $object->balance = $balance[0]; - $object->date = $balance[1]; + $object->date = $balance[1]; $object->date_tz = $balance[1]?->format('e'); $object->saveQuietly(); } diff --git a/app/Support/Models/BillDateCalculator.php b/app/Support/Models/BillDateCalculator.php index cd904de57e..817ecf86be 100644 --- a/app/Support/Models/BillDateCalculator.php +++ b/app/Support/Models/BillDateCalculator.php @@ -40,7 +40,7 @@ class BillDateCalculator * * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ - public function getPayDates(Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, null|Carbon $lastPaid): array + public function getPayDates(Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, ?Carbon $lastPaid): array { $this->diffInMonths = 0; $earliest->startOfDay(); @@ -56,15 +56,15 @@ class BillDateCalculator $lastPaid?->format('Y-m-d') )); - $daysUntilEOM = Navigation::daysUntilEndOfMonth($billStart); + $daysUntilEOM = Navigation::daysUntilEndOfMonth($billStart); Log::debug(sprintf('For bill start, days until end of month is %d', $daysUntilEOM)); - $set = new Collection(); - $currentStart = clone $earliest; + $set = new Collection(); + $currentStart = clone $earliest; // 2023-06-23 subDay to fix 7655 $currentStart->subDay(); - $loop = 0; + $loop = 0; Log::debug('Start of loop'); while ($currentStart <= $latest) { @@ -118,7 +118,7 @@ class BillDateCalculator // for the next loop, go to end of period, THEN add day. Log::debug('Add one day to nextExpectedMatch/currentStart.'); $nextExpectedMatch->addDay(); - $currentStart = clone $nextExpectedMatch; + $currentStart = clone $nextExpectedMatch; ++$loop; if ($loop > 31) { @@ -128,8 +128,8 @@ class BillDateCalculator } } Log::debug('end of loop'); - $simple = $set->map( // @phpstan-ignore-line - static fn(Carbon $date) => $date->format('Y-m-d') + $simple = $set->map( // @phpstan-ignore-line + static fn (Carbon $date) => $date->format('Y-m-d') ); Log::debug(sprintf('Found %d pay dates', $set->count()), $simple->toArray()); @@ -151,13 +151,13 @@ class BillDateCalculator return $billStartDate; } - $steps = Navigation::diffInPeriods($period, $skip, $earliest, $billStartDate); + $steps = Navigation::diffInPeriods($period, $skip, $earliest, $billStartDate); if ($steps === $this->diffInMonths) { Log::debug(sprintf('Steps is %d, which is the same as diffInMonths (%d), so we add another 1.', $steps, $this->diffInMonths)); ++$steps; } $this->diffInMonths = $steps; - $result = clone $billStartDate; + $result = clone $billStartDate; if ($steps > 0) { --$steps; Log::debug(sprintf('Steps is %d, because addPeriod already adds 1.', $steps)); diff --git a/app/Support/Models/ReturnsIntegerIdTrait.php b/app/Support/Models/ReturnsIntegerIdTrait.php index 5763f9a6fd..b8a71ccd89 100644 --- a/app/Support/Models/ReturnsIntegerIdTrait.php +++ b/app/Support/Models/ReturnsIntegerIdTrait.php @@ -38,6 +38,6 @@ trait ReturnsIntegerIdTrait */ protected function id(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Support/Models/ReturnsIntegerUserIdTrait.php b/app/Support/Models/ReturnsIntegerUserIdTrait.php index c831ea2da3..38cc1f3d90 100644 --- a/app/Support/Models/ReturnsIntegerUserIdTrait.php +++ b/app/Support/Models/ReturnsIntegerUserIdTrait.php @@ -36,11 +36,11 @@ trait ReturnsIntegerUserIdTrait */ protected function userGroupId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } protected function userId(): Attribute { - return Attribute::make(get: static fn($value): int => (int) $value); + return Attribute::make(get: static fn ($value): int => (int) $value); } } diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 118adaa6a4..291418b388 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -41,7 +41,7 @@ class Navigation { private readonly Calculator $calculator; - public function __construct(null|Calculator $calculator = null) + public function __construct(?Calculator $calculator = null) { $this->calculator = $calculator instanceof Calculator ? $calculator : new Calculator(); } @@ -68,13 +68,13 @@ class Navigation '1Y' => Periodicity::Yearly, 'custom' => Periodicity::Monthly, // custom? just add one month. // last X periods? Jump the relevant month / quarter / year - 'last7' => Periodicity::Weekly, - 'last30' => Periodicity::Monthly, - 'last90' => Periodicity::Quarterly, - 'last365' => Periodicity::Yearly, - 'MTD' => Periodicity::Monthly, - 'QTD' => Periodicity::Quarterly, - 'YTD' => Periodicity::Yearly + 'last7' => Periodicity::Weekly, + 'last30' => Periodicity::Monthly, + 'last90' => Periodicity::Quarterly, + 'last365' => Periodicity::Yearly, + 'MTD' => Periodicity::Monthly, + 'QTD' => Periodicity::Quarterly, + 'YTD' => Periodicity::Yearly, ]; if (!array_key_exists($repeatFreq, $functionMap)) { @@ -91,7 +91,7 @@ class Navigation if ($end < $start) { [$start, $end] = [$end, $start]; } - $periods = []; + $periods = []; // first, 13 periods of [range] $loopCount = 0; $loopDate = clone $end; @@ -141,20 +141,20 @@ class Navigation public function diffInPeriods(string $period, int $skip, Carbon $beginning, Carbon $end): int { Log::debug(sprintf('diffInPeriods: %s (skip: %d), between %s and %s.', $period, $skip, $beginning->format('Y-m-d'), $end->format('Y-m-d'))); - $map = [ + $map = [ 'daily' => 'diffInDays', 'weekly' => 'diffInWeeks', 'monthly' => 'diffInMonths', 'quarterly' => 'diffInMonths', 'half-year' => 'diffInMonths', - 'yearly' => 'diffInYears' + 'yearly' => 'diffInYears', ]; if (!array_key_exists($period, $map)) { Log::warning(sprintf('No diffInPeriods for period "%s"', $period)); return 1; } - $func = $map[$period]; + $func = $map[$period]; // first do the diff $floatDiff = $beginning->{$func}($end, true); // @phpstan-ignore-line @@ -169,7 +169,7 @@ class Navigation } // then do ceil() - $diff = ceil($floatDiff); + $diff = ceil($floatDiff); Log::debug(sprintf('Diff is %f periods (%d rounded up)', $floatDiff, $diff)); @@ -184,7 +184,7 @@ class Navigation public function endOfPeriod(Carbon $end, string $repeatFreq): Carbon { - $currentEnd = clone $end; + $currentEnd = clone $end; // Log::debug(sprintf('Now in endOfPeriod("%s", "%s").', $currentEnd->toIso8601String(), $repeatFreq)); if ('MTD' === $repeatFreq && $end->isFuture()) { // fall back to a monthly schedule if the requested period is MTD. @@ -219,7 +219,7 @@ class Navigation 'half_year' => 'addMonths', 'year' => 'addYear', 'yearly' => 'addYear', - '1Y' => 'addYear' + '1Y' => 'addYear', ]; $modifierMap = ['half-year' => 6, 'half_year' => 6, '6M' => 6]; $subDay = ['week', 'weekly', '1W', 'month', 'monthly', '1M', '3M', 'quarter', 'quarterly', '6M', 'half-year', 'half_year', '1Y', 'year', 'yearly']; @@ -233,7 +233,7 @@ class Navigation Log::debug('Session data available.'); /** @var Carbon $tStart */ - $tStart = session('start', today(config('app.timezone'))->startOfMonth()); + $tStart = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $tEnd */ $tEnd = session('end', today(config('app.timezone'))->endOfMonth()); @@ -284,15 +284,15 @@ class Navigation return $end->endOfMonth(); } - $result = match ($repeatFreq) { - 'last7' => $currentEnd->addDays(7)->startOfDay(), - 'last30' => $currentEnd->addDays(30)->startOfDay(), - 'last90' => $currentEnd->addDays(90)->startOfDay(), + $result = match ($repeatFreq) { + 'last7' => $currentEnd->addDays(7)->startOfDay(), + 'last30' => $currentEnd->addDays(30)->startOfDay(), + 'last90' => $currentEnd->addDays(90)->startOfDay(), 'last365' => $currentEnd->addDays(365)->startOfDay(), - 'MTD' => $currentEnd->startOfMonth()->startOfDay(), - 'QTD' => $currentEnd->firstOfQuarter()->startOfDay(), - 'YTD' => $currentEnd->startOfYear()->startOfDay(), - default => null + 'MTD' => $currentEnd->startOfMonth()->startOfDay(), + 'QTD' => $currentEnd->firstOfQuarter()->startOfDay(), + 'YTD' => $currentEnd->startOfYear()->startOfDay(), + default => null }; if (null !== $result) { // add sanity check. @@ -342,7 +342,7 @@ class Navigation return $end; } - $function = $functionMap[$repeatFreq]; + $function = $functionMap[$repeatFreq]; if (array_key_exists($repeatFreq, $modifierMap)) { $currentEnd->{$function}($modifierMap[$repeatFreq])->milli(0); // @phpstan-ignore-line @@ -383,7 +383,7 @@ class Navigation return $currentEnd; } - public function endOfX(Carbon $theCurrentEnd, string $repeatFreq, null|Carbon $maxDate): Carbon + public function endOfX(Carbon $theCurrentEnd, string $repeatFreq, ?Carbon $maxDate): Carbon { $functionMap = [ '1D' => 'endOfDay', @@ -399,10 +399,10 @@ class Navigation 'quarterly' => 'lastOfQuarter', '1Y' => 'endOfYear', 'year' => 'endOfYear', - 'yearly' => 'endOfYear' + 'yearly' => 'endOfYear', ]; - $currentEnd = clone $theCurrentEnd; + $currentEnd = clone $theCurrentEnd; if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; @@ -445,7 +445,7 @@ class Navigation */ public function listOfPeriods(Carbon $start, Carbon $end): array { - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); // define period to increment $increment = 'addDay'; $format = $this->preferredCarbonFormat($start, $end); @@ -462,11 +462,11 @@ class Navigation $increment = 'addYear'; $displayFormat = (string) trans('config.year_js'); } - $begin = clone $start; - $entries = []; + $begin = clone $start; + $entries = []; while ($begin < $end) { - $formatted = $begin->format($format); - $displayed = $begin->isoFormat($displayFormat); + $formatted = $begin->format($format); + $displayed = $begin->isoFormat($displayFormat); $entries[$formatted] = $displayed; $begin->{$increment}(); // @phpstan-ignore-line } @@ -487,7 +487,7 @@ class Navigation Log::debug('Any error occurred to calculate the next date.', [ 'date' => $epoch, 'periodicity' => $periodicity->name, - 'skipInterval' => $skipInterval + 'skipInterval' => $skipInterval, ]); return $epoch; @@ -516,7 +516,7 @@ class Navigation 'last30' => (string) trans('config.month_js'), 'last90' => (string) trans('config.month_js'), 'last365' => (string) trans('config.year_js'), - 'QTD' => (string) trans('config.month_js') + 'QTD' => (string) trans('config.month_js'), ]; if (array_key_exists($repeatFrequency, $formatMap)) { @@ -564,10 +564,10 @@ class Navigation return match ($period) { default => 'Y-m-d', // '1D' => 'Y-m-d', - '1W' => '\WW,Y', - '1M' => 'Y-m', + '1W' => '\WW,Y', + '1M' => 'Y-m', '3M', '6M' => '\QQ,Y', - '1Y' => 'Y' + '1Y' => 'Y' }; } @@ -647,9 +647,9 @@ class Navigation public function startOfPeriod(Carbon $theDate, string $repeatFreq): Carbon { - $date = clone $theDate; + $date = clone $theDate; // Log::debug(sprintf('Now in startOfPeriod("%s", "%s")', $date->toIso8601String(), $repeatFreq)); - $functionMap = [ + $functionMap = [ '1D' => 'startOfDay', 'daily' => 'startOfDay', '1W' => 'startOfWeek', @@ -664,7 +664,7 @@ class Navigation 'year' => 'startOfYear', 'yearly' => 'startOfYear', '1Y' => 'startOfYear', - 'MTD' => 'startOfMonth' + 'MTD' => 'startOfMonth', ]; $parameterMap = ['startOfWeek' => [Carbon::MONDAY]]; @@ -694,15 +694,15 @@ class Navigation return $date; } - $result = match ($repeatFreq) { - 'last7' => $date->subDays(7)->startOfDay(), - 'last30' => $date->subDays(30)->startOfDay(), - 'last90' => $date->subDays(90)->startOfDay(), + $result = match ($repeatFreq) { + 'last7' => $date->subDays(7)->startOfDay(), + 'last30' => $date->subDays(30)->startOfDay(), + 'last90' => $date->subDays(90)->startOfDay(), 'last365' => $date->subDays(365)->startOfDay(), - 'MTD' => $date->startOfMonth()->startOfDay(), - 'QTD' => $date->firstOfQuarter()->startOfDay(), - 'YTD' => $date->startOfYear()->startOfDay(), - default => null + 'MTD' => $date->startOfMonth()->startOfDay(), + 'QTD' => $date->firstOfQuarter()->startOfDay(), + 'YTD' => $date->startOfYear()->startOfDay(), + default => null }; if (null !== $result) { // Log::debug(sprintf('Result is "%s"', $date->toIso8601String())); @@ -723,10 +723,10 @@ class Navigation /** * @throws FireflyException */ - public function subtractPeriod(Carbon $theDate, string $repeatFreq, null|int $subtract = null): Carbon + public function subtractPeriod(Carbon $theDate, string $repeatFreq, ?int $subtract = null): Carbon { $subtract ??= 1; - $date = clone $theDate; + $date = clone $theDate; // 1D 1W 1M 3M 6M 1Y $functionMap = [ '1D' => 'subDays', @@ -739,7 +739,7 @@ class Navigation 'monthly' => 'subMonths', 'year' => 'subYears', '1Y' => 'subYears', - 'yearly' => 'subYears' + 'yearly' => 'subYears', ]; $modifierMap = ['quarter' => 3, '3M' => 3, 'quarterly' => 3, 'half-year' => 6, '6M' => 6]; if (array_key_exists($repeatFreq, $functionMap)) { @@ -759,7 +759,7 @@ class Navigation // this is then subtracted from $theDate (* $subtract). if ('custom' === $repeatFreq) { /** @var Carbon $tStart */ - $tStart = session('start', today(config('app.timezone'))->startOfMonth()); + $tStart = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $tEnd */ $tEnd = session('end', today(config('app.timezone'))->endOfMonth()); @@ -847,7 +847,7 @@ class Navigation return $fiscalHelper->endOfFiscalYear($end); } - $list = ['last7', 'last30', 'last90', 'last365', 'YTD', 'QTD', 'MTD']; + $list = ['last7', 'last30', 'last90', 'last365', 'YTD', 'QTD', 'MTD']; if (in_array($range, $list, true)) { $end = today(config('app.timezone')); $end->endOfDay(); @@ -870,7 +870,7 @@ class Navigation '1W' => 'startOfWeek', '1M' => 'startOfMonth', '3M' => 'firstOfQuarter', - 'custom' => 'startOfMonth' // this only happens in test situations. + 'custom' => 'startOfMonth', // this only happens in test situations. ]; if (array_key_exists($range, $functionMap)) { $function = $functionMap[$range]; diff --git a/app/Support/Notifications/UrlValidator.php b/app/Support/Notifications/UrlValidator.php index 3daaa434cc..c7b82a32d4 100644 --- a/app/Support/Notifications/UrlValidator.php +++ b/app/Support/Notifications/UrlValidator.php @@ -31,10 +31,9 @@ class UrlValidator { public static function isValidWebhookURL(string $url): bool { - return ( + return str_starts_with($url, 'https://hooks.slack.com/services/') || str_starts_with($url, 'https://discord.com/api/webhooks/') - || str_ends_with($url, '/slack') - ); + || str_ends_with($url, '/slack'); } } diff --git a/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php b/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php index e2004d9482..9bca8324ca 100644 --- a/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php +++ b/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php @@ -43,10 +43,10 @@ trait RecalculatesAvailableBudgetsTrait { private function calculateAmount(AvailableBudget $availableBudget): void { - $repository = app(BudgetLimitRepositoryInterface::class); + $repository = app(BudgetLimitRepositoryInterface::class); $repository->setUser($availableBudget->user); - $newAmount = '0'; - $abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY()); + $newAmount = '0'; + $abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY()); Log::debug(sprintf( 'Now at AB #%d, ("%s" to "%s")', $availableBudget->id, @@ -54,7 +54,7 @@ trait RecalculatesAvailableBudgetsTrait $availableBudget->end_date->format('Y-m-d') )); // have to recalculate everything just in case. - $set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date); + $set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date); Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count())); /** @var BudgetLimit $budgetLimit */ @@ -122,7 +122,7 @@ trait RecalculatesAvailableBudgetsTrait Log::debug(sprintf('Now in updateAvailableBudget(limit #%d)', $budgetLimit->id)); /** @var null|Budget $budget */ - $budget = Budget::find($budgetLimit->budget_id); + $budget = Budget::find($budgetLimit->budget_id); if (null === $budget) { Log::warning('Budget is null, probably deleted, find deleted version.'); @@ -137,7 +137,7 @@ trait RecalculatesAvailableBudgetsTrait } /** @var null|User $user */ - $user = $budget->user; + $user = $budget->user; // sanity check. It happens when the budget has been deleted so the original user is unknown. if (null === $user) { @@ -160,15 +160,15 @@ trait RecalculatesAvailableBudgetsTrait if (null === $viewRange || is_array($viewRange)) { $viewRange = '1M'; } - $viewRange = (string) $viewRange; + $viewRange = (string) $viewRange; - $start = Navigation::startOfPeriod($budgetLimit->start_date, $viewRange); - $end = Navigation::startOfPeriod($budgetLimit->end_date, $viewRange); - $end = Navigation::endOfPeriod($end, $viewRange); + $start = Navigation::startOfPeriod($budgetLimit->start_date, $viewRange); + $end = Navigation::startOfPeriod($budgetLimit->end_date, $viewRange); + $end = Navigation::endOfPeriod($end, $viewRange); if ($end < $start) { - [$start, $end] = [$end, $start]; + [$start, $end] = [$end, $start]; $budgetLimit->start_date = $start; - $budgetLimit->end_date = $end; + $budgetLimit->end_date = $end; $budgetLimit->saveQuietly(); } @@ -177,9 +177,9 @@ trait RecalculatesAvailableBudgetsTrait Log::debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d'))); // from the start until the end of the budget limit, need to loop! - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $currentEnd = Navigation::endOfPeriod($current, $viewRange); + $currentEnd = Navigation::endOfPeriod($current, $viewRange); // create or find AB for this particular period, and set the amount accordingly. /** @var null|AvailableBudget $availableBudget */ @@ -188,7 +188,8 @@ trait RecalculatesAvailableBudgetsTrait ->where('start_date', $current->format('Y-m-d')) ->where('end_date', $currentEnd->format('Y-m-d')) ->where('transaction_currency_id', $budgetLimit->transaction_currency_id) - ->first(); + ->first() + ; if (null !== $availableBudget) { Log::debug('Found 1 AB, will update.'); @@ -216,7 +217,7 @@ trait RecalculatesAvailableBudgetsTrait 'start_date_tz' => $current->format('e'), 'end_date' => $currentEnd, 'end_date_tz' => $currentEnd->format('e'), - 'amount' => $amount + 'amount' => $amount, ]); $availableBudget->save(); Log::debug(sprintf('ID of new AB is #%d', $availableBudget->id)); @@ -225,7 +226,7 @@ trait RecalculatesAvailableBudgetsTrait } // prep for next loop - $current = Navigation::addPeriod($current, $viewRange); + $current = Navigation::addPeriod($current, $viewRange); } } } diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index d3a39e2658..f4dbc7f7d2 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -49,7 +49,7 @@ class ParseDateString 'start of this quarter', 'end of this quarter', 'start of this year', - 'end of this year' + 'end of this year', ]; public function isDateRange(string $date): bool @@ -77,15 +77,15 @@ class ParseDateString public function parseDate(string $date): Carbon { Log::debug(sprintf('parseDate("%s")', $date)); - $date = strtolower($date); + $date = strtolower($date); // parse keywords: if (in_array($date, $this->keywords, true)) { return $this->parseKeyword($date); } // if regex for YYYY-MM-DD: - $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; - $result = preg_match($pattern, $date); + $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; + $result = preg_match($pattern, $date); if (0 !== $result) { return $this->parseDefaultDate($date); } @@ -285,17 +285,17 @@ class ParseDateString $today = today(config('app.timezone'))->startOfDay(); return match ($keyword) { - default => $today, - 'yesterday' => $today->subDay(), - 'tomorrow' => $today->addDay(), - 'start of this week' => $today->startOfWeek(CarbonInterface::MONDAY), - 'end of this week' => $today->endOfWeek(CarbonInterface::SUNDAY), - 'start of this month' => $today->startOfMonth(), - 'end of this month' => $today->endOfMonth(), + default => $today, + 'yesterday' => $today->subDay(), + 'tomorrow' => $today->addDay(), + 'start of this week' => $today->startOfWeek(CarbonInterface::MONDAY), + 'end of this week' => $today->endOfWeek(CarbonInterface::SUNDAY), + 'start of this month' => $today->startOfMonth(), + 'end of this month' => $today->endOfMonth(), 'start of this quarter' => $today->startOfQuarter(), - 'end of this quarter' => $today->endOfQuarter(), - 'start of this year' => $today->startOfYear(), - 'end of this year' => $today->endOfYear() + 'end of this quarter' => $today->endOfQuarter(), + 'start of this year' => $today->startOfYear(), + 'end of this year' => $today->endOfYear() }; } @@ -328,16 +328,16 @@ class ParseDateString $today = today(config('app.timezone'))->startOfDay(); $functions = [ ['d' => 'subDays', 'w' => 'subWeeks', 'm' => 'subMonths', 'q' => 'subQuarters', 'y' => 'subYears'], - ['d' => 'addDays', 'w' => 'addWeeks', 'm' => 'addMonths', 'q' => 'addQuarters', 'y' => 'addYears'] + ['d' => 'addDays', 'w' => 'addWeeks', 'm' => 'addMonths', 'q' => 'addQuarters', 'y' => 'addYears'], ]; foreach ($parts as $part) { Log::debug(sprintf('Now parsing part "%s"', $part)); - $part = trim($part); + $part = trim($part); // verify if correct - $pattern = '/[+-]\d+[wqmdy]/'; - $result = preg_match($pattern, $part); + $pattern = '/[+-]\d+[wqmdy]/'; + $result = preg_match($pattern, $part); if (0 === $result) { Log::error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part)); @@ -351,7 +351,7 @@ class ParseDateString continue; } - $func = $functions[$direction][$period]; + $func = $functions[$direction][$period]; Log::debug(sprintf('Will now do %s(%d) on %s', $func, $number, $today->format('Y-m-d'))); $today->{$func}($number); // @phpstan-ignore-line Log::debug(sprintf('Resulting date is %s', $today->format('Y-m-d'))); diff --git a/app/Support/Preferences.php b/app/Support/Preferences.php index 5816d841aa..267c5e79a2 100644 --- a/app/Support/Preferences.php +++ b/app/Support/Preferences.php @@ -53,7 +53,8 @@ class Preferences $q->whereNull('user_group_id'); $q->orWhere('user_group_id', $user->user_group_id); }) - ->get(); + ->get() + ; } public function beginsWith(User $user, string $search): Collection @@ -89,12 +90,12 @@ class Preferences Cache::put($key, '', 5); } - public function get(string $name, array|bool|int|string|null $default = null): null|Preference + public function get(string $name, array|bool|int|string|null $default = null): ?Preference { /** @var null|User $user */ $user = auth()->user(); if (null === $user) { - $preference = new Preference(); + $preference = new Preference(); $preference->data = $default; return $preference; @@ -112,7 +113,8 @@ class Preferences $q->orWhere('user_group_id', $user->user_group_id); }) ->whereIn('name', $list) - ->get(['id', 'name', 'data']); + ->get(['id', 'name', 'data']) + ; /** @var Preference $preference */ foreach ($preferences as $preference) { @@ -127,7 +129,7 @@ class Preferences return $result; } - public function getEncrypted(string $name, mixed $default = null): null|Preference + public function getEncrypted(string $name, mixed $default = null): ?Preference { $result = $this->get($name, $default); if (!$result instanceof Preference) { @@ -154,7 +156,7 @@ class Preferences return $result; } - public function getEncryptedForUser(User $user, string $name, array|bool|int|string|null $default = null): null|Preference + public function getEncryptedForUser(User $user, string $name, array|bool|int|string|null $default = null): ?Preference { $result = $this->getForUser($user, $name, $default); if ('' === $result->data) { @@ -178,7 +180,7 @@ class Preferences return $result; } - public function getForUser(User $user, string $name, array|bool|int|string|null $default = null): null|Preference + public function getForUser(User $user, string $name, array|bool|int|string|null $default = null): ?Preference { // Log::debug(sprintf('getForUser(#%d, "%s")', $user->id, $name)); // don't care about user group ID, except for some specific preferences. @@ -189,7 +191,7 @@ class Preferences $query->where('user_group_id', $userGroupId); } - $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); + $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); if (null !== $preference && null === $preference->data) { $preference->delete(); @@ -213,12 +215,12 @@ class Preferences return $this->setForUser($user, $name, $default); } - public function getFresh(string $name, array|bool|int|string|null $default = null): null|Preference + public function getFresh(string $name, array|bool|int|string|null $default = null): ?Preference { /** @var null|User $user */ $user = auth()->user(); if (null === $user) { - $preference = new Preference(); + $preference = new Preference(); $preference->data = $default; return $preference; @@ -229,8 +231,8 @@ class Preferences public function lastActivity(): string { - $instance = PreferencesSingleton::getInstance(); - $pref = $instance->getPreference('last_activity'); + $instance = PreferencesSingleton::getInstance(); + $pref = $instance->getPreference('last_activity'); if (null !== $pref) { // Log::debug(sprintf('Found last activity in singleton: %s', $pref)); return $pref; @@ -244,7 +246,7 @@ class Preferences if (is_array($lastActivity)) { $lastActivity = implode(',', $lastActivity); } - $setting = hash('sha256', (string) $lastActivity); + $setting = hash('sha256', (string) $lastActivity); $instance->setPreference('last_activity', $setting); return $setting; @@ -264,7 +266,7 @@ class Preferences $user = auth()->user(); if (null === $user) { // make new preference, return it: - $pref = new Preference(); + $pref = new Preference(); $pref->name = $name; $pref->data = $value; @@ -289,19 +291,19 @@ class Preferences public function setForUser(User $user, string $name, array|bool|int|string|null $value): Preference { - $fullName = sprintf('preference%s%s', $user->id, $name); - $userGroupId = $this->getUserGroupId($user, $name); - $userGroupId = 0 === (int) $userGroupId ? null : (int) $userGroupId; + $fullName = sprintf('preference%s%s', $user->id, $name); + $userGroupId = $this->getUserGroupId($user, $name); + $userGroupId = 0 === (int) $userGroupId ? null : (int) $userGroupId; Cache::forget($fullName); - $query = Preference::where('user_id', $user->id)->where('name', $name); + $query = Preference::where('user_id', $user->id)->where('name', $name); if (null !== $userGroupId) { Log::debug('Include user group ID in query'); $query->where('user_group_id', $userGroupId); } - $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); + $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); if (null !== $preference && null === $value) { $preference->delete(); @@ -312,10 +314,10 @@ class Preferences return new Preference(); } if (null === $preference) { - $preference = new Preference(); - $preference->user_id = (int) $user->id; + $preference = new Preference(); + $preference->user_id = (int) $user->id; $preference->user_group_id = $userGroupId; - $preference->name = $name; + $preference->name = $name; } $preference->data = $value; $preference->save(); @@ -324,7 +326,7 @@ class Preferences return $preference; } - private function getUserGroupId(User $user, string $preferenceName): null|int + private function getUserGroupId(User $user, string $preferenceName): ?int { $groupId = null; $items = config('firefly.admin_specific_prefs') ?? []; diff --git a/app/Support/Report/Budget/BudgetReportGenerator.php b/app/Support/Report/Budget/BudgetReportGenerator.php index d421efa7f1..9b8aa084af 100644 --- a/app/Support/Report/Budget/BudgetReportGenerator.php +++ b/app/Support/Report/Budget/BudgetReportGenerator.php @@ -59,10 +59,10 @@ class BudgetReportGenerator */ public function __construct() { - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->nbRepository = app(NoBudgetRepositoryInterface::class); + $this->nbRepository = app(NoBudgetRepositoryInterface::class); } /** @@ -70,7 +70,7 @@ class BudgetReportGenerator */ public function accountPerBudget(): void { - $spent = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts, $this->budgets); + $spent = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts, $this->budgets); $this->report = []; /** @var Account $account */ @@ -153,16 +153,16 @@ class BudgetReportGenerator // add no budget info. $this->report['budgets'][0] = ['budget_id' => null, 'budget_name' => null, 'no_budget' => true, 'budget_limits' => []]; - $noBudget = $this->nbRepository->sumExpenses($this->start, $this->end, $this->accounts); + $noBudget = $this->nbRepository->sumExpenses($this->start, $this->end, $this->accounts); foreach ($noBudget as $noBudgetEntry) { // currency information: - $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $this->currency->id); - $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; - $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; - $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; - $nbCurrencyDp = $noBudgetEntry['currency_decimal_places'] ?? $this->currency->decimal_places; + $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $this->currency->id); + $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; + $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; + $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; + $nbCurrencyDp = $noBudgetEntry['currency_decimal_places'] ?? $this->currency->decimal_places; - $this->report['budgets'][0]['budget_limits'][] = [ + $this->report['budgets'][0]['budget_limits'][] = [ 'budget_limit_id' => null, 'start_date' => $this->start, 'end_date' => $this->end, @@ -176,20 +176,20 @@ class BudgetReportGenerator 'currency_code' => $nbCurrencyCode, 'currency_name' => $nbCurrencyName, 'currency_symbol' => $nbCurrencySymbol, - 'currency_decimal_places' => $nbCurrencyDp + 'currency_decimal_places' => $nbCurrencyDp, ]; - $this->report['sums'][$nbCurrencyId]['spent'] = bcadd($this->report['sums'][$nbCurrencyId]['spent'] ?? '0', (string) $noBudgetEntry['sum']); + $this->report['sums'][$nbCurrencyId]['spent'] = bcadd($this->report['sums'][$nbCurrencyId]['spent'] ?? '0', (string) $noBudgetEntry['sum']); // append currency info because it may be missing: - $this->report['sums'][$nbCurrencyId]['currency_id'] = $nbCurrencyId; - $this->report['sums'][$nbCurrencyId]['currency_code'] = $nbCurrencyCode; - $this->report['sums'][$nbCurrencyId]['currency_name'] = $nbCurrencyName; - $this->report['sums'][$nbCurrencyId]['currency_symbol'] = $nbCurrencySymbol; + $this->report['sums'][$nbCurrencyId]['currency_id'] = $nbCurrencyId; + $this->report['sums'][$nbCurrencyId]['currency_code'] = $nbCurrencyCode; + $this->report['sums'][$nbCurrencyId]['currency_name'] = $nbCurrencyName; + $this->report['sums'][$nbCurrencyId]['currency_symbol'] = $nbCurrencySymbol; $this->report['sums'][$nbCurrencyId]['currency_decimal_places'] = $nbCurrencyDp; // append other sums because they might be missing: $this->report['sums'][$nbCurrencyId]['overspent'] ??= '0'; - $this->report['sums'][$nbCurrencyId]['left'] ??= '0'; - $this->report['sums'][$nbCurrencyId]['budgeted'] ??= '0'; + $this->report['sums'][$nbCurrencyId]['left'] ??= '0'; + $this->report['sums'][$nbCurrencyId]['budgeted'] ??= '0'; } } @@ -201,15 +201,15 @@ class BudgetReportGenerator // make percentages based on total amount. foreach ($this->report['budgets'] as $budgetId => $data) { foreach ($data['budget_limits'] as $limitId => $entry) { - $budgetId = (int) $budgetId; - $limitId = (int) $limitId; - $currencyId = (int) $entry['currency_id']; - $spent = $entry['spent']; - $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; - $spentPct = '0'; - $budgeted = $entry['budgeted']; - $totalBudgeted = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; - $budgetedPct = '0'; + $budgetId = (int) $budgetId; + $limitId = (int) $limitId; + $currencyId = (int) $entry['currency_id']; + $spent = $entry['spent']; + $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; + $spentPct = '0'; + $budgeted = $entry['budgeted']; + $totalBudgeted = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; + $budgetedPct = '0'; if (0 !== bccomp((string) $spent, '0') && 0 !== bccomp($totalSpent, '0')) { $spentPct = round((float) bcmul(bcdiv((string) $spent, $totalSpent), '100')); @@ -218,7 +218,7 @@ class BudgetReportGenerator $budgetedPct = round((float) bcmul(bcdiv((string) $budgeted, $totalBudgeted), '100')); } $this->report['sums'][$currencyId]['budgeted'] ??= '0'; - $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; + $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['budgeted_pct'] = $budgetedPct; } } @@ -234,11 +234,11 @@ class BudgetReportGenerator 'budget_id' => $budgetId, 'budget_name' => $budget->name, 'no_budget' => false, - 'budget_limits' => [] + 'budget_limits' => [], ]; // get all budget limits for budget in period: - $limits = $this->blRepository->getBudgetLimits($budget, $this->start, $this->end); + $limits = $this->blRepository->getBudgetLimits($budget, $this->start, $this->end); /** @var BudgetLimit $limit */ foreach ($limits as $limit) { @@ -254,14 +254,14 @@ class BudgetReportGenerator $budgetId = (int) $budget['id']; $currencyId = (int) $expenses['currency_id']; foreach ($budget['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; - $this->report[$sourceAccountId]['currencies'][$currencyId] ??= [ + $this->report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $expenses['currency_id'], 'currency_symbol' => $expenses['currency_symbol'], 'currency_name' => $expenses['currency_name'], 'currency_decimal_places' => $expenses['currency_decimal_places'], - 'budgets' => [] + 'budgets' => [], ]; $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId] ??= '0'; @@ -288,14 +288,14 @@ class BudgetReportGenerator */ private function processLimit(Budget $budget, BudgetLimit $limit): void { - $budgetId = $budget->id; - $limitId = $limit->id; - $limitCurrency = $limit->transactionCurrency ?? $this->currency; - $currencyId = $limitCurrency->id; - $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection()->push($budget)); - $spent = $expenses[$currencyId]['sum'] ?? '0'; - $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); - $overspent = 1 === bccomp(bcmul($spent, '-1'), $limit->amount) ? bcadd($spent, $limit->amount) : '0'; + $budgetId = $budget->id; + $limitId = $limit->id; + $limitCurrency = $limit->transactionCurrency ?? $this->currency; + $currencyId = $limitCurrency->id; + $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection()->push($budget)); + $spent = $expenses[$currencyId]['sum'] ?? '0'; + $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); + $overspent = 1 === bccomp(bcmul($spent, '-1'), $limit->amount) ? bcadd($spent, $limit->amount) : '0'; $this->report['budgets'][$budgetId]['budget_limits'][$limitId] ??= [ 'budget_limit_id' => $limitId, @@ -311,11 +311,11 @@ class BudgetReportGenerator 'currency_code' => $limitCurrency->code, 'currency_name' => $limitCurrency->name, 'currency_symbol' => $limitCurrency->symbol, - 'currency_decimal_places' => $limitCurrency->decimal_places + 'currency_decimal_places' => $limitCurrency->decimal_places, ]; // make sum information: - $this->report['sums'][$currencyId] ??= [ + $this->report['sums'][$currencyId] ??= [ 'budgeted' => '0', 'spent' => '0', 'left' => '0', @@ -324,11 +324,11 @@ class BudgetReportGenerator 'currency_code' => $limitCurrency->code, 'currency_name' => $limitCurrency->name, 'currency_symbol' => $limitCurrency->symbol, - 'currency_decimal_places' => $limitCurrency->decimal_places + 'currency_decimal_places' => $limitCurrency->decimal_places, ]; - $this->report['sums'][$currencyId]['budgeted'] = bcadd((string) $this->report['sums'][$currencyId]['budgeted'], $limit->amount); - $this->report['sums'][$currencyId]['spent'] = bcadd((string) $this->report['sums'][$currencyId]['spent'], $spent); - $this->report['sums'][$currencyId]['left'] = bcadd((string) $this->report['sums'][$currencyId]['left'], bcadd($limit->amount, $spent)); + $this->report['sums'][$currencyId]['budgeted'] = bcadd((string) $this->report['sums'][$currencyId]['budgeted'], $limit->amount); + $this->report['sums'][$currencyId]['spent'] = bcadd((string) $this->report['sums'][$currencyId]['spent'], $spent); + $this->report['sums'][$currencyId]['left'] = bcadd((string) $this->report['sums'][$currencyId]['left'], bcadd($limit->amount, $spent)); $this->report['sums'][$currencyId]['overspent'] = bcadd((string) $this->report['sums'][$currencyId]['overspent'], $overspent); } } diff --git a/app/Support/Report/Category/CategoryReportGenerator.php b/app/Support/Report/Category/CategoryReportGenerator.php index 0373294d88..1dd7969019 100644 --- a/app/Support/Report/Category/CategoryReportGenerator.php +++ b/app/Support/Report/Category/CategoryReportGenerator.php @@ -47,7 +47,7 @@ class CategoryReportGenerator */ public function __construct() { - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); $this->noCatRepository = app(NoCategoryRepositoryInterface::class); } @@ -62,17 +62,17 @@ class CategoryReportGenerator */ public function operations(): void { - $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); - $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); + $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); + $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); // also transferred out and transferred into these accounts in this category: $transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts); $transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts); - $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); - $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); + $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); + $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); - $this->report = ['categories' => [], 'sums' => []]; + $this->report = ['categories' => [], 'sums' => []]; // needs four for-each loops. foreach ([$earnedWith, $spentWith, $earnedWithout, $spentWithout, $transferredIn, $transferredOut] as $data) { @@ -114,14 +114,14 @@ class CategoryReportGenerator 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0' + 'sum' => '0', ]; // loop journals: foreach ($categoryRow['transaction_journals'] as $journal) { // sum of sums - $this->report['sums'][$currencyId]['sum'] = bcadd((string) $this->report['sums'][$currencyId]['sum'], (string) $journal['amount']); + $this->report['sums'][$currencyId]['sum'] = bcadd((string) $this->report['sums'][$currencyId]['sum'], (string) $journal['amount']); // sum of spent: - $this->report['sums'][$currencyId]['spent'] = -1 === bccomp((string) $journal['amount'], '0') + $this->report['sums'][$currencyId]['spent'] = -1 === bccomp((string) $journal['amount'], '0') ? bcadd((string) $this->report['sums'][$currencyId]['spent'], (string) $journal['amount']) : $this->report['sums'][$currencyId]['spent']; // sum of earned @@ -130,13 +130,13 @@ class CategoryReportGenerator : $this->report['sums'][$currencyId]['earned']; // sum of category - $this->report['categories'][$key]['sum'] = bcadd((string) $this->report['categories'][$key]['sum'], (string) $journal['amount']); + $this->report['categories'][$key]['sum'] = bcadd((string) $this->report['categories'][$key]['sum'], (string) $journal['amount']); // total spent in category - $this->report['categories'][$key]['spent'] = -1 === bccomp((string) $journal['amount'], '0') + $this->report['categories'][$key]['spent'] = -1 === bccomp((string) $journal['amount'], '0') ? bcadd((string) $this->report['categories'][$key]['spent'], (string) $journal['amount']) : $this->report['categories'][$key]['spent']; // total earned in category - $this->report['categories'][$key]['earned'] = 1 === bccomp((string) $journal['amount'], '0') + $this->report['categories'][$key]['earned'] = 1 === bccomp((string) $journal['amount'], '0') ? bcadd((string) $this->report['categories'][$key]['earned'], (string) $journal['amount']) : $this->report['categories'][$key]['earned']; } @@ -152,7 +152,7 @@ class CategoryReportGenerator 'currency_symbol' => $currencyRow['currency_symbol'], 'currency_name' => $currencyRow['currency_name'], 'currency_code' => $currencyRow['currency_code'], - 'currency_decimal_places' => $currencyRow['currency_decimal_places'] + 'currency_decimal_places' => $currencyRow['currency_decimal_places'], ]; /** diff --git a/app/Support/Report/Summarizer/TransactionSummarizer.php b/app/Support/Report/Summarizer/TransactionSummarizer.php index e117ffdf8b..921d897857 100644 --- a/app/Support/Report/Summarizer/TransactionSummarizer.php +++ b/app/Support/Report/Summarizer/TransactionSummarizer.php @@ -36,7 +36,7 @@ class TransactionSummarizer private TransactionCurrency $default; private User $user; - public function __construct(null|User $user = null) + public function __construct(?User $user = null) { if ($user instanceof User) { $this->setUser($user); @@ -48,14 +48,14 @@ class TransactionSummarizer Log::debug(sprintf('Now in groupByCurrencyId([%d journals], "%s", %s)', count($journals), $method, var_export($includeForeign, true))); $array = []; foreach ($journals as $journal) { - $field = 'amount'; + $field = 'amount'; // grab default currency information. - $currencyId = (int) $journal['currency_id']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyCode = $journal['currency_code']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; + $currencyId = (int) $journal['currency_id']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyCode = $journal['currency_code']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; // prepare foreign currency info: $foreignCurrencyId = 0; @@ -106,14 +106,14 @@ class TransactionSummarizer } // first process normal amount - $amount = (string) ($journal[$field] ?? '0'); + $amount = (string) ($journal[$field] ?? '0'); $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces + 'currency_decimal_places' => $currencyDecimalPlaces, ]; if ('positive' === $method) { @@ -132,7 +132,7 @@ class TransactionSummarizer 'currency_name' => $foreignCurrencyName, 'currency_symbol' => $foreignCurrencySymbol, 'currency_code' => $foreignCurrencyCode, - 'currency_decimal_places' => $foreignCurrencyDecimalPlaces + 'currency_decimal_places' => $foreignCurrencyDecimalPlaces, ]; if ('positive' === $method) { @@ -181,7 +181,7 @@ class TransactionSummarizer if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } - $key = sprintf('%s-%s', $journal[$idKey], $currencyId); + $key = sprintf('%s-%s', $journal[$idKey], $currencyId); // sum it all up or create a new array. $array[$key] ??= [ 'id' => $journal[$idKey], @@ -191,11 +191,11 @@ class TransactionSummarizer 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces + 'currency_decimal_places' => $currencyDecimalPlaces, ]; // add the data from the $field to the array. - $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) ($journal[$field] ?? '0'))); // @phpstan-ignore-line + $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) ($journal[$field] ?? '0'))); // @phpstan-ignore-line Log::debug(sprintf( 'Field for transaction #%d is "%s" (%s). Sum: %s', $journal['transaction_group_id'], @@ -214,7 +214,7 @@ class TransactionSummarizer $journal['foreign_amount'], $array[$key]['sum'] )); - $key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']); + $key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']); $array[$key] ??= [ 'id' => $journal[$idKey], 'name' => $journal[$nameKey], @@ -223,7 +223,7 @@ class TransactionSummarizer 'currency_name' => $journal['foreign_currency_name'], 'currency_symbol' => $journal['foreign_currency_symbol'], 'currency_code' => $journal['foreign_currency_code'], - 'currency_decimal_places' => $journal['foreign_currency_decimal_places'] + 'currency_decimal_places' => $journal['foreign_currency_decimal_places'], ]; $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) $journal['foreign_amount'])); // @phpstan-ignore-line } @@ -240,8 +240,8 @@ class TransactionSummarizer public function setUser(User $user): void { - $this->user = $user; - $this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $this->user = $user; + $this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); $this->convertToPrimary = Amount::convertToPrimary($user); } } diff --git a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php index f333bda663..5df0917c24 100644 --- a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php @@ -66,7 +66,7 @@ trait CalculateRangeOccurrences } while ($start < $end) { $domCorrected = min($dayOfMonth, $start->daysInMonth); - $start->day = $domCorrected; + $start->day = $domCorrected; if (0 === ($attempts % $skipMod) && $start->lte($start) && $end->gte($start)) { $return[] = clone $start; } @@ -83,8 +83,8 @@ trait CalculateRangeOccurrences */ protected function getNdomInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $return = []; - $attempts = 0; + $return = []; + $attempts = 0; $start->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? $counters = [1 => 'first', 2 => 'second', 3 => 'third', 4 => 'fourth', 5 => 'fifth']; @@ -109,12 +109,12 @@ trait CalculateRangeOccurrences */ protected function getWeeklyInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $return = []; - $attempts = 0; + $return = []; + $attempts = 0; Log::debug('Rep is weekly.'); // monday = 1 // sunday = 7 - $dayOfWeek = (int) $moment; + $dayOfWeek = (int) $moment; 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: @@ -146,17 +146,17 @@ trait CalculateRangeOccurrences */ protected function getYearlyInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $attempts = 0; - $date = new Carbon($moment); + $attempts = 0; + $date = new Carbon($moment); $date->year = $start->year; - $return = []; + $return = []; if ($start > $date) { $date->addYear(); } // is $date between $start and $end? - $obj = clone $date; - $count = 0; + $obj = clone $date; + $count = 0; while ($obj <= $end && $obj >= $start && $count < 10) { if (0 === ($attempts % $skipMod)) { $return[] = clone $obj; diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrences.php b/app/Support/Repositories/Recurring/CalculateXOccurrences.php index fc871155f1..c53c9d8e67 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrences.php @@ -89,10 +89,10 @@ trait CalculateXOccurrences */ protected function getXNDomOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; $mutator->addDay(); // always assume today has passed. $mutator->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? @@ -120,14 +120,14 @@ trait CalculateXOccurrences */ protected function getXWeeklyOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; // monday = 1 // sunday = 7 $mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int) $moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); @@ -155,16 +155,16 @@ trait CalculateXOccurrences */ protected function getXYearlyOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $mutator = clone $date; - $total = 0; - $attempts = 0; - $date = new Carbon($moment); + $return = []; + $mutator = clone $date; + $total = 0; + $attempts = 0; + $date = new Carbon($moment); $date->year = $mutator->year; if ($mutator > $date) { $date->addYear(); } - $obj = clone $date; + $obj = clone $date; while ($total < $count) { if (0 === ($attempts % $skipMod)) { $return[] = clone $obj; diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php index 828e0eb949..14eb19b361 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php @@ -87,7 +87,7 @@ trait CalculateXOccurrencesSince ++$total; } ++$attempts; - $mutator = $mutator->endOfMonth()->addDay(); + $mutator = $mutator->endOfMonth()->addDay(); } Log::debug('Collected enough occurrences.'); @@ -103,10 +103,10 @@ trait CalculateXOccurrencesSince protected function getXNDomOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; $mutator->addDay(); // always assume today has passed. $mutator->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? @@ -137,15 +137,15 @@ trait CalculateXOccurrencesSince protected function getXWeeklyOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; // monday = 1 // sunday = 7 // Removed assumption today has passed, see issue https://github.com/firefly-iii/firefly-iii/issues/4798 // $mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int) $moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); @@ -176,11 +176,11 @@ trait CalculateXOccurrencesSince protected function getXYearlyOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s(%s, %d, %d, %s)', __METHOD__, $date->format('Y-m-d'), $date->format('Y-m-d'), $count, $skipMod)); - $return = []; - $mutator = clone $date; - $total = 0; - $attempts = 0; - $date = new Carbon($moment); + $return = []; + $mutator = clone $date; + $total = 0; + $attempts = 0; + $date = new Carbon($moment); $date->year = $mutator->year; if ($mutator > $date) { Log::debug(sprintf( @@ -192,7 +192,7 @@ trait CalculateXOccurrencesSince $date->addYear(); Log::debug(sprintf('Date is now %s', $date->format('Y-m-d'))); } - $obj = clone $date; + $obj = clone $date; while ($total < $count) { Log::debug(sprintf('total (%d) < count (%d) so go.', $total, $count)); Log::debug(sprintf('attempts (%d) %% skipmod (%d) === %d', $attempts, $skipMod, $attempts % $skipMod)); diff --git a/app/Support/Repositories/Recurring/FiltersWeekends.php b/app/Support/Repositories/Recurring/FiltersWeekends.php index 753befdfb7..c6d6eeaccf 100644 --- a/app/Support/Repositories/Recurring/FiltersWeekends.php +++ b/app/Support/Repositories/Recurring/FiltersWeekends.php @@ -46,7 +46,7 @@ trait FiltersWeekends return $dates; } - $return = []; + $return = []; /** @var Carbon $date */ foreach ($dates as $date) { @@ -60,7 +60,7 @@ trait FiltersWeekends // is weekend and must set back to Friday? if (RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value === $repetition->weekend) { - $clone = clone $date; + $clone = clone $date; $clone->addDays(5 - $date->dayOfWeekIso); Log::debug(sprintf( 'Date is %s, and this is in the weekend, so corrected to %s (Friday).', @@ -74,7 +74,7 @@ trait FiltersWeekends // postpone to Monday? if (RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value === $repetition->weekend) { - $clone = clone $date; + $clone = clone $date; $clone->addDays(8 - $date->dayOfWeekIso); Log::debug(sprintf( 'Date is %s, and this is in the weekend, so corrected to %s (Monday).', diff --git a/app/Support/Repositories/UserGroup/UserGroupInterface.php b/app/Support/Repositories/UserGroup/UserGroupInterface.php index 82e8f6ccd6..d7a737b919 100644 --- a/app/Support/Repositories/UserGroup/UserGroupInterface.php +++ b/app/Support/Repositories/UserGroup/UserGroupInterface.php @@ -33,9 +33,9 @@ interface UserGroupInterface { public function checkUserGroupAccess(UserRoleEnum $role): bool; - public function getUser(): null|User; + public function getUser(): ?User; - public function getUserGroup(): null|UserGroup; + public function getUserGroup(): ?UserGroup; public function setUser(Authenticatable|User|null $user): void; diff --git a/app/Support/Repositories/UserGroup/UserGroupTrait.php b/app/Support/Repositories/UserGroup/UserGroupTrait.php index 6940fe5ac6..c9d3b3fc1c 100644 --- a/app/Support/Repositories/UserGroup/UserGroupTrait.php +++ b/app/Support/Repositories/UserGroup/UserGroupTrait.php @@ -37,8 +37,8 @@ use Illuminate\Support\Facades\Log; */ trait UserGroupTrait { - protected null|User $user = null; - protected null|UserGroup $userGroup = null; + protected ?User $user = null; + protected ?UserGroup $userGroup = null; public function checkUserGroupAccess(UserRoleEnum $role): bool { @@ -53,7 +53,7 @@ trait UserGroupTrait return false; } - public function getUser(): null|User + public function getUser(): ?User { return $this->user; } @@ -64,7 +64,7 @@ trait UserGroupTrait public function setUser(Authenticatable|User|null $user): void { if ($user instanceof User) { - $this->user = $user; + $this->user = $user; if (null === $user->userGroup) { throw new FireflyException(sprintf('User #%d ("%s") has no user group.', $user->id, $user->email)); } @@ -77,7 +77,7 @@ trait UserGroupTrait throw new FireflyException(sprintf('Object is %s, not User.', $class)); } - public function getUserGroup(): null|UserGroup + public function getUserGroup(): ?UserGroup { return $this->userGroup; } @@ -104,7 +104,7 @@ trait UserGroupTrait } /** @var null|UserGroup $userGroup */ - $userGroup = UserGroup::find($userGroupId); + $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { throw new FireflyException(sprintf('Cannot find administration for user #%d', $this->user->id)); } diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php index 74112ad460..0db2b39909 100644 --- a/app/Support/Request/AppendsLocationData.php +++ b/app/Support/Request/AppendsLocationData.php @@ -39,9 +39,9 @@ trait AppendsLocationData $lat = $information['latitude'] ?? null; if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) { $return['store_location'] = true; - $return['longitude'] = $information['longitude']; - $return['latitude'] = $information['latitude']; - $return['zoom_level'] = $information['zoom_level']; + $return['longitude'] = $information['longitude']; + $return['latitude'] = $information['latitude']; + $return['zoom_level'] = $information['zoom_level']; } } @@ -88,39 +88,39 @@ trait AppendsLocationData /** * Read the submitted Request data and add new or updated Location data to the array. */ - protected function appendLocationData(array $data, null|string $prefix): array + protected function appendLocationData(array $data, ?string $prefix): array { Log::debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); - $data['store_location'] = false; + $data['store_location'] = false; $data['update_location'] = false; $data['remove_location'] = false; - $data['longitude'] = null; - $data['latitude'] = null; - $data['zoom_level'] = null; + $data['longitude'] = null; + $data['latitude'] = null; + $data['zoom_level'] = null; - $longitudeKey = $this->getLocationKey($prefix, 'longitude'); - $latitudeKey = $this->getLocationKey($prefix, 'latitude'); - $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); - $isValidPOST = $this->isValidPost($prefix); - $isValidPUT = $this->isValidPUT($prefix); - $isValidEmptyPUT = $this->isValidEmptyPUT($prefix); + $longitudeKey = $this->getLocationKey($prefix, 'longitude'); + $latitudeKey = $this->getLocationKey($prefix, 'latitude'); + $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); + $isValidPOST = $this->isValidPost($prefix); + $isValidPUT = $this->isValidPUT($prefix); + $isValidEmptyPUT = $this->isValidEmptyPUT($prefix); // for a POST (store), all fields must be present and not NULL. if ($isValidPOST) { 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); - $data['zoom_level'] = $this->convertString($zoomLevelKey); + $data['longitude'] = $this->convertString($longitudeKey); + $data['latitude'] = $this->convertString($latitudeKey); + $data['zoom_level'] = $this->convertString($zoomLevelKey); } // for a PUT (api update) or POST update (UI) if ($isValidPUT) { 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); + $data['longitude'] = $this->convertString($longitudeKey); + $data['latitude'] = $this->convertString($latitudeKey); + $data['zoom_level'] = $this->convertString($zoomLevelKey); } if ($isValidEmptyPUT) { Log::debug('Method is PUT and all fields present and NULL.'); @@ -137,7 +137,7 @@ trait AppendsLocationData return $data; } - private function getLocationKey(null|string $prefix, string $key): string + private function getLocationKey(?string $prefix, string $key): string { if (null === $prefix) { return $key; @@ -146,21 +146,20 @@ trait AppendsLocationData return sprintf('%s_%s', $prefix, $key); } - private function isValidEmptyPUT(null|string $prefix): bool + private function isValidEmptyPUT(?string $prefix): bool { $longitudeKey = $this->getLocationKey($prefix, 'longitude'); $latitudeKey = $this->getLocationKey($prefix, 'latitude'); $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); - return ( + return null === $this->get($longitudeKey) && null === $this->get($latitudeKey) && null === $this->get($zoomLevelKey) - && ('PUT' === $this->method() || 'POST' === $this->method() && $this->routeIs('*.update')) - ); + && ('PUT' === $this->method() || 'POST' === $this->method() && $this->routeIs('*.update')); } - private function isValidPUT(null|string $prefix): bool + private function isValidPUT(?string $prefix): bool { $longitudeKey = $this->getLocationKey($prefix, 'longitude'); $latitudeKey = $this->getLocationKey($prefix, 'latitude'); @@ -200,7 +199,7 @@ trait AppendsLocationData return false; } - private function isValidPost(null|string $prefix): bool + private function isValidPost(?string $prefix): bool { Log::debug('Now in isValidPost()'); $longitudeKey = $this->getLocationKey($prefix, 'longitude'); diff --git a/app/Support/Request/ChecksLogin.php b/app/Support/Request/ChecksLogin.php index 905e1a9424..15dd960b8f 100644 --- a/app/Support/Request/ChecksLogin.php +++ b/app/Support/Request/ChecksLogin.php @@ -41,7 +41,7 @@ trait ChecksLogin { Log::debug(sprintf('Now in %s', __METHOD__)); // Only allow logged-in users - $check = auth()->check(); + $check = auth()->check(); if (!$check) { return false; } @@ -77,10 +77,10 @@ trait ChecksLogin * Will throw exception if invalid. * TODO duplicated in JSONAPI code. */ - public function getUserGroup(): null|UserGroup + public function getUserGroup(): ?UserGroup { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug('Now in getUserGroup()'); /** @var null|UserGroup $userGroup */ @@ -92,7 +92,7 @@ trait ChecksLogin 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); + $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { Log::error(sprintf('Request class has user_group_id (#%d), but group does not exist.', $userGroupId)); diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index e325adf055..901ea52926 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -88,17 +88,17 @@ trait ConvertsDataTypes "\u{202F}", // narrow no-break space "\u{3000}", // ideographic space "\u{FEFF}", // zero width no -break space - "\r" // carriage return + "\r", // carriage return ]; - public function clearIban(null|string $string): null|string + public function clearIban(?string $string): ?string { $string = $this->clearString($string); return Steam::filterSpaces($string); } - public function clearString(null|string $string): null|string + public function clearString(?string $string): ?string { $string = $this->clearStringKeepNewlines($string); @@ -115,7 +115,7 @@ trait ConvertsDataTypes return trim($string); } - public function clearStringKeepNewlines(null|string $string): null|string + public function clearStringKeepNewlines(?string $string): ?string { if (null === $string) { return null; @@ -147,15 +147,15 @@ trait ConvertsDataTypes public function convertSortParameters(string $field, string $class): array { // assume this all works, because the validator would have caught any errors. - $parameter = (string) request()->query->get($field); + $parameter = (string) request()->query->get($field); if ('' === $parameter) { return []; } $parts = explode(',', $parameter); $sortParameters = []; foreach ($parts as $part) { - $part = trim($part); - $direction = 'asc'; + $part = trim($part); + $direction = 'asc'; if ('-' === $part[0]) { $part = substr($part, 1); $direction = 'desc'; @@ -238,7 +238,7 @@ trait ConvertsDataTypes /** * @param mixed $array */ - protected function arrayFromValue($array): null|array + protected function arrayFromValue($array): ?array { if (is_array($array)) { return $array; @@ -253,7 +253,7 @@ trait ConvertsDataTypes return null; } - protected function convertBoolean(null|string $value): bool + protected function convertBoolean(?string $value): bool { if (null === $value) { return false; @@ -277,7 +277,7 @@ trait ConvertsDataTypes return '1' === $value; } - protected function convertDateTime(null|string $string): null|Carbon + protected function convertDateTime(?string $string): ?Carbon { $value = $this->get((string) $string); if (null === $value) { @@ -328,7 +328,7 @@ trait ConvertsDataTypes /** * Return floating value. */ - protected function convertFloat(string $field): null|float + protected function convertFloat(string $field): ?float { $res = $this->get($field); if (null === $res) { @@ -338,7 +338,7 @@ trait ConvertsDataTypes return (float) $res; } - protected function dateFromValue(null|string $string): null|Carbon + protected function dateFromValue(?string $string): ?Carbon { if (null === $string) { return null; @@ -363,7 +363,7 @@ trait ConvertsDataTypes return $carbon; } - protected function floatFromValue(null|string $string): null|float + protected function floatFromValue(?string $string): ?float { if (null === $string) { return null; @@ -384,7 +384,7 @@ trait ConvertsDataTypes $return = []; foreach ($fields as $field => $info) { if (true === $this->has($info[0])) { - $method = $info[1]; + $method = $info[1]; $return[$field] = $this->{$method}($info[0]); // @phpstan-ignore-line } } @@ -395,7 +395,7 @@ trait ConvertsDataTypes /** * Return date or NULL. */ - protected function getCarbonDate(string $field): null|Carbon + protected function getCarbonDate(string $field): ?Carbon { $data = (string) $this->get($field); Log::debug(sprintf('Date string is "%s"', $data)); @@ -417,7 +417,7 @@ trait ConvertsDataTypes /** * Parse to integer */ - protected function integerFromValue(null|string $string): null|int + protected function integerFromValue(?string $string): ?int { if (null === $string) { return null; @@ -432,7 +432,7 @@ trait ConvertsDataTypes /** * Return integer value, or NULL when it's not set. */ - protected function nullableInteger(string $field): null|int + protected function nullableInteger(string $field): ?int { if (false === $this->has($field)) { return null; @@ -456,7 +456,7 @@ trait ConvertsDataTypes if (!is_array($entry)) { continue; } - $amount = null; + $amount = null; if (array_key_exists('current_amount', $entry)) { $amount = $this->clearString((string) ($entry['current_amount'] ?? '0')); if (null === $entry['current_amount']) { diff --git a/app/Support/Request/ValidatesWebhooks.php b/app/Support/Request/ValidatesWebhooks.php index 711cbc7f56..f49885f992 100644 --- a/app/Support/Request/ValidatesWebhooks.php +++ b/app/Support/Request/ValidatesWebhooks.php @@ -38,9 +38,9 @@ trait ValidatesWebhooks if (count($validator->failed()) > 0) { return; } - $data = $validator->getData(); - $triggers = $data['triggers'] ?? []; - $responses = $data['responses'] ?? []; + $data = $validator->getData(); + $triggers = $data['triggers'] ?? []; + $responses = $data['responses'] ?? []; if (0 === count($triggers) || 0 === count($responses)) { Log::debug('No trigger or response, return.'); diff --git a/app/Support/Search/AccountSearch.php b/app/Support/Search/AccountSearch.php index 8e556410e2..516c7d1405 100644 --- a/app/Support/Search/AccountSearch.php +++ b/app/Support/Search/AccountSearch.php @@ -36,19 +36,19 @@ use function Safe\json_encode; */ class AccountSearch implements GenericSearchInterface { - public const string SEARCH_ALL = 'all'; + public const string SEARCH_ALL = 'all'; - public const string SEARCH_IBAN = 'iban'; + public const string SEARCH_IBAN = 'iban'; - public const string SEARCH_ID = 'id'; + public const string SEARCH_ID = 'id'; - public const string SEARCH_NAME = 'name'; + public const string SEARCH_NAME = 'name'; public const string SEARCH_NUMBER = 'number'; private string $field; private string $query; - private array $types = []; + private array $types = []; private User $user; public function search(): Collection @@ -57,7 +57,8 @@ class AccountSearch implements GenericSearchInterface ->accounts() ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') - ->whereIn('account_types.type', $this->types); + ->whereIn('account_types.type', $this->types) + ; $like = sprintf('%%%s%%', $this->query); $originalQuery = $this->query; diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index bfb5d22d3e..a6764c3eba 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -68,19 +68,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 = 25; private readonly Collection $operators; - private int $page = 1; - 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. @@ -88,14 +88,14 @@ class OperatorQuerySearch implements SearchInterface public function __construct() { Log::debug('Constructed OperatorQuerySearch'); - $this->operators = new Collection(); - $this->validOperators = array_keys(config('search.operators')); - $this->startTime = microtime(true); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->operators = new Collection(); + $this->validOperators = array_keys(config('search.operators')); + $this->startTime = microtime(true); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->tagRepository = app(TagRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->tagRepository = app(TagRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class); } @@ -111,7 +111,7 @@ class OperatorQuerySearch implements SearchInterface $operator = substr($operator, 1); } - $config = config(sprintf('search.operators.%s', $operator)); + $config = config(sprintf('search.operators.%s', $operator)); if (null === $config) { throw new FireflyException(sprintf('No configuration for search operator "%s"', $operator)); } @@ -241,12 +241,13 @@ class OperatorQuerySearch implements SearchInterface $this->collector ->withAccountInformation() ->withCategoryInformation() - ->withBudgetInformation(); + ->withBudgetInformation() + ; $this->setLimit((int) Preferences::getForUser($user, 'listPageSize', 50)->data); } - private function findCurrency(string $value): null|TransactionCurrency + private function findCurrency(string $value): ?TransactionCurrency { if (str_contains($value, '(') && str_contains($value, ')')) { // bad method to split and get the currency code: @@ -275,7 +276,7 @@ class OperatorQuerySearch implements SearchInterface $value = $node->getValue(); $prohibited = $node->isProhibited($flipProhibitedFlag); - $context = config(sprintf('search.operators.%s.needs_context', $operator)); + $context = config(sprintf('search.operators.%s.needs_context', $operator)); // is an operator that needs no context, and value is false, then prohibited = true. if ('false' === $value && in_array($operator, $this->validOperators, true) && false === $context && !$prohibited) { @@ -289,7 +290,7 @@ class OperatorQuerySearch implements SearchInterface } // must be valid operator: - $inArray = in_array($operator, $this->validOperators, true); + $inArray = in_array($operator, $this->validOperators, true); 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)); @@ -343,7 +344,7 @@ class OperatorQuerySearch implements SearchInterface private function handleStringNode(StringNode $node, bool $flipProhibitedFlag): void { - $string = $node->getValue(); + $string = $node->getValue(); $prohibited = $node->isProhibited($flipProhibitedFlag); @@ -438,7 +439,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; $collectorMethod = 'setSourceAccounts'; if ($prohibited) { @@ -453,7 +454,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::EXPENSE->value + AccountTypeEnum::EXPENSE->value, ]; $collectorMethod = 'setDestinationAccounts'; if ($prohibited) { @@ -468,7 +469,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; $collectorMethod = 'setAccounts'; if ($prohibited) { @@ -476,7 +477,7 @@ class OperatorQuerySearch implements SearchInterface } } // string position (default): starts with: - $stringMethod = 'str_starts_with'; + $stringMethod = 'str_starts_with'; // string position: ends with: if (StringPosition::ENDS === $stringPosition) { @@ -490,7 +491,7 @@ class OperatorQuerySearch implements SearchInterface } // get accounts: - $accounts = $this->accountRepository->searchAccount($value, $searchTypes, 1337); + $accounts = $this->accountRepository->searchAccount($value, $searchTypes, 1337); if (0 === $accounts->count() && false === $prohibited) { Log::warning('Found zero accounts, search for non existing account, NO results will be returned.'); $this->collector->findNothing(); @@ -503,7 +504,7 @@ class OperatorQuerySearch implements SearchInterface return; } Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); - $filtered = $accounts->filter(static fn(Account $account): bool => $stringMethod(strtolower($account->name), strtolower($value))); + $filtered = $accounts->filter(static fn (Account $account): bool => $stringMethod(strtolower($account->name), strtolower($value))); if (0 === $filtered->count()) { Log::warning('Left with zero accounts, so cannot find anything, NO results will be returned.'); @@ -533,7 +534,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; $collectorMethod = 'setSourceAccounts'; if ($prohibited) { @@ -548,7 +549,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::EXPENSE->value + AccountTypeEnum::EXPENSE->value, ]; $collectorMethod = 'setDestinationAccounts'; if ($prohibited) { @@ -564,7 +565,7 @@ class OperatorQuerySearch implements SearchInterface AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value, - AccountTypeEnum::REVENUE->value + AccountTypeEnum::REVENUE->value, ]; $collectorMethod = 'setAccounts'; if ($prohibited) { @@ -573,7 +574,7 @@ class OperatorQuerySearch implements SearchInterface } // string position (default): starts with: - $stringMethod = 'str_starts_with'; + $stringMethod = 'str_starts_with'; // string position: ends with: if (StringPosition::ENDS === $stringPosition) { @@ -587,7 +588,7 @@ class OperatorQuerySearch implements SearchInterface } // search for accounts: - $accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 1337); + $accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 1337); if (0 === $accounts->count()) { Log::debug('Found zero accounts, search for invalid account.'); Log::warning('Call to findNothing() from searchAccountNr().'); @@ -598,7 +599,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): bool { + $filtered = $accounts->filter(static function (Account $account) use ($value, $stringMethod): bool { // either IBAN or account number $ibanMatch = $stringMethod(strtolower((string) $account->iban), strtolower($value)); $accountNrMatch = false; @@ -1264,13 +1265,13 @@ class OperatorQuerySearch implements SearchInterface throw new FireflyException(sprintf('Unsupported search operator: "%s"', $operator)); - // some search operators are ignored, basically: + // some search operators are ignored, basically: case 'user_action': Log::info(sprintf('Ignore search operator "%s"', $operator)); return false; - // all account related searches: + // all account related searches: case 'account_is': $this->searchAccount($value, SearchDirection::BOTH, StringPosition::IS); @@ -1433,7 +1434,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'source_account_id': - $account = $this->accountRepository->find((int) $value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setSourceAccounts(new Collection()->push($account)); } @@ -1446,7 +1447,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-source_account_id': - $account = $this->accountRepository->find((int) $value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->excludeSourceAccounts(new Collection()->push($account)); } @@ -1459,25 +1460,25 @@ class OperatorQuerySearch implements SearchInterface break; case 'journal_id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->setJournalIds($parts); break; case '-journal_id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->excludeJournalIds($parts); break; case 'id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->setIds($parts); break; case '-id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->excludeIds($parts); break; @@ -1563,7 +1564,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'destination_account_id': - $account = $this->accountRepository->find((int) $value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setDestinationAccounts(new Collection()->push($account)); } @@ -1575,7 +1576,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-destination_account_id': - $account = $this->accountRepository->find((int) $value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->excludeDestinationAccounts(new Collection()->push($account)); } @@ -1588,12 +1589,12 @@ class OperatorQuerySearch implements SearchInterface case 'account_id': Log::debug(sprintf('Now in "account_id" with value "%s"', $value)); - $parts = explode(',', $value); - $collection = new Collection(); + $parts = explode(',', $value); + $collection = new Collection(); foreach ($parts as $accountId) { $accountId = (int) $accountId; Log::debug(sprintf('Searching for account with ID #%d', $accountId)); - $account = $this->accountRepository->find($accountId); + $account = $this->accountRepository->find($accountId); if (null !== $account) { Log::debug(sprintf('Found account with ID #%d ("%s")', $accountId, $account->name)); $collection->push($account); @@ -1614,8 +1615,8 @@ class OperatorQuerySearch implements SearchInterface break; case '-account_id': - $parts = explode(',', $value); - $collection = new Collection(); + $parts = explode(',', $value); + $collection = new Collection(); foreach ($parts as $accountId) { $account = $this->accountRepository->find((int) $accountId); if (null !== $account) { @@ -1632,45 +1633,45 @@ class OperatorQuerySearch implements SearchInterface break; - // cash account + // cash account case 'source_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setSourceAccounts(new Collection()->push($account)); break; case '-source_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeSourceAccounts(new Collection()->push($account)); break; case 'destination_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setDestinationAccounts(new Collection()->push($account)); break; case '-destination_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeDestinationAccounts(new Collection()->push($account)); break; case 'account_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setAccounts(new Collection()->push($account)); break; case '-account_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeAccounts(new Collection()->push($account)); break; - // description + // description case 'description_starts': $this->collector->descriptionStarts([$value]); @@ -1693,7 +1694,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'description_contains': - $this->words[] = $value; + $this->words[] = $value; return false; @@ -1712,10 +1713,10 @@ class OperatorQuerySearch implements SearchInterface break; - // currency + // currency case 'currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->setCurrency($currency); } @@ -1727,7 +1728,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->excludeCurrency($currency); } @@ -1739,7 +1740,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'foreign_currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->setForeignCurrency($currency); } @@ -1751,7 +1752,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-foreign_currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->excludeForeignCurrency($currency); } @@ -1762,7 +1763,7 @@ class OperatorQuerySearch implements SearchInterface break; - // attachments + // attachments case 'has_attachments': case '-has_no_attachments': @@ -1778,7 +1779,7 @@ class OperatorQuerySearch implements SearchInterface break; - // categories + // categories case '-has_any_category': case 'has_no_category': $this->collector->withoutCategory(); @@ -1792,7 +1793,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_is': - $category = $this->categoryRepository->findByName($value); + $category = $this->categoryRepository->findByName($value); if (null !== $category) { $this->collector->setCategory($category); @@ -1804,7 +1805,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_is': - $category = $this->categoryRepository->findByName($value); + $category = $this->categoryRepository->findByName($value); if (null !== $category) { $this->collector->excludeCategory($category); @@ -1814,7 +1815,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_ends': - $result = $this->categoryRepository->categoryEndsWith($value, 1337); + $result = $this->categoryRepository->categoryEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1826,7 +1827,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_ends': - $result = $this->categoryRepository->categoryEndsWith($value, 1337); + $result = $this->categoryRepository->categoryEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1838,7 +1839,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_starts': - $result = $this->categoryRepository->categoryStartsWith($value, 1337); + $result = $this->categoryRepository->categoryStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1850,7 +1851,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_starts': - $result = $this->categoryRepository->categoryStartsWith($value, 1337); + $result = $this->categoryRepository->categoryStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1862,7 +1863,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_contains': - $result = $this->categoryRepository->searchCategory($value, 1337); + $result = $this->categoryRepository->searchCategory($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1874,7 +1875,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_contains': - $result = $this->categoryRepository->searchCategory($value, 1337); + $result = $this->categoryRepository->searchCategory($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1885,7 +1886,7 @@ class OperatorQuerySearch implements SearchInterface break; - // budgets + // budgets case '-has_any_budget': case 'has_no_budget': @@ -1900,7 +1901,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_contains': - $result = $this->budgetRepository->searchBudget($value, 1337); + $result = $this->budgetRepository->searchBudget($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1912,7 +1913,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_contains': - $result = $this->budgetRepository->searchBudget($value, 1337); + $result = $this->budgetRepository->searchBudget($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1924,7 +1925,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_is': - $budget = $this->budgetRepository->findByName($value); + $budget = $this->budgetRepository->findByName($value); if (null !== $budget) { $this->collector->setBudget($budget); @@ -1936,7 +1937,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_is': - $budget = $this->budgetRepository->findByName($value); + $budget = $this->budgetRepository->findByName($value); if (null !== $budget) { $this->collector->excludeBudget($budget); @@ -1948,7 +1949,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_ends': - $result = $this->budgetRepository->budgetEndsWith($value, 1337); + $result = $this->budgetRepository->budgetEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1960,7 +1961,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_ends': - $result = $this->budgetRepository->budgetEndsWith($value, 1337); + $result = $this->budgetRepository->budgetEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1972,7 +1973,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_starts': - $result = $this->budgetRepository->budgetStartsWith($value, 1337); + $result = $this->budgetRepository->budgetStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1984,7 +1985,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_starts': - $result = $this->budgetRepository->budgetStartsWith($value, 1337); + $result = $this->budgetRepository->budgetStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1995,7 +1996,7 @@ class OperatorQuerySearch implements SearchInterface break; - // bill + // bill case '-has_any_bill': case 'has_no_bill': @@ -2010,7 +2011,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_contains': - $result = $this->billRepository->searchBill($value, 1337); + $result = $this->billRepository->searchBill($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); @@ -2022,7 +2023,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_contains': - $result = $this->billRepository->searchBill($value, 1337); + $result = $this->billRepository->searchBill($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); @@ -2034,7 +2035,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_is': - $bill = $this->billRepository->findByName($value); + $bill = $this->billRepository->findByName($value); if (null !== $bill) { $this->collector->setBill($bill); @@ -2046,7 +2047,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_is': - $bill = $this->billRepository->findByName($value); + $bill = $this->billRepository->findByName($value); if (null !== $bill) { $this->collector->excludeBills(new Collection()->push($bill)); @@ -2058,7 +2059,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_ends': - $result = $this->billRepository->billEndsWith($value, 1337); + $result = $this->billRepository->billEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); } @@ -2070,7 +2071,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_ends': - $result = $this->billRepository->billEndsWith($value, 1337); + $result = $this->billRepository->billEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); } @@ -2082,7 +2083,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_starts': - $result = $this->billRepository->billStartsWith($value, 1337); + $result = $this->billRepository->billStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); } @@ -2094,7 +2095,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_starts': - $result = $this->billRepository->billStartsWith($value, 1337); + $result = $this->billRepository->billStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); } @@ -2105,7 +2106,7 @@ class OperatorQuerySearch implements SearchInterface break; - // tags + // tags case '-has_any_tag': case 'has_no_tag': @@ -2121,10 +2122,10 @@ class OperatorQuerySearch implements SearchInterface case '-tag_is_not': case 'tag_is': - $result = $this->tagRepository->findByTag($value); + $result = $this->tagRepository->findByTag($value); if (null !== $result) { $this->includeTags[] = $result->id; - $this->includeTags = array_unique($this->includeTags); + $this->includeTags = array_unique($this->includeTags); } // no tags found means search must result in nothing. if (null === $result) { @@ -2136,7 +2137,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'tag_contains': - $tags = $this->tagRepository->searchTag($value); + $tags = $this->tagRepository->searchTag($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); @@ -2144,14 +2145,14 @@ class OperatorQuerySearch implements SearchInterface } if ($tags->count() > 0) { // changed from includeTags to includeAnyTags for #8632 - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeAnyTags = array_unique(array_merge($this->includeAnyTags, $ids)); } break; case 'tag_starts': - $tags = $this->tagRepository->tagStartsWith($value); + $tags = $this->tagRepository->tagStartsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); @@ -2159,56 +2160,56 @@ class OperatorQuerySearch implements SearchInterface } if ($tags->count() > 0) { // changed from includeTags to includeAnyTags for #8632 - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeAnyTags = array_unique(array_merge($this->includeAnyTags, $ids)); } break; case '-tag_starts': - $tags = $this->tagRepository->tagStartsWith($value); + $tags = $this->tagRepository->tagStartsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case 'tag_ends': - $tags = $this->tagRepository->tagEndsWith($value); + $tags = $this->tagRepository->tagEndsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case '-tag_ends': - $tags = $this->tagRepository->tagEndsWith($value); + $tags = $this->tagRepository->tagEndsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case '-tag_contains': - $tags = $this->tagRepository->searchTag($value)->keyBy('id'); + $tags = $this->tagRepository->searchTag($value)->keyBy('id'); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); @@ -2216,7 +2217,7 @@ class OperatorQuerySearch implements SearchInterface $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->excludeTags, $ids)); } @@ -2224,15 +2225,15 @@ class OperatorQuerySearch implements SearchInterface case '-tag_is': case 'tag_is_not': - $result = $this->tagRepository->findByTag($value); + $result = $this->tagRepository->findByTag($value); if (null !== $result) { $this->excludeTags[] = $result->id; - $this->excludeTags = array_unique($this->excludeTags); + $this->excludeTags = array_unique($this->excludeTags); } break; - // notes + // notes case 'notes_contains': $this->collector->notesContain($value); @@ -2296,13 +2297,13 @@ class OperatorQuerySearch implements SearchInterface break; - // amount + // amount case 'amount_is': // strip comma's, make dots. Log::debug(sprintf('Original value "%s"', $value)); - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountIs($amount); @@ -2311,8 +2312,8 @@ class OperatorQuerySearch implements SearchInterface case '-amount_is': // strip comma's, make dots. Log::debug(sprintf('Original value "%s"', $value)); - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountIsNot($amount); @@ -2320,9 +2321,9 @@ class OperatorQuerySearch implements SearchInterface case 'foreign_amount_is': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountIs($amount); @@ -2330,9 +2331,9 @@ class OperatorQuerySearch implements SearchInterface case '-foreign_amount_is': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountIsNot($amount); @@ -2341,9 +2342,9 @@ class OperatorQuerySearch implements SearchInterface case '-amount_more': case 'amount_less': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountLess($amount); @@ -2352,9 +2353,9 @@ class OperatorQuerySearch implements SearchInterface case '-foreign_amount_more': case 'foreign_amount_less': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountLess($amount); @@ -2364,8 +2365,8 @@ class OperatorQuerySearch implements SearchInterface case 'amount_more': Log::debug(sprintf('Now handling operator "%s"', $operator)); // strip comma's, make dots. - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountMore($amount); @@ -2375,14 +2376,14 @@ class OperatorQuerySearch implements SearchInterface case 'foreign_amount_more': Log::debug(sprintf('Now handling operator "%s"', $operator)); // strip comma's, make dots. - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountMore($amount); break; - // transaction type + // transaction type case 'transaction_type': $this->collector->setTypes([ucfirst($value)]); @@ -2396,151 +2397,151 @@ class OperatorQuerySearch implements SearchInterface break; - // dates + // dates case '-date_on': case 'date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactDateParams($range, $prohibited); return false; case 'date_before': case '-date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setDateBeforeParams($range); return false; case 'date_after': case '-date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setDateAfterParams($range); return false; case 'interest_date_on': case '-interest_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('interest_date', $range, $prohibited); return false; case 'interest_date_before': case '-interest_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('interest_date', $range); return false; case 'interest_date_after': case '-interest_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('interest_date', $range); return false; case 'book_date_on': case '-book_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('book_date', $range, $prohibited); return false; case 'book_date_before': case '-book_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('book_date', $range); return false; case 'book_date_after': case '-book_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('book_date', $range); return false; case 'process_date_on': case '-process_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('process_date', $range, $prohibited); return false; case 'process_date_before': case '-process_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('process_date', $range); return false; case 'process_date_after': case '-process_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('process_date', $range); return false; case 'due_date_on': case '-due_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('due_date', $range, $prohibited); return false; case 'due_date_before': case '-due_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('due_date', $range); return false; case 'due_date_after': case '-due_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('due_date', $range); return false; case 'payment_date_on': case '-payment_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('payment_date', $range, $prohibited); return false; case 'payment_date_before': case '-payment_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('payment_date', $range); return false; case 'payment_date_after': case '-payment_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('payment_date', $range); return false; case 'invoice_date_on': case '-invoice_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('invoice_date', $range, $prohibited); return false; case 'invoice_date_before': case '-invoice_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('invoice_date', $range); return false; case 'invoice_date_after': case '-invoice_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('invoice_date', $range); return false; @@ -2548,7 +2549,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_on': case '-created_at_on': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactObjectDateParams('created_at', $range, $prohibited); return false; @@ -2556,7 +2557,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_before': case '-created_at_after': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateBeforeParams('created_at', $range); return false; @@ -2564,7 +2565,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_after': case '-created_at_before': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateAfterParams('created_at', $range); return false; @@ -2572,7 +2573,7 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_on': case '-updated_at_on': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactObjectDateParams('updated_at', $range, $prohibited); return false; @@ -2580,7 +2581,7 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_before': case '-updated_at_after': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateBeforeParams('updated_at', $range); return false; @@ -2588,12 +2589,12 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_after': case '-updated_at_before': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateAfterParams('updated_at', $range); return false; - // external URL + // external URL case '-any_external_url': case 'no_external_url': @@ -2659,7 +2660,7 @@ class OperatorQuerySearch implements SearchInterface break; - // other fields + // other fields case 'external_id_is': $this->collector->setExternalId($value); diff --git a/app/Support/Search/QueryParser/NodeResult.php b/app/Support/Search/QueryParser/NodeResult.php index 6b602b9180..75efbb83e4 100644 --- a/app/Support/Search/QueryParser/NodeResult.php +++ b/app/Support/Search/QueryParser/NodeResult.php @@ -33,7 +33,7 @@ namespace FireflyIII\Support\Search\QueryParser; class NodeResult { public function __construct( - public readonly null|Node $node, + public readonly ?Node $node, public readonly bool $isSubqueryEnd ) {} } diff --git a/app/Support/Search/QueryParser/QueryParser.php b/app/Support/Search/QueryParser/QueryParser.php index 54f9efade5..e1bba560e4 100644 --- a/app/Support/Search/QueryParser/QueryParser.php +++ b/app/Support/Search/QueryParser/QueryParser.php @@ -40,7 +40,7 @@ class QueryParser implements QueryParserInterface public function parse(string $query): NodeGroup { Log::debug(sprintf('Parsing query in QueryParser: "%s"', $query)); - $this->query = $query; + $this->query = $query; $this->position = 0; return $this->buildNodeGroup(false); @@ -64,7 +64,7 @@ class QueryParser implements QueryParserInterface if ('\\' === $char && '"' === $nextChar) { // Log::debug('BACKSLASH!'); // escaped quote, pretend it's a normal char and continue two places (skipping the actual character). - $tokenUnderConstruction .= '\\' . $nextChar; + $tokenUnderConstruction .= '\\'.$nextChar; $this->position += 2; continue; @@ -141,7 +141,7 @@ class QueryParser implements QueryParserInterface if ('' === $tokenUnderConstruction) { // In any other location, it's just a normal character $tokenUnderConstruction .= $char; - $skipNext = true; + $skipNext = true; } if ('' !== $tokenUnderConstruction && !$skipNext) { // @phpstan-ignore-line Log::debug(sprintf('Turns out that "%s" is a field name. Reset the token.', $tokenUnderConstruction)); @@ -169,7 +169,7 @@ class QueryParser implements QueryParserInterface ++$this->position; } - $finalNode = '' !== $tokenUnderConstruction || '' !== $fieldName ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) : null; + $finalNode = '' !== $tokenUnderConstruction || '' !== $fieldName ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) : null; return new NodeResult($finalNode, true); } @@ -180,7 +180,7 @@ class QueryParser implements QueryParserInterface $nodeResult = $this->buildNextNode($isSubquery); while ($nodeResult->node instanceof Node) { - $nodes[] = $nodeResult->node; + $nodes[] = $nodeResult->node; if ($nodeResult->isSubqueryEnd) { break; } diff --git a/app/Support/Singleton/PreferencesSingleton.php b/app/Support/Singleton/PreferencesSingleton.php index 72b36e141e..073ed4f50a 100644 --- a/app/Support/Singleton/PreferencesSingleton.php +++ b/app/Support/Singleton/PreferencesSingleton.php @@ -26,9 +26,9 @@ namespace FireflyIII\Support\Singleton; class PreferencesSingleton { - private static null|PreferencesSingleton $instance = null; + private static ?PreferencesSingleton $instance = null; - private array $preferences = []; + private array $preferences = []; private function __construct() { diff --git a/app/Support/Steam.php b/app/Support/Steam.php index 7986e8eba7..5e05ebcde1 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -55,8 +55,8 @@ class Steam public function accountsBalancesOptimized( Collection $accounts, Carbon $date, - null|TransactionCurrency $primary = null, - null|bool $convertToPrimary = null, + ?TransactionCurrency $primary = null, + ?bool $convertToPrimary = null, bool $inclusive = true ): array { Log::debug(sprintf( @@ -65,10 +65,10 @@ class Steam $date->toIso8601String(), var_export($inclusive, true) )); - $result = []; + $result = []; $convertToPrimary ??= Amount::convertToPrimary(); $primary ??= Amount::getPrimaryCurrency(); - $currencies = $this->getCurrencies($accounts); + $currencies = $this->getCurrencies($accounts); // balance(s) in all currencies for ALL accounts. $arrayOfSums = Transaction::whereIn('account_id', $accounts->pluck('id')->toArray()) @@ -77,32 +77,33 @@ class Steam ->where('transaction_journals.date', $inclusive ? '<=' : '<', $date->format('Y-m-d H:i:s')) ->groupBy(['transactions.account_id', 'transaction_currencies.code']) ->get(['transactions.account_id', 'transaction_currencies.code', DB::raw('SUM(transactions.amount) as sum_of_amount')]) - ->toArray(); + ->toArray() + ; Log::debug('Array of sums: ', $arrayOfSums); /** @var Account $account */ foreach ($accounts as $account) { - $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. - $currency = $currencies[$account->id]; + $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. + $currency = $currencies[$account->id]; // second array - $accountSums = array_filter($arrayOfSums, static fn(array $entry): bool => $entry['account_id'] === $account->id); + $accountSums = array_filter($arrayOfSums, static fn (array $entry): bool => $entry['account_id'] === $account->id); if (0 === count($accountSums)) { $result[$account->id] = $return; continue; } - $sumsByCode = []; + $sumsByCode = []; foreach ($accountSums as $accountSum) { // $accountSum = array_values($accountSum)[0]; - $sumOfAmount = (string) $accountSum['sum_of_amount']; - $sumOfAmount = $this->floatalize('' === $sumOfAmount ? '0' : $sumOfAmount); + $sumOfAmount = (string) $accountSum['sum_of_amount']; + $sumOfAmount = $this->floatalize('' === $sumOfAmount ? '0' : $sumOfAmount); $sumsByCode[$accountSum['code']] = $sumOfAmount; } // Log::debug('All balances are (joined)', $others); // if there is no request to convert, take this as "balance" and "pc_balance". - $return['balance'] = $sumsByCode[$currency->code] ?? '0'; + $return['balance'] = $sumsByCode[$currency->code] ?? '0'; if (!$convertToPrimary) { unset($return['pc_balance']); @@ -117,12 +118,12 @@ class Steam } // either way, the balance is always combined with the virtual balance: - $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); + $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); if ($convertToPrimary) { // the primary currency balance is combined with a converted virtual_balance: - $converter = new ExchangeRateConverter(); - $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); + $converter = new ExchangeRateConverter(); + $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); $return['pc_balance'] = bcadd($pcVirtualBalance, $return['pc_balance']); // Log::debug(sprintf('Primary virtual balance makes the primary total %s', $return['pc_balance'])); @@ -133,7 +134,7 @@ class Steam // Log::debug(sprintf('Virtual balance makes the (primary currency) total %s', $return['balance'])); } - $final = array_merge($return, $sumsByCode); + $final = array_merge($return, $sumsByCode); $result[$account->id] = $final; Log::debug(sprintf('Final balance for account #%d is', $account->id), $final); } @@ -149,19 +150,19 @@ class Steam Collection $accounts, Carbon $start, Carbon $end, - null|TransactionCurrency $primary = null, - null|bool $convertToPrimary = null + ?TransactionCurrency $primary = null, + ?bool $convertToPrimary = null ): array { return [ $this->accountsBalancesOptimized($accounts, $start, $primary, $convertToPrimary, inclusive: false), - $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary) + $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary), ]; } /** * https://stackoverflow.com/questions/1642614/how-to-ceil-floor-and-round-bcmath-numbers */ - public function bcround(null|string $number, int $precision = 0): string + public function bcround(?string $number, int $precision = 0): string { if (null === $number) { return '0'; @@ -177,16 +178,16 @@ class Steam // Log::debug(sprintf('Trying bcround("%s",%d)', $number, $precision)); if (str_contains($number, '.')) { if ('-' !== $number[0]) { - return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision); + return bcadd($number, '0.'.str_repeat('0', $precision).'5', $precision); } - return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision); + return bcsub($number, '0.'.str_repeat('0', $precision).'5', $precision); } return $number; } - public function filterAccountBalance(array $set, Account $account, bool $convertToPrimary, null|TransactionCurrency $currency = null): array + public function filterAccountBalance(array $set, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array { Log::debug(sprintf('filterAccountBalance(#%d)', $account->id), $set); if (0 === count($set)) { @@ -237,7 +238,7 @@ class Steam return $set; } - public function filterAccountBalances(array $total, Account $account, bool $convertToPrimary, null|TransactionCurrency $currency = null): array + public function filterAccountBalances(array $total, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array { Log::debug(sprintf('filterAccountBalances(#%d)', $account->id)); $return = []; @@ -298,7 +299,7 @@ class Steam "\u{3000}", // ideographic space "\u{FEFF}", // zero width no -break space "\x20", // plain old normal space, - ' ' + ' ', ]; // clear zalgo text @@ -310,27 +311,27 @@ class Steam #[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". + 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) + 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)] + 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, - null|TransactionCurrency $primary = null, - null|bool $convertToPrimary = null, + ?TransactionCurrency $primary = null, + ?bool $convertToPrimary = null, bool $inclusive = true ): array { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($account->id); $cache->addProperty($date); if ($cache->has()) { @@ -346,25 +347,26 @@ class Steam $primary = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } // account balance thing. - $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; + $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; if ($currencyPresent) { $accountCurrency = $account->meta['currency']; } if (!$currencyPresent) { $accountCurrency = $this->getAccountCurrency($account); } - $hasCurrency = null !== $accountCurrency; - $currency = $hasCurrency ? $accountCurrency : $primary; - $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. + $hasCurrency = null !== $accountCurrency; + $currency = $hasCurrency ? $accountCurrency : $primary; + $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. // balance(s) in all currencies. - $array = $account + $array = $account ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') ->where('transaction_journals.date', $inclusive ? '<=' : '<', $date->format('Y-m-d H:i:s')) ->get(['transaction_currencies.code', 'transactions.amount']) - ->toArray(); - $others = $this->groupAndSumTransactions($array, 'code', 'amount'); + ->toArray() + ; + $others = $this->groupAndSumTransactions($array, 'code', 'amount'); Log::debug('All balances are (joined)', $others); // if there is no request to convert, take this as "balance" and "pc_balance". $return['balance'] = $others[$currency->code] ?? '0'; @@ -381,12 +383,12 @@ class Steam } // either way, the balance is always combined with the virtual balance: - $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); + $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); if ($convertToPrimary) { // the primary currency balance is combined with a converted virtual_balance: - $converter = new ExchangeRateConverter(); - $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); + $converter = new ExchangeRateConverter(); + $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); $return['pc_balance'] = bcadd($pcVirtualBalance, $return['pc_balance']); // Log::debug(sprintf('Primary virtual balance makes the primary total %s', $return['pc_balance'])); @@ -397,7 +399,7 @@ class Steam // Log::debug(sprintf('Virtual balance makes the (primary currency) total %s', $return['balance'])); } - $final = array_merge($return, $others); + $final = array_merge($return, $others); Log::debug('Final balance is', $final); $cache->store($final); @@ -415,7 +417,7 @@ class Steam Log::debug(sprintf('called finalAccountBalanceInRange(#%d, %s, %s)', $account->id, $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); // set up cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($account->id); $cache->addProperty('final-balance-in-range'); $cache->addProperty($start); @@ -427,15 +429,15 @@ class Steam // return $cache->get(); } - $balances = []; - $formatted = $start->format('Y-m-d'); + $balances = []; + $formatted = $start->format('Y-m-d'); Log::debug('Get first balance to start.'); // 2025-10-08 replaced finalAccountBalance with accountsBalancesOptimized: - $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); - $startBalance = $this->accountsBalancesOptimized(new Collection()->push($account), $start, $primaryCurrency, $convertToPrimary, false)[$account->id]; - $accountCurrency = $this->getAccountCurrency($account); - $hasCurrency = $accountCurrency instanceof TransactionCurrency; - $currency = $accountCurrency ?? $primaryCurrency; + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); + $startBalance = $this->accountsBalancesOptimized(new Collection()->push($account), $start, $primaryCurrency, $convertToPrimary, false)[$account->id]; + $accountCurrency = $this->getAccountCurrency($account); + $hasCurrency = $accountCurrency instanceof TransactionCurrency; + $currency = $accountCurrency ?? $primaryCurrency; Log::debug(sprintf('Currency is %s', $currency->code)); // set start balances: @@ -447,14 +449,14 @@ class Steam Log::debug(sprintf('Also set start balance in %s', $primaryCurrency->code)); $startBalance[$primaryCurrency->code] ??= '0'; } - $currencies = [$currency->id => $currency, $primaryCurrency->id => $primaryCurrency]; + $currencies = [$currency->id => $currency, $primaryCurrency->id => $primaryCurrency]; $balances[$formatted] = $startBalance; Log::debug('Final start balance: ', $startBalance); // sums up the balance changes per day. Log::debug(sprintf('Date >= %s and <= %s', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); - $set = $account + $set = $account ->transactions() ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transaction_journals.date', '>=', $start->format('Y-m-d H:i:s')) @@ -463,32 +465,33 @@ class Steam ->groupBy('transactions.transaction_currency_id') ->orderBy('transaction_journals.date', 'ASC') ->whereNull('transaction_journals.deleted_at') - ->get(['transaction_journals.date', 'transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) AS sum_of_day')]); // @phpstan-ignore-line + ->get(['transaction_journals.date', 'transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) AS sum_of_day')]) // @phpstan-ignore-line + ; - $currentBalance = $startBalance; - $converter = new ExchangeRateConverter(); + $currentBalance = $startBalance; + $converter = new ExchangeRateConverter(); /** @var Transaction $entry */ foreach ($set as $entry) { // get date object - $carbon = new Carbon($entry->date, $entry->date_tz); - $carbonKey = $carbon->format('Y-m-d'); + $carbon = new Carbon($entry->date, $entry->date_tz); + $carbonKey = $carbon->format('Y-m-d'); // make sure sum is a string: - $sumOfDay = (string) ($entry->sum_of_day ?? '0'); + $sumOfDay = (string) ($entry->sum_of_day ?? '0'); // #10426 make sure sum is not in scientific notation. - $sumOfDay = $this->floatalize($sumOfDay); + $sumOfDay = $this->floatalize($sumOfDay); // find currency of this entry, does not have to exist. $currencies[$entry->transaction_currency_id] ??= Amount::getTransactionCurrencyById($entry->transaction_currency_id); // make sure this $entry has its own $entryCurrency /** @var TransactionCurrency $entryCurrency */ - $entryCurrency = $currencies[$entry->transaction_currency_id]; + $entryCurrency = $currencies[$entry->transaction_currency_id]; Log::debug(sprintf('Processing transaction(s) on moment %s', $carbon->format('Y-m-d H:i:s'))); // add amount to current balance in currency code. - $currentBalance[$entryCurrency->code] ??= '0'; + $currentBalance[$entryCurrency->code] ??= '0'; $currentBalance[$entryCurrency->code] = bcadd($sumOfDay, (string) $currentBalance[$entryCurrency->code]); // if not requested to convert to primary currency, add the amount to "balance", do nothing else. @@ -498,7 +501,7 @@ class Steam // if convert to primary currency add the converted amount to "pc_balance". // if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency. if ($convertToPrimary) { - $pcSumOfDay = $converter->convert($entryCurrency, $primaryCurrency, $carbon, $sumOfDay); + $pcSumOfDay = $converter->convert($entryCurrency, $primaryCurrency, $carbon, $sumOfDay); $currentBalance['pc_balance'] = bcadd((string) ($currentBalance['pc_balance'] ?? '0'), $pcSumOfDay); // if it's the same currency as the entry, also add to balance (see other code). if ($currency->id === $entryCurrency->id) { @@ -506,7 +509,7 @@ class Steam } } // add to final array. - $balances[$carbonKey] = $currentBalance; + $balances[$carbonKey] = $currentBalance; Log::debug(sprintf('Updated entry [%s]', $carbonKey), $currentBalance); } $cache->store($balances); @@ -523,7 +526,7 @@ class Steam */ public function floatalize(string $value): string { - $value = strtoupper($value); + $value = strtoupper($value); if (!str_contains($value, 'E')) { return $value; } @@ -545,10 +548,10 @@ class Steam return number_format((float) $value, 0, '.', ''); } - public function getAccountCurrency(Account $account): null|TransactionCurrency + public function getAccountCurrency(Account $account): ?TransactionCurrency { - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); // return null if not in this list. if (!in_array($type, $list, true)) { @@ -601,16 +604,17 @@ class Steam { $list = []; - $set = auth() + $set = auth() ->user() ->transactions() ->whereIn('transactions.account_id', $accounts) ->groupBy(['transactions.account_id', 'transaction_journals.user_id']) - ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]); // @phpstan-ignore-line + ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]) // @phpstan-ignore-line + ; /** @var Transaction $entry */ foreach ($set as $entry) { - $date = new Carbon($entry->max_date, config('app.timezone')); + $date = new Carbon($entry->max_date, config('app.timezone')); $date->setTimezone(config('app.timezone')); $list[(int) $entry->account_id] = $date; } @@ -628,14 +632,14 @@ class Steam if (null !== $cached) { return $cached; } - $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; + $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; if (is_array($locale)) { $locale = 'equal'; } if ('equal' === $locale) { $locale = $this->getLanguage(); } - $locale = (string) $locale; + $locale = (string) $locale; // Check for Windows to replace the locale correctly. if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) { @@ -688,7 +692,7 @@ class Steam public function getSafeUrl(string $unknownUrl, string $safeUrl): string { // Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); - $returnUrl = $safeUrl; + $returnUrl = $safeUrl; // die('in get safe url'); try { @@ -734,7 +738,7 @@ class Steam return $amount; } - public function opposite(null|string $amount = null): null|string + public function opposite(?string $amount = null): ?string { if (null === $amount) { return null; @@ -807,12 +811,12 @@ class Steam if (null === $preference) { $singleton->setPreference($key, $currency); } - $current = $amount; + $current = $amount; if ($currency->id !== $primary->id) { $current = $converter->convert($currency, $primary, $date, $amount); Log::debug(sprintf('Convert %s %s to %s %s', $currency->code, $amount, $primary->code, $current)); } - $total = bcadd((string) $current, $total); + $total = bcadd((string) $current, $total); } return $total; @@ -820,14 +824,14 @@ class Steam private function getCurrencies(Collection $accounts): array { - $currencies = []; - $accountCurrencies = []; - $accountPreferences = []; - $primary = Amount::getPrimaryCurrency(); + $currencies = []; + $accountCurrencies = []; + $accountPreferences = []; + $primary = Amount::getPrimaryCurrency(); $currencies[$primary->id] = $primary; - $ids = $accounts->pluck('id')->toArray(); - $result = AccountMeta::whereIn('account_id', $ids)->where('name', 'currency_id')->get(); + $ids = $accounts->pluck('id')->toArray(); + $result = AccountMeta::whereIn('account_id', $ids)->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($result as $item) { @@ -837,7 +841,7 @@ class Steam } } // collect those currencies, skip primary because we already have it. - $set = TransactionCurrency::whereIn('id', $accountPreferences)->where('id', '!=', $primary->id)->get(); + $set = TransactionCurrency::whereIn('id', $accountPreferences)->where('id', '!=', $primary->id)->get(); foreach ($set as $item) { $currencies[$item->id] = $item; } @@ -847,7 +851,7 @@ class Steam $accountId = $account->id; $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; if ($currencyPresent) { - $currencyId = $account->meta['currency']->id; + $currencyId = $account->meta['currency']->id; $currencies[$currencyId] ??= $account->meta['currency']; $accountCurrencies[$accountId] = $account->meta['currency']; } @@ -867,7 +871,7 @@ class Steam $return = []; foreach ($array as $item) { - $groupKey = $item[$group] ?? 'unknown'; + $groupKey = $item[$group] ?? 'unknown'; $return[$groupKey] = bcadd($return[$groupKey] ?? '0', (string) $item[$field]); } diff --git a/app/Support/System/IsOldVersion.php b/app/Support/System/IsOldVersion.php index a4c1831f60..2ebbc68e29 100644 --- a/app/Support/System/IsOldVersion.php +++ b/app/Support/System/IsOldVersion.php @@ -44,8 +44,8 @@ trait IsOldVersion return 0; } - $currentDate = Carbon::createFromFormat('!Y-m-d', $currentParts[1]); - $latestDate = Carbon::createFromFormat('!Y-m-d', $latestParts[1]); + $currentDate = Carbon::createFromFormat('!Y-m-d', $currentParts[1]); + $latestDate = Carbon::createFromFormat('!Y-m-d', $latestParts[1]); if ($currentDate->lt($latestDate)) { Log::debug(sprintf('This current version is older, current = %s, latest version %s.', $current, $latest)); diff --git a/app/Support/System/OAuthKeys.php b/app/Support/System/OAuthKeys.php index 3930e2941a..c45ed177e1 100644 --- a/app/Support/System/OAuthKeys.php +++ b/app/Support/System/OAuthKeys.php @@ -65,7 +65,7 @@ class OAuthKeys Log::debug(sprintf('Private key file at "%s" exists? %s', $private, var_export($privateExists, true))); Log::debug(sprintf('Public key file at "%s" exists ? %s', $public, var_export($publicExists, true))); - $result = file_exists($private) && file_exists($public); + $result = file_exists($private) && file_exists($public); Log::debug(sprintf('Method will return %s', var_export($result, true))); return $result; @@ -102,7 +102,7 @@ class OAuthKeys if ('' !== $publicKey) { Log::debug(sprintf('SHA2 hash of public key in DB : %s', hash('sha256', $publicKey))); } - $return = '' !== $privateKey && '' !== $publicKey; + $return = '' !== $privateKey && '' !== $publicKey; Log::debug(sprintf('keysInDatabase will return %s', var_export($return, true))); return $return; @@ -141,8 +141,8 @@ class OAuthKeys return false; } - $private = storage_path('oauth-private.key'); - $public = storage_path('oauth-public.key'); + $private = storage_path('oauth-private.key'); + $public = storage_path('oauth-public.key'); file_put_contents($private, $privateContent); file_put_contents($public, $publicContent); diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.php index d42d2c9abc..edc84fedc8 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -73,7 +73,7 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountByAccount', - static function (AccountModel $account, string $amount, null|bool $coloured = null): string { + static function (AccountModel $account, string $amount, ?bool $coloured = null): string { $coloured ??= true; /** @var AccountRepositoryInterface $accountRepos */ @@ -94,7 +94,7 @@ class AmountFormat extends AbstractExtension // formatAmountByCode return new TwigFunction( 'formatAmountByCode', - static function (string $amount, string $code, null|bool $coloured = null): string { + static function (string $amount, string $code, ?bool $coloured = null): string { $coloured ??= true; try { @@ -118,7 +118,7 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountByCurrency', - static function (TransactionCurrency $currency, string $amount, null|bool $coloured = null): string { + static function (TransactionCurrency $currency, string $amount, ?bool $coloured = null): string { $coloured ??= true; return Amount::formatAnything($currency, $amount, $coloured); @@ -134,9 +134,9 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountBySymbol', - static function (string $amount, null|string $symbol = null, null|int $decimalPlaces = null, null|bool $coloured = null): string { + static function (string $amount, ?string $symbol = null, ?int $decimalPlaces = null, ?bool $coloured = null): string { if (null === $symbol) { - $message = sprintf( + $message = sprintf( 'formatAmountBySymbol("%s", %s, %d, %s) was called without a symbol. Please browse to /flush to clear your cache.', $amount, var_export($symbol, true), @@ -149,8 +149,8 @@ class AmountFormat extends AbstractExtension if (null !== $symbol) { $decimalPlaces ??= 2; $coloured ??= true; - $currency = new TransactionCurrency(); - $currency->symbol = $symbol; + $currency = new TransactionCurrency(); + $currency->symbol = $symbol; $currency->decimal_places = $decimalPlaces; } diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 05576787ca..3d13930dc3 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -67,7 +67,7 @@ class General extends AbstractExtension $this->hasRole(), $this->getRootSearchOperator(), $this->carbonize(), - $this->fireflyIIIConfig() + $this->fireflyIIIConfig(), ]; } @@ -80,7 +80,7 @@ class General extends AbstractExtension return new TwigFunction('activeRoutePartial', static function (): string { $args = func_get_args(); $route = $args[0]; // name of the route. - $name = Route::getCurrentRoute()->getName() ?? ''; + $name = Route::getCurrentRoute()->getName() ?? ''; if (str_contains($name, $route)) { return 'active'; } @@ -99,7 +99,7 @@ class General extends AbstractExtension 'activeRoutePartialObjectType', static function (array $context): string { [, $route, $objectType] = func_get_args(); - $activeObjectType = $context['objectType'] ?? false; + $activeObjectType = $context['objectType'] ?? false; if ($objectType === $activeObjectType && false !== stripos((string) Route::getCurrentRoute()->getName(), (string) $route)) { return 'active'; @@ -134,17 +134,17 @@ class General extends AbstractExtension */ protected function balance(): TwigFilter { - return new TwigFilter('balance', static function (null|Account $account): string { + return new TwigFilter('balance', static function (?Account $account): string { if (!$account instanceof Account) { return '0'; } /** @var Carbon $date */ - $date = now(); + $date = now(); // get the date from the current session. If it's in the future, keep `now()`. /** @var Carbon $session */ - $session = clone session('end', today(config('app.timezone'))->endOfMonth()); + $session = clone session('end', today(config('app.timezone'))->endOfMonth()); if ($session->lt($date)) { $date = $session->copy(); $date->endOfDay(); @@ -152,13 +152,13 @@ class General extends AbstractExtension Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. - $info = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; + $info = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; // $info = Steam::finalAccountBalance($account, $date); $currency = Steam::getAccountCurrency($account); $primary = Amount::getPrimaryCurrency(); $convertToPrimary = Amount::convertToPrimary(); $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $currency ??= $primary; + $currency ??= $primary; $strings = []; foreach ($info as $key => $balance) { if ('balance' === $key) { @@ -191,7 +191,7 @@ class General extends AbstractExtension protected function carbonize(): TwigFunction { - return new TwigFunction('carbonize', static fn(string $date): Carbon => new Carbon($date, config('app.timezone'))); + return new TwigFunction('carbonize', static fn (string $date): Carbon => new Carbon($date, config('app.timezone'))); } /** @@ -214,15 +214,15 @@ class General extends AbstractExtension return new TwigFilter('filesize', static function (int $size): string { // less than one GB, more than one MB if ($size < (1024 * 1024 * 2014) && $size >= (1024 * 1024)) { - return round($size / (1024 * 1024), 2) . ' MB'; + return round($size / (1024 * 1024), 2).' MB'; } // less than one MB if ($size < (1024 * 1024)) { - return round($size / 1024, 2) . ' KB'; + return round($size / 1024, 2).' KB'; } - return $size . ' bytes'; + return $size.' bytes'; }); } @@ -286,7 +286,7 @@ class General extends AbstractExtension return new TwigFunction('menuOpenRoutePartial', static function (): string { $args = func_get_args(); $route = $args[0]; // name of the route. - $name = Route::getCurrentRoute()->getName() ?? ''; + $name = Route::getCurrentRoute()->getName() ?? ''; if (str_contains($name, $route)) { return 'menu-open'; } @@ -304,16 +304,15 @@ class General extends AbstractExtension { return new TwigFilter( 'mimeIcon', - static fn(string $string): string => match ($string) { - 'application/pdf' => 'fa-file-pdf-o', + static fn (string $string): string => match ($string) { + 'application/pdf' => 'fa-file-pdf-o', 'image/webp', 'image/png', 'image/jpeg', 'image/svg+xml', 'image/heic', 'image/heic-sequence', - 'application/vnd.oasis.opendocument.image' - => 'fa-file-image-o', + 'application/vnd.oasis.opendocument.image' => 'fa-file-image-o', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', @@ -326,8 +325,7 @@ class General extends AbstractExtension 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.opendocument.text-web', - 'application/vnd.oasis.opendocument.text-master' - => 'fa-file-word-o', + 'application/vnd.oasis.opendocument.text-master' => 'fa-file-word-o', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', @@ -335,8 +333,7 @@ class General extends AbstractExtension 'application/vnd.sun.xml.calc.template', 'application/vnd.stardivision.calc', 'application/vnd.oasis.opendocument.spreadsheet', - 'application/vnd.oasis.opendocument.spreadsheet-template' - => 'fa-file-excel-o', + 'application/vnd.oasis.opendocument.spreadsheet-template' => 'fa-file-excel-o', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.presentationml.template', @@ -345,21 +342,18 @@ class General extends AbstractExtension 'application/vnd.sun.xml.impress.template', 'application/vnd.stardivision.impress', 'application/vnd.oasis.opendocument.presentation', - 'application/vnd.oasis.opendocument.presentation-template' - => 'fa-file-powerpoint-o', + 'application/vnd.oasis.opendocument.presentation-template' => 'fa-file-powerpoint-o', 'application/vnd.sun.xml.draw', 'application/vnd.sun.xml.draw.template', 'application/vnd.stardivision.draw', - 'application/vnd.oasis.opendocument.chart' - => 'fa-paint-brush', + 'application/vnd.oasis.opendocument.chart' => 'fa-paint-brush', 'application/vnd.oasis.opendocument.graphics', 'application/vnd.oasis.opendocument.graphics-template', 'application/vnd.sun.xml.math', 'application/vnd.stardivision.math', 'application/vnd.oasis.opendocument.formula', - 'application/vnd.oasis.opendocument.database' - => 'fa-calculator', - default => 'fa-file-o' + 'application/vnd.oasis.opendocument.database' => 'fa-calculator', + default => 'fa-file-o' }, ['is_safe' => ['html']] ); @@ -394,6 +388,6 @@ class General extends AbstractExtension private function fireflyIIIConfig() { - return new TwigFunction('fireflyiiiconfig', static fn(string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data); + return new TwigFunction('fireflyiiiconfig', static fn (string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data); } } diff --git a/app/Support/Twig/Rule.php b/app/Support/Twig/Rule.php index 5c610264e3..2842a2510d 100644 --- a/app/Support/Twig/Rule.php +++ b/app/Support/Twig/Rule.php @@ -40,7 +40,7 @@ class Rule extends AbstractExtension $ruleActions = array_keys(Config::get('firefly.rule-actions')); $possibleActions = []; foreach ($ruleActions as $key) { - $possibleActions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice'); + $possibleActions[$key] = (string) trans('firefly.rule_action_'.$key.'_choice'); } unset($ruleActions); asort($possibleActions); @@ -51,10 +51,10 @@ class Rule extends AbstractExtension public function allJournalTriggers(): TwigFunction { - return new TwigFunction('allJournalTriggers', static fn(): array => [ + return new TwigFunction('allJournalTriggers', 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') + 'manual-activation' => (string) trans('firefly.rule_trigger_manual'), ]); } @@ -65,7 +65,7 @@ class Rule extends AbstractExtension $possibleTriggers = []; foreach ($ruleTriggers as $key) { if ('user_action' !== $key) { - $possibleTriggers[$key] = (string) trans('firefly.rule_trigger_' . $key . '_choice'); + $possibleTriggers[$key] = (string) trans('firefly.rule_trigger_'.$key.'_choice'); } } unset($ruleTriggers); diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index 877b2ae404..c9da254942 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -80,7 +80,8 @@ class TransactionGroupTwig extends AbstractExtension ->where('name', $metaField) ->where('transaction_journal_id', $journalId) ->whereNull('deleted_at') - ->first(); + ->first() + ; if (null === $entry) { return today(config('app.timezone')); } @@ -97,7 +98,8 @@ class TransactionGroupTwig extends AbstractExtension ->where('name', $metaField) ->where('transaction_journal_id', $journalId) ->whereNull('deleted_at') - ->first(); + ->first() + ; if (null === $entry) { return ''; } @@ -113,7 +115,8 @@ class TransactionGroupTwig extends AbstractExtension ->where('name', $metaField) ->where('transaction_journal_id', $journalId) ->whereNull('deleted_at') - ->count(); + ->count() + ; return 1 === $count; }); @@ -145,9 +148,9 @@ class TransactionGroupTwig extends AbstractExtension */ private function foreignJournalArrayAmount(array $array): string { - $type = $array['transaction_type_type'] ?? TransactionTypeEnum::WITHDRAWAL->value; - $amount = $array['foreign_amount'] ?? '0'; - $colored = true; + $type = $array['transaction_type_type'] ?? TransactionTypeEnum::WITHDRAWAL->value; + $amount = $array['foreign_amount'] ?? '0'; + $colored = true; $sourceType = $array['source_account_type'] ?? 'invalid'; $amount = $this->signAmount($amount, $type, $sourceType); @@ -155,7 +158,7 @@ class TransactionGroupTwig extends AbstractExtension if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($array['foreign_currency_symbol'], (int) $array['foreign_currency_decimal_places'], $amount, $colored); + $result = Amount::formatFlat($array['foreign_currency_symbol'], (int) $array['foreign_currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -168,7 +171,7 @@ class TransactionGroupTwig extends AbstractExtension */ private function foreignJournalObjectAmount(TransactionJournal $journal): string { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; /** @var Transaction $first */ $first = $journal->transactions()->where('amount', '<', 0)->first(); @@ -177,12 +180,12 @@ class TransactionGroupTwig extends AbstractExtension $colored = true; $sourceType = $first->account->accountType()->first()->type; - $amount = $this->signAmount($amount, $type, $sourceType); + $amount = $this->signAmount($amount, $type, $sourceType); if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); + $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -213,7 +216,7 @@ class TransactionGroupTwig extends AbstractExtension $colored = false; } - $result = Amount::formatFlat($array['currency_symbol'], (int) $array['currency_decimal_places'], $amount, $colored); + $result = Amount::formatFlat($array['currency_symbol'], (int) $array['currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -226,7 +229,7 @@ class TransactionGroupTwig extends AbstractExtension */ private function normalJournalObjectAmount(TransactionJournal $journal): string { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; /** @var Transaction $first */ $first = $journal->transactions()->where('amount', '<', 0)->first(); @@ -235,12 +238,12 @@ class TransactionGroupTwig extends AbstractExtension $colored = true; $sourceType = $first->account->accountType()->first()->type; - $amount = $this->signAmount($amount, $type, $sourceType); + $amount = $this->signAmount($amount, $type, $sourceType); if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); + $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } diff --git a/app/Support/Twig/Translation.php b/app/Support/Twig/Translation.php index de3630a7b5..cbf621a514 100644 --- a/app/Support/Twig/Translation.php +++ b/app/Support/Twig/Translation.php @@ -37,7 +37,7 @@ class Translation extends AbstractExtension #[Override] public function getFilters(): array { - return [new TwigFilter('_', static fn(string $name) => (string) trans(sprintf('firefly.%s', $name)), ['is_safe' => ['html']])]; + return [new TwigFilter('_', static fn (string $name) => (string) trans(sprintf('firefly.%s', $name)), ['is_safe' => ['html']])]; } #[Override] diff --git a/app/TransactionRules/Actions/AddTag.php b/app/TransactionRules/Actions/AddTag.php index c3e895df59..d0de2e9370 100644 --- a/app/TransactionRules/Actions/AddTag.php +++ b/app/TransactionRules/Actions/AddTag.php @@ -52,12 +52,12 @@ class AddTag implements ActionInterface $factory = app(TagFactory::class); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); $factory->setUser($user); $tagName = $this->action->getValue($journal); $tag = $factory->findOrCreate($tagName); - $type = $journal['transaction_type_type']; + $type = $journal['transaction_type_type']; if ( TransactionTypeEnum::OPENING_BALANCE->value === $type || TransactionTypeEnum::LIABILITY_CREDIT->value === $type @@ -75,15 +75,16 @@ class AddTag implements ActionInterface return false; } - $count = DB::table('tag_transaction_journal') + $count = DB::table('tag_transaction_journal') ->where('tag_id', $tag->id) ->where('transaction_journal_id', $journal['transaction_journal_id']) - ->count(); + ->count() + ; if (0 === $count) { // add to journal: DB::table('tag_transaction_journal')->insert([ 'tag_id' => $tag->id, - 'transaction_journal_id' => $journal['transaction_journal_id'] + 'transaction_journal_id' => $journal['transaction_journal_id'], ]); Log::debug(sprintf('RuleAction AddTag. Added tag #%d ("%s") to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); diff --git a/app/TransactionRules/Actions/AppendDescription.php b/app/TransactionRules/Actions/AppendDescription.php index ff9b687fc1..ea7327e6f2 100644 --- a/app/TransactionRules/Actions/AppendDescription.php +++ b/app/TransactionRules/Actions/AppendDescription.php @@ -52,11 +52,12 @@ class AppendDescription implements ActionInterface DB::table('transaction_journals') ->where('id', $journal['transaction_journal_id']) ->limit(1) - ->update(['description' => $description]); + ->update(['description' => $description]) + ; // event for audit log entry /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $journal['description'], $description)); return true; diff --git a/app/TransactionRules/Actions/AppendDescriptionToNotes.php b/app/TransactionRules/Actions/AppendDescriptionToNotes.php index 8c5c4ba067..4108dbefef 100644 --- a/app/TransactionRules/Actions/AppendDescriptionToNotes.php +++ b/app/TransactionRules/Actions/AppendDescriptionToNotes.php @@ -59,9 +59,9 @@ class AppendDescriptionToNotes implements ActionInterface return false; } - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } @@ -72,7 +72,7 @@ class AppendDescriptionToNotes implements ActionInterface if ('' === $note->text) { $note->text = (string) $object->description; } - $after = $note->text; + $after = $note->text; // event for audit log entry event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $after)); diff --git a/app/TransactionRules/Actions/AppendNotes.php b/app/TransactionRules/Actions/AppendNotes.php index ab79871136..32cdb3f385 100644 --- a/app/TransactionRules/Actions/AppendNotes.php +++ b/app/TransactionRules/Actions/AppendNotes.php @@ -48,21 +48,21 @@ class AppendNotes implements ActionInterface public function actOnArray(array $journal): bool { $this->refreshNotes($journal); - $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); + $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = (int) $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $before = $dbNote->text; - $append = $this->action->getValue($journal); - $text = sprintf('%s%s', $dbNote->text, $append); + $before = $dbNote->text; + $append = $this->action->getValue($journal); + $text = sprintf('%s%s', $dbNote->text, $append); $dbNote->text = $text; $dbNote->save(); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); Log::debug(sprintf('RuleAction AppendNotes appended "%s" to "%s".', $append, $before)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $text)); diff --git a/app/TransactionRules/Actions/AppendNotesToDescription.php b/app/TransactionRules/Actions/AppendNotesToDescription.php index e9ced2573e..a3d1a211e0 100644 --- a/app/TransactionRules/Actions/AppendNotesToDescription.php +++ b/app/TransactionRules/Actions/AppendNotesToDescription.php @@ -62,16 +62,16 @@ class AppendNotesToDescription implements ActionInterface return false; } - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { Log::debug('Journal has no notes.'); - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } // only append if there is something to append if ('' !== $note->text) { - $before = $object->description; + $before = $object->description; $object->description = trim(sprintf('%s %s', $object->description, (string) $this->clearString($note->text))); $object->save(); Log::debug(sprintf('Journal description is updated to "%s".', $object->description)); diff --git a/app/TransactionRules/Actions/ClearNotes.php b/app/TransactionRules/Actions/ClearNotes.php index c710a60fa0..7a68a74f50 100644 --- a/app/TransactionRules/Actions/ClearNotes.php +++ b/app/TransactionRules/Actions/ClearNotes.php @@ -49,7 +49,7 @@ class ClearNotes implements ActionInterface $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); /** @var null|Note $notes */ - $notes = $object->notes()->first(); + $notes = $object->notes()->first(); if (null === $notes) { 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'))); @@ -61,7 +61,8 @@ class ClearNotes implements ActionInterface DB::table('notes') ->where('noteable_id', $journal['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) - ->delete(); + ->delete() + ; 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 842ccc4744..0c8103bb75 100644 --- a/app/TransactionRules/Actions/ConvertToDeposit.php +++ b/app/TransactionRules/Actions/ConvertToDeposit.php @@ -57,14 +57,14 @@ class ConvertToDeposit implements ActionInterface // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { 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'))); @@ -73,7 +73,7 @@ class ConvertToDeposit implements ActionInterface } Log::debug(sprintf('Convert journal #%d to deposit.', $journal['transaction_journal_id'])); - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value === $type) { 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'))); @@ -143,22 +143,22 @@ class ConvertToDeposit implements ActionInterface */ private function convertWithdrawalArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; // find or create revenue account. /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $destAccount = $this->getDestinationAccount($journal); - $sourceAccount = $this->getSourceAccount($journal); + $destAccount = $this->getDestinationAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); // get the action value, or use the original destination name in case the action value is empty: // this becomes a new or existing (revenue) account, which is the source of the new deposit. - $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.source.Deposit'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -172,16 +172,18 @@ class ConvertToDeposit implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposingAccount->id]); + ->update(['account_id' => $opposingAccount->id]) + ; // update the destination transaction and put in the original source account ID. DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $sourceAccount->id]); + ->update(['account_id' => $sourceAccount->id]) + ; // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); @@ -227,21 +229,21 @@ class ConvertToDeposit implements ActionInterface */ private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; // find or create revenue account. /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $sourceAccount = $this->getSourceAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (revenue) account, which is the source of the new deposit. - $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.source.Deposit'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -255,10 +257,11 @@ class ConvertToDeposit implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposingAccount->id]); + ->update(['account_id' => $opposingAccount->id]) + ; // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); diff --git a/app/TransactionRules/Actions/ConvertToTransfer.php b/app/TransactionRules/Actions/ConvertToTransfer.php index eaed32b9a2..f73936cc95 100644 --- a/app/TransactionRules/Actions/ConvertToTransfer.php +++ b/app/TransactionRules/Actions/ConvertToTransfer.php @@ -58,18 +58,18 @@ class ConvertToTransfer implements ActionInterface */ public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { 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'))); @@ -77,9 +77,9 @@ class ConvertToTransfer implements ActionInterface return false; } - $type = $object->transactionType->type; - $user = $object->user; - $journalId = $object->id; + $type = $object->transactionType->type; + $user = $object->user; + $journalId = $object->id; if (TransactionTypeEnum::TRANSFER->value === $type) { 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'))); @@ -94,7 +94,7 @@ class ConvertToTransfer implements ActionInterface // find the asset account in the action value. /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); $expectedType = null; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { @@ -107,7 +107,7 @@ class ConvertToTransfer implements ActionInterface // Deposit? Replace source with account with same type as destination. } - $opposing = $repository->findByName($accountName, [$expectedType]); + $opposing = $repository->findByName($accountName, [$expectedType]); if (null === $opposing) { Log::error(sprintf( @@ -210,14 +210,14 @@ class ConvertToTransfer implements ActionInterface */ private function convertWithdrawalArray(TransactionJournal $journal, Account $opposing): bool { - $repository = app(AccountRepositoryInterface::class); - $sourceAccount = $this->getSourceAccount($journal); + $repository = app(AccountRepositoryInterface::class); + $sourceAccount = $this->getSourceAccount($journal); $repository->setUser($sourceAccount->user); if ($sourceAccount->id === $opposing->id) { 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 + $this->action->rule_id, ])); event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_source_asset', ['name' => $opposing->name]))); @@ -225,30 +225,30 @@ class ConvertToTransfer implements ActionInterface } /** @var Transaction $sourceTransaction */ - $sourceTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '<', 0)->first(); + $sourceTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '<', 0)->first(); /** @var Transaction $destTransaction */ - $destTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '>', 0)->first(); + $destTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '>', 0)->first(); // update destination transaction: $destTransaction->account_id = $opposing->id; $destTransaction->save(); // check if the currencies are a match. /** @var TransactionCurrency $sourceCurrency */ - $sourceCurrency = $repository->getAccountCurrency($sourceAccount); + $sourceCurrency = $repository->getAccountCurrency($sourceAccount); /** @var TransactionCurrency $destCurrency */ - $destCurrency = $repository->getAccountCurrency($opposing); + $destCurrency = $repository->getAccountCurrency($opposing); // if the currencies do not match, need to be smart about the involved amounts: if ($sourceCurrency->id !== $destCurrency->id) { Log::debug(sprintf('Accounts have different currencies. Source has %s, dest has %s', $sourceCurrency->code, $destCurrency->code)); - $foreignAmount = '' === (string) $sourceTransaction->foreign_amount ? $sourceTransaction->amount : $sourceTransaction->foreign_amount; + $foreignAmount = '' === (string) $sourceTransaction->foreign_amount ? $sourceTransaction->amount : $sourceTransaction->foreign_amount; Log::debug(sprintf('Foreign amount: %s', $foreignAmount)); // source transaction: set the foreign currency ID and leave as is. - $sourceTransaction->foreign_currency_id = $destCurrency->id; - $sourceTransaction->foreign_amount = Steam::negative($foreignAmount); + $sourceTransaction->foreign_currency_id = $destCurrency->id; + $sourceTransaction->foreign_amount = Steam::negative($foreignAmount); $sourceTransaction->save(); Log::debug(sprintf( 'Set source transaction #%d foreign currency ID to #%d (amount: %s)', @@ -258,10 +258,10 @@ class ConvertToTransfer implements ActionInterface )); // dest transaction: set reverse amounts and currency IDs from source transaction. - $destTransaction->foreign_currency_id = $sourceCurrency->transaction_currency_id; + $destTransaction->foreign_currency_id = $sourceCurrency->transaction_currency_id; $destTransaction->transaction_currency_id = $sourceTransaction->foreign_currency_id; - $destTransaction->amount = Steam::positive($foreignAmount); - $destTransaction->foreign_amount = Steam::positive($sourceTransaction->amount); + $destTransaction->amount = Steam::positive($foreignAmount); + $destTransaction->foreign_amount = Steam::positive($sourceTransaction->amount); $destTransaction->save(); Log::debug(sprintf( 'Set dest transaction #%d to #%d %s and foreign #%d %s', @@ -274,7 +274,7 @@ class ConvertToTransfer implements ActionInterface } // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); @@ -310,7 +310,7 @@ class ConvertToTransfer implements ActionInterface 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 + $this->action->rule_id, ])); event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_destination_asset', ['name' => $opposing->name]))); @@ -321,10 +321,11 @@ class ConvertToTransfer implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposing->id]); + ->update(['account_id' => $opposing->id]) + ; // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); diff --git a/app/TransactionRules/Actions/ConvertToWithdrawal.php b/app/TransactionRules/Actions/ConvertToWithdrawal.php index 4b7f9f64fc..76dafbafe5 100644 --- a/app/TransactionRules/Actions/ConvertToWithdrawal.php +++ b/app/TransactionRules/Actions/ConvertToWithdrawal.php @@ -57,14 +57,14 @@ class ConvertToWithdrawal implements ActionInterface // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { 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'))); @@ -72,7 +72,7 @@ class ConvertToWithdrawal implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { 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'))); @@ -138,21 +138,21 @@ class ConvertToWithdrawal implements ActionInterface */ private function convertDepositArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $sourceAccount = $this->getSourceAccount($journal); - $destAccount = $this->getDestinationAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); + $destAccount = $this->getDestinationAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (expense) account, which is the destination of the new withdrawal. - $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.destination.Withdrawal'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -166,16 +166,18 @@ class ConvertToWithdrawal implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $destAccount->id]); + ->update(['account_id' => $destAccount->id]) + ; // update destination transaction(s) to be new expense account. DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $opposingAccount->id]); + ->update(['account_id' => $opposingAccount->id]) + ; // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id]); Log::debug('Converted deposit to withdrawal.'); @@ -220,20 +222,20 @@ class ConvertToWithdrawal implements ActionInterface private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool { // find or create expense account. - $user = $journal->user; + $user = $journal->user; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $destAccount = $this->getDestinationAccount($journal); + $destAccount = $this->getDestinationAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (expense) account, which is the destination of the new withdrawal. - $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.destination.Withdrawal'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -247,10 +249,11 @@ class ConvertToWithdrawal implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $opposingAccount->id]); + ->update(['account_id' => $opposingAccount->id]) + ; // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id]); Log::debug('Converted transfer to withdrawal.'); diff --git a/app/TransactionRules/Actions/DeleteTransaction.php b/app/TransactionRules/Actions/DeleteTransaction.php index 5c11333145..b2ea5ef6c3 100644 --- a/app/TransactionRules/Actions/DeleteTransaction.php +++ b/app/TransactionRules/Actions/DeleteTransaction.php @@ -45,7 +45,7 @@ class DeleteTransaction implements ActionInterface public function actOnArray(array $journal): bool { - $count = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $count = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); // destroy entire group. if (1 === $count) { diff --git a/app/TransactionRules/Actions/LinkToBill.php b/app/TransactionRules/Actions/LinkToBill.php index 0f6b1453cd..81fa51fe95 100644 --- a/app/TransactionRules/Actions/LinkToBill.php +++ b/app/TransactionRules/Actions/LinkToBill.php @@ -48,23 +48,24 @@ class LinkToBill implements ActionInterface public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($user); - $billName = $this->action->getValue($journal); - $bill = $repository->findByName($billName); + $billName = $this->action->getValue($journal); + $bill = $repository->findByName($billName); /** @var TransactionJournal $object */ - $object = TransactionJournal::with('transactionType')->find($journal['transaction_journal_id']); - $type = $object->transactionType->type; + $object = TransactionJournal::with('transactionType')->find($journal['transaction_journal_id']); + $type = $object->transactionType->type; if (null !== $bill && TransactionTypeEnum::WITHDRAWAL->value === $type) { - $count = DB::table('transaction_journals') + $count = DB::table('transaction_journals') ->where('id', '=', $journal['transaction_journal_id']) ->where('bill_id', $bill->id) - ->count(); + ->count() + ; if (0 !== $count) { Log::error(sprintf( 'RuleAction LinkToBill could not set the bill of journal #%d to bill "%s": already set.', diff --git a/app/TransactionRules/Actions/MoveDescriptionToNotes.php b/app/TransactionRules/Actions/MoveDescriptionToNotes.php index cbbf28409f..07fa960342 100644 --- a/app/TransactionRules/Actions/MoveDescriptionToNotes.php +++ b/app/TransactionRules/Actions/MoveDescriptionToNotes.php @@ -47,7 +47,7 @@ class MoveDescriptionToNotes implements ActionInterface public function actOnArray(array $journal): bool { /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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'))); @@ -56,23 +56,23 @@ class MoveDescriptionToNotes implements ActionInterface } /** @var null|Note $note */ - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } $before = $note->text; $beforeDescription = $object->description; if ('' !== $note->text) { - $note->text = trim(sprintf("%s \n%s", $note->text, $object->description)); + $note->text = trim(sprintf("%s \n%s", $note->text, $object->description)); $object->description = '(no description)'; } if ('' === $note->text) { - $note->text = (string) $object->description; + $note->text = (string) $object->description; $object->description = '(no description)'; } - $after = $note->text; + $after = $note->text; event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $beforeDescription, $object->description)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $after)); diff --git a/app/TransactionRules/Actions/MoveNotesToDescription.php b/app/TransactionRules/Actions/MoveNotesToDescription.php index 467af03186..5ecbbec54b 100644 --- a/app/TransactionRules/Actions/MoveNotesToDescription.php +++ b/app/TransactionRules/Actions/MoveNotesToDescription.php @@ -53,14 +53,14 @@ class MoveNotesToDescription implements ActionInterface public function actOnArray(array $journal): bool { /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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(); + $note = $object->notes()->first(); if (null === $note) { event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_notes_to_move'))); @@ -74,8 +74,8 @@ class MoveNotesToDescription implements ActionInterface return false; } - $before = $object->description; - $beforeNote = $note->text; + $before = $object->description; + $beforeNote = $note->text; $object->description = (string) $this->clearString($note->text); $object->save(); $note->delete(); diff --git a/app/TransactionRules/Actions/PrependDescription.php b/app/TransactionRules/Actions/PrependDescription.php index 18657957ef..92f2492838 100644 --- a/app/TransactionRules/Actions/PrependDescription.php +++ b/app/TransactionRules/Actions/PrependDescription.php @@ -48,7 +48,8 @@ class PrependDescription implements ActionInterface DB::table('transaction_journals') ->where('id', $journal['transaction_journal_id']) ->limit(1) - ->update(['description' => $after]); + ->update(['description' => $after]) + ; // journal /** @var TransactionJournal $object */ diff --git a/app/TransactionRules/Actions/PrependNotes.php b/app/TransactionRules/Actions/PrependNotes.php index 67ce2b4fc7..00605ba954 100644 --- a/app/TransactionRules/Actions/PrependNotes.php +++ b/app/TransactionRules/Actions/PrependNotes.php @@ -44,23 +44,23 @@ class PrependNotes implements ActionInterface public function actOnArray(array $journal): bool { - $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); + $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = (int) $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $before = $dbNote->text; - $after = $this->action->getValue($journal); + $before = $dbNote->text; + $after = $this->action->getValue($journal); Log::debug(sprintf('RuleAction PrependNotes prepended "%s" to "%s".', $after, $dbNote->text)); - $text = sprintf('%s%s', $after, $dbNote->text); + $text = sprintf('%s%s', $after, $dbNote->text); $dbNote->text = $text; $dbNote->save(); // journal /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); // audit log event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $text)); diff --git a/app/TransactionRules/Actions/RemoveAllTags.php b/app/TransactionRules/Actions/RemoveAllTags.php index 6b25422593..d71ed16877 100644 --- a/app/TransactionRules/Actions/RemoveAllTags.php +++ b/app/TransactionRules/Actions/RemoveAllTags.php @@ -45,7 +45,7 @@ class RemoveAllTags implements ActionInterface public function actOnArray(array $journal): bool { 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(); + $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->count(); if (0 === $count) { 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'))); diff --git a/app/TransactionRules/Actions/RemoveTag.php b/app/TransactionRules/Actions/RemoveTag.php index 5fcb9cd13f..f88e68cded 100644 --- a/app/TransactionRules/Actions/RemoveTag.php +++ b/app/TransactionRules/Actions/RemoveTag.php @@ -45,11 +45,11 @@ class RemoveTag implements ActionInterface public function actOnArray(array $journal): bool { - $name = $this->action->getValue($journal); + $name = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); - $tag = $user->tags()->where('tag', $name)->first(); + $user = User::find($journal['user_id']); + $tag = $user->tags()->where('tag', $name)->first(); // if tag does not exist, no need to continue: if (null === $tag) { @@ -62,10 +62,11 @@ class RemoveTag implements ActionInterface return false; } - $count = DB::table('tag_transaction_journal') + $count = DB::table('tag_transaction_journal') ->where('transaction_journal_id', $journal['transaction_journal_id']) ->where('tag_id', $tag->id) - ->count(); + ->count() + ; if (0 === $count) { Log::debug(sprintf( 'RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag is linked.', @@ -81,7 +82,8 @@ class RemoveTag implements ActionInterface DB::table('tag_transaction_journal') ->where('transaction_journal_id', $journal['transaction_journal_id']) ->where('tag_id', $tag->id) - ->delete(); + ->delete() + ; /** @var TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); diff --git a/app/TransactionRules/Actions/SetAmount.php b/app/TransactionRules/Actions/SetAmount.php index 1968c185c3..26ba8c4443 100644 --- a/app/TransactionRules/Actions/SetAmount.php +++ b/app/TransactionRules/Actions/SetAmount.php @@ -57,7 +57,7 @@ class SetAmount implements ActionInterface return false; } - $value = $this->action->getValue($journal); + $value = $this->action->getValue($journal); if (!is_numeric($value) || 0 === bccomp($value, '0')) { Log::debug(sprintf('RuleAction SetAmount, amount "%s" is not a number or is zero, will not continue.', $value)); @@ -67,10 +67,10 @@ class SetAmount implements ActionInterface } /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); - $positive = Steam::positive($value); - $negative = Steam::negative($value); + $positive = Steam::positive($value); + $negative = Steam::negative($value); $this->updatePositive($object, $positive); $this->updateNegative($object, $negative); @@ -86,12 +86,12 @@ class SetAmount implements ActionInterface [ 'currency_symbol' => $object->transactionCurrency->symbol, 'decimal_places' => $object->transactionCurrency->decimal_places, - 'amount' => $journal['amount'] + 'amount' => $journal['amount'], ], [ 'currency_symbol' => $object->transactionCurrency->symbol, 'decimal_places' => $object->transactionCurrency->decimal_places, - 'amount' => $value + 'amount' => $value, ] ) ); diff --git a/app/TransactionRules/Actions/SetBudget.php b/app/TransactionRules/Actions/SetBudget.php index 920e57734e..e040619d6d 100644 --- a/app/TransactionRules/Actions/SetBudget.php +++ b/app/TransactionRules/Actions/SetBudget.php @@ -47,10 +47,10 @@ class SetBudget implements ActionInterface public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); - $search = $this->action->getValue($journal); + $user = User::find($journal['user_id']); + $search = $this->action->getValue($journal); - $budget = $user->budgets()->where('name', $search)->first(); + $budget = $user->budgets()->where('name', $search)->first(); if (null === $budget) { Log::debug(sprintf( 'RuleAction SetBudget could not set budget of journal #%d to "%s" because no such budget exists.', @@ -71,7 +71,7 @@ class SetBudget implements ActionInterface )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_set_budget', [ 'type' => $journal['transaction_type_type'], - 'name' => $search + 'name' => $search, ]))); return false; @@ -98,11 +98,11 @@ class SetBudget implements ActionInterface DB::table('budget_transaction_journal')->where('transaction_journal_id', '=', $journal['transaction_journal_id'])->delete(); DB::table('budget_transaction_journal')->insert([ 'transaction_journal_id' => $journal['transaction_journal_id'], - 'budget_id' => $budget->id + 'budget_id' => $budget->id, ]); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'set_budget', $oldBudgetName, $budget->name)); return true; diff --git a/app/TransactionRules/Actions/SetCategory.php b/app/TransactionRules/Actions/SetCategory.php index b709829bde..3673bc962b 100644 --- a/app/TransactionRules/Actions/SetCategory.php +++ b/app/TransactionRules/Actions/SetCategory.php @@ -47,8 +47,8 @@ class SetCategory implements ActionInterface public function actOnArray(array $journal): bool { /** @var null|User $user */ - $user = User::find($journal['user_id']); - $search = $this->action->getValue($journal); + $user = User::find($journal['user_id']); + $search = $this->action->getValue($journal); if (null === $user) { 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'))); @@ -57,9 +57,9 @@ class SetCategory implements ActionInterface } /** @var CategoryFactory $factory */ - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser($user); - $category = $factory->findOrCreate(null, $search); + $category = $factory->findOrCreate(null, $search); if (null === $category) { Log::debug(sprintf( 'RuleAction SetCategory could not set category of journal #%d to "%s" because no such category exists.', @@ -92,11 +92,11 @@ class SetCategory implements ActionInterface DB::table('category_transaction_journal')->where('transaction_journal_id', '=', $journal['transaction_journal_id'])->delete(); DB::table('category_transaction_journal')->insert([ 'transaction_journal_id' => $journal['transaction_journal_id'], - 'category_id' => $category->id + 'category_id' => $category->id, ]); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'set_category', $oldCategoryName, $category->name)); return true; diff --git a/app/TransactionRules/Actions/SetDescription.php b/app/TransactionRules/Actions/SetDescription.php index c8b852bdda..9c2f5f2124 100644 --- a/app/TransactionRules/Actions/SetDescription.php +++ b/app/TransactionRules/Actions/SetDescription.php @@ -54,7 +54,7 @@ class SetDescription implements ActionInterface $after = $this->action->getValue($journal); // replace newlines. - $after = trim(str_replace(["\r", "\n", "\t", "\036", "\025"], '', $after)); + $after = trim(str_replace(["\r", "\n", "\t", "\036", "\025"], '', $after)); if ('' === $after) { Log::warning('Action resulted in an empty description, reset to default value.'); diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index 7c060935c9..14704cdf67 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -51,13 +51,13 @@ class SetDestinationAccount implements ActionInterface public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { @@ -66,11 +66,11 @@ class SetDestinationAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; $this->repository->setUser($user); // 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); + $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::DEPOSIT->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { Log::error(sprintf('Cant change destination 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,7 +80,7 @@ class SetDestinationAccount implements ActionInterface // new destination account must be different from the current source account: /** @var null|Transaction $source */ - $source = $object->transactions()->where('amount', '<', 0)->first(); + $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); @@ -127,14 +127,15 @@ class SetDestinationAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '>', 0) - ->update(['account_id' => $newAccount->id]); + ->update(['account_id' => $newAccount->id]) + ; Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); return true; } - private function findAssetAccount(string $type, string $accountName): null|Account + private function findAssetAccount(string $type, string $accountName): ?Account { // switch on type: $allowed = config(sprintf('firefly.expected_source_types.destination.%s', $type)); @@ -155,7 +156,7 @@ class SetDestinationAccount implements ActionInterface 'account_type_id' => null, 'virtual_balance' => 0, 'active' => true, - 'iban' => null + 'iban' => null, ]; $account = $this->repository->store($data); } diff --git a/app/TransactionRules/Actions/SetDestinationToCashAccount.php b/app/TransactionRules/Actions/SetDestinationToCashAccount.php index e15bd884b7..2c69b6f52a 100644 --- a/app/TransactionRules/Actions/SetDestinationToCashAccount.php +++ b/app/TransactionRules/Actions/SetDestinationToCashAccount.php @@ -50,11 +50,11 @@ class SetDestinationToCashAccount implements ActionInterface public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); - $repository = app(AccountRepositoryInterface::class); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -62,7 +62,7 @@ class SetDestinationToCashAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value !== $type) { Log::error('Transaction must be withdrawal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_withdrawal'))); @@ -76,7 +76,7 @@ class SetDestinationToCashAccount implements ActionInterface // new destination account must be different from the current source account: /** @var null|Transaction $source */ - $source = $object->transactions()->where('amount', '<', 0)->first(); + $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); @@ -108,7 +108,8 @@ class SetDestinationToCashAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '>', 0) - ->update(['account_id' => $cashAccount->id]); + ->update(['account_id' => $cashAccount->id]) + ; Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); diff --git a/app/TransactionRules/Actions/SetNotes.php b/app/TransactionRules/Actions/SetNotes.php index 0b0b5855bf..f6501c3a3b 100644 --- a/app/TransactionRules/Actions/SetNotes.php +++ b/app/TransactionRules/Actions/SetNotes.php @@ -43,15 +43,15 @@ class SetNotes implements ActionInterface public function actOnArray(array $journal): bool { - $dbNote = Note::where('noteable_id', $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(); + $dbNote = Note::where('noteable_id', $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $oldNotes = $dbNote->text; - $newNotes = $this->action->getValue($journal); + $oldNotes = $dbNote->text; + $newNotes = $this->action->getValue($journal); $dbNote->text = $newNotes; $dbNote->save(); @@ -63,7 +63,7 @@ class SetNotes implements ActionInterface )); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $oldNotes, $newNotes)); diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index 148772d0d6..570978b8aa 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -51,13 +51,13 @@ class SetSourceAccount implements ActionInterface public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -65,11 +65,11 @@ class SetSourceAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; $this->repository->setUser($user); // 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); + $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::WITHDRAWAL->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { 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]))); @@ -79,7 +79,7 @@ class SetSourceAccount implements ActionInterface // new source account must be different from the current destination account: /** @var null|Transaction $destination */ - $destination = $object->transactions()->where('amount', '>', 0)->first(); + $destination = $object->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { Log::error('Could not find destination transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction'))); @@ -116,7 +116,8 @@ class SetSourceAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '<', 0) - ->update(['account_id' => $newAccount->id]); + ->update(['account_id' => $newAccount->id]) + ; event(new TriggeredAuditLog($this->action->rule, $object, 'set_source', null, $newAccount->name)); @@ -125,7 +126,7 @@ class SetSourceAccount implements ActionInterface return true; } - private function findAssetAccount(string $type, string $accountName): null|Account + private function findAssetAccount(string $type, string $accountName): ?Account { // switch on type: $allowed = config(sprintf('firefly.expected_source_types.source.%s', $type)); @@ -147,7 +148,7 @@ class SetSourceAccount implements ActionInterface 'account_type_id' => null, 'virtual_balance' => 0, 'active' => true, - 'iban' => null + 'iban' => null, ]; $account = $this->repository->store($data); } diff --git a/app/TransactionRules/Actions/SetSourceToCashAccount.php b/app/TransactionRules/Actions/SetSourceToCashAccount.php index e66d9771b4..3387560d42 100644 --- a/app/TransactionRules/Actions/SetSourceToCashAccount.php +++ b/app/TransactionRules/Actions/SetSourceToCashAccount.php @@ -50,11 +50,11 @@ class SetSourceToCashAccount implements ActionInterface public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); - $repository = app(AccountRepositoryInterface::class); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -62,7 +62,7 @@ class SetSourceToCashAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value !== $type) { Log::error('Transaction must be deposit.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_deposit'))); @@ -108,7 +108,8 @@ class SetSourceToCashAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '<', 0) - ->update(['account_id' => $cashAccount->id]); + ->update(['account_id' => $cashAccount->id]) + ; Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); diff --git a/app/TransactionRules/Actions/SwitchAccounts.php b/app/TransactionRules/Actions/SwitchAccounts.php index 4c75771352..df2c84bc47 100644 --- a/app/TransactionRules/Actions/SwitchAccounts.php +++ b/app/TransactionRules/Actions/SwitchAccounts.php @@ -48,14 +48,14 @@ class SwitchAccounts implements ActionInterface { // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { 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(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { 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'))); @@ -63,7 +63,7 @@ class SwitchAccounts implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::TRANSFER->value !== $type) { Log::error(sprintf( 'Journal #%d is NOT a transfer (rule #%d), cannot switch accounts.', @@ -76,10 +76,10 @@ class SwitchAccounts implements ActionInterface } /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $object->transactions()->where('amount', '<', 0)->first(); + $sourceTransaction = $object->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destTransaction */ - $destTransaction = $object->transactions()->where('amount', '>', 0)->first(); + $destTransaction = $object->transactions()->where('amount', '>', 0)->first(); if (null === $sourceTransaction || null === $destTransaction) { Log::error(sprintf( 'Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', @@ -90,10 +90,10 @@ class SwitchAccounts implements ActionInterface return false; } - $sourceAccountId = $sourceTransaction->account_id; - $destinationAccountId = $destTransaction->account_id; + $sourceAccountId = $sourceTransaction->account_id; + $destinationAccountId = $destTransaction->account_id; $sourceTransaction->account_id = $destinationAccountId; - $destTransaction->account_id = $sourceAccountId; + $destTransaction->account_id = $sourceAccountId; $sourceTransaction->save(); $destTransaction->save(); diff --git a/app/TransactionRules/Actions/UpdatePiggyBank.php b/app/TransactionRules/Actions/UpdatePiggyBank.php index 4a4585db66..a13d30ded4 100644 --- a/app/TransactionRules/Actions/UpdatePiggyBank.php +++ b/app/TransactionRules/Actions/UpdatePiggyBank.php @@ -54,12 +54,12 @@ class UpdatePiggyBank implements ActionInterface // refresh the transaction type. /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var TransactionJournal $journalObj */ - $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); + $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); - $piggyBank = $this->findPiggyBank($user, $actionValue); + $piggyBank = $this->findPiggyBank($user, $actionValue); if (!$piggyBank instanceof PiggyBank) { Log::info(sprintf('No piggy bank named "%s", cant execute action #%d of rule #%d', $actionValue, $this->action->id, $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_piggy', ['name' => $actionValue]))); @@ -86,7 +86,7 @@ class UpdatePiggyBank implements ActionInterface /** @var Transaction $destination */ $destination = $journalObj->transactions()->where('amount', '>', 0)->first(); - $accounts = $this->getAccounts($journalObj); + $accounts = $this->getAccounts($journalObj); Log::debug(sprintf('Source account is #%d: "%s"', $accounts['source']->id, $accounts['source']->name)); Log::debug(sprintf('Destination account is #%d: "%s"', $accounts['destination']->id, $accounts['source']->name)); @@ -98,7 +98,7 @@ class UpdatePiggyBank implements ActionInterface 'currency_symbol' => $journalObj->transactionCurrency->symbol, 'decimal_places' => $journalObj->transactionCurrency->decimal_places, 'amount' => $destination->amount, - 'piggy' => $piggyBank->name + 'piggy' => $piggyBank->name, ])); return true; @@ -114,7 +114,7 @@ class UpdatePiggyBank implements ActionInterface 'decimal_places' => $journalObj->transactionCurrency->decimal_places, 'amount' => $destination->amount, 'piggy' => $piggyBank->name, - 'piggy_id' => $piggyBank->id + 'piggy_id' => $piggyBank->id, ])); return true; @@ -139,7 +139,7 @@ class UpdatePiggyBank implements ActionInterface return false; } - private function findPiggyBank(User $user, string $name): null|PiggyBank + private function findPiggyBank(User $user, string $name): ?PiggyBank { /** @var PiggyBankRepositoryInterface $repository */ $repository = app(PiggyBankRepositoryInterface::class); @@ -152,11 +152,11 @@ class UpdatePiggyBank implements ActionInterface { return [ 'source' => $journal->transactions()->where('amount', '<', '0')->first()?->account, - 'destination' => $journal->transactions()->where('amount', '>', '0')->first()?->account + 'destination' => $journal->transactions()->where('amount', '>', '0')->first()?->account, ]; } - private function isConnected(PiggyBank $piggyBank, null|Account $link): bool + private function isConnected(PiggyBank $piggyBank, ?Account $link): bool { if (!$link instanceof Account) { return false; @@ -179,11 +179,11 @@ class UpdatePiggyBank implements ActionInterface $accountRepository->setUser($account->user); // how much can we remove from this piggy bank? - $toRemove = $repository->getCurrentAmount($piggyBank, $account); + $toRemove = $repository->getCurrentAmount($piggyBank, $account); Log::debug(sprintf('Amount is %s, max to remove is %s', $amount, $toRemove)); // if $amount is bigger than $toRemove, shrink it. - $amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove; + $amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove; Log::debug(sprintf('Amount is now %s', $amount)); // if amount is zero, stop. @@ -199,7 +199,7 @@ class UpdatePiggyBank implements ActionInterface $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency(); event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_remove_from_piggy', [ 'amount' => Amount::formatAnything($amount, $currency, false), - 'name' => $piggyBank->name + 'name' => $piggyBank->name, ]))); return; @@ -218,7 +218,7 @@ class UpdatePiggyBank implements ActionInterface // how much can we add to the piggy bank? if (0 !== bccomp($piggyBank->target_amount, '0')) { - $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account)); + $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account)); Log::debug(sprintf('Max amount to add to piggy bank is %s, amount is %s', $toAdd, $amount)); // update amount to fit: @@ -242,7 +242,7 @@ class UpdatePiggyBank implements ActionInterface $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency(); event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_to_piggy', [ 'amount' => Amount::formatAnything($currency, $amount, false), - 'name' => $piggyBank->name + 'name' => $piggyBank->name, ]))); return; diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php index a9731cc1ce..13b3dac12b 100644 --- a/app/TransactionRules/Engine/SearchRuleEngine.php +++ b/app/TransactionRules/Engine/SearchRuleEngine.php @@ -45,7 +45,7 @@ use Illuminate\Support\Facades\Log; class SearchRuleEngine implements RuleEngineInterface { private readonly Collection $groups; - private array $operators = []; + private array $operators = []; // always collect the triggers from the database, unless indicated otherwise. private bool $refreshTriggers = true; private array $resultCount = []; @@ -54,7 +54,7 @@ class SearchRuleEngine implements RuleEngineInterface public function __construct() { - $this->rules = new Collection(); + $this->rules = new Collection(); $this->groups = new Collection(); } @@ -69,7 +69,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug('SearchRuleEngine::find()'); $collection = new Collection(); foreach ($this->rules as $rule) { - $found = new Collection(); + $found = new Collection(); if (true === $rule->strict) { $found = $this->findStrictRule($rule); } @@ -78,7 +78,7 @@ class SearchRuleEngine implements RuleEngineInterface } $collection = $collection->merge($found); } - $result = $collection->unique(); + $result = $collection->unique(); Log::debug(sprintf('SearchRuleEngine::find() returns %d unique transactions.', $result->count())); return $result; @@ -90,8 +90,8 @@ class SearchRuleEngine implements RuleEngineInterface private function findStrictRule(Rule $rule): Collection { Log::debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0)); - $searchArray = []; - $triggers = []; + $searchArray = []; + $triggers = []; if ($this->refreshTriggers) { $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get(); } @@ -110,7 +110,7 @@ class SearchRuleEngine implements RuleEngineInterface } // if the trigger needs no context, value is different: - $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true); + $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true); if (false === $needsContext) { Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type)); $searchArray[$ruleTrigger->trigger_type][] = 'true'; @@ -126,7 +126,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value'])); $searchArray[$operator['type']][] = sprintf('"%s"', $operator['value']); } - $date = today(config('app.timezone')); + $date = today(config('app.timezone')); if ($this->hasSpecificJournalTrigger($searchArray)) { $date = $this->setDateFromJournalTrigger($searchArray); } @@ -146,7 +146,7 @@ class SearchRuleEngine implements RuleEngineInterface } } - $result = $searchEngine->searchTransactions(); + $result = $searchEngine->searchTransactions(); return $result->getCollection(); } @@ -171,7 +171,7 @@ class SearchRuleEngine implements RuleEngineInterface $dateTrigger = true; } } - $result = $journalTrigger && $dateTrigger; + $result = $journalTrigger && $dateTrigger; Log::debug(sprintf('Result of hasSpecificJournalTrigger is %s.', var_export($result, true))); return $result; @@ -190,7 +190,7 @@ class SearchRuleEngine implements RuleEngineInterface if (0 !== $journalId) { $repository = app(JournalRepositoryInterface::class); $repository->setUser($this->user); - $journal = $repository->find($journalId); + $journal = $repository->find($journalId); if (null !== $journal) { $date = $journal->date; Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d'))); @@ -205,7 +205,7 @@ class SearchRuleEngine implements RuleEngineInterface public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->operators = []; } @@ -272,10 +272,10 @@ class SearchRuleEngine implements RuleEngineInterface $searchEngine->parseQuery(sprintf('%s:%s', $type, $value)); } - $result = $searchEngine->searchTransactions(); - $collection = $result->getCollection(); + $result = $searchEngine->searchTransactions(); + $collection = $result->getCollection(); Log::debug(sprintf('Found in this run, %d transactions', $collection->count())); - $total = $total->merge($collection); + $total = $total->merge($collection); Log::debug(sprintf('Total collection is now %d transactions', $total->count())); ++$count; // if trigger says stop processing, do so. @@ -289,7 +289,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug(sprintf('Done running %d trigger(s)', $count)); // make collection unique - $unique = $total->unique(static function (array $group): string { + $unique = $total->unique(static function (array $group): string { $str = ''; foreach ($group['transactions'] as $transaction) { $str = sprintf('%s%d', $str, $transaction['transaction_journal_id']); @@ -381,7 +381,7 @@ class SearchRuleEngine implements RuleEngineInterface $this->processResults($rule, $collection); - $result = $collection->count() > 0; + $result = $collection->count() > 0; if ($result) { Log::debug(sprintf('SearchRuleEngine:: Done. Rule #%d was triggered (on %d transaction(s)).', $rule->id, $collection->count())); @@ -477,9 +477,10 @@ class SearchRuleEngine implements RuleEngineInterface private function addNotes(array $transaction): array { $transaction['notes'] = ''; - $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) + $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) - ->first(['notes.*']); + ->first(['notes.*']) + ; if (null !== $dbNote) { $transaction['notes'] = $dbNote->text; } @@ -523,7 +524,8 @@ class SearchRuleEngine implements RuleEngineInterface // ->where('rule_triggers.trigger_type', 'user_action') // ->where('rule_triggers.trigger_value', 'store-journal') ->where('rules.active', true) - ->get(['rules.*']); + ->get(['rules.*']) + ; } Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $rules->count())); diff --git a/app/TransactionRules/Expressions/ActionExpression.php b/app/TransactionRules/Expressions/ActionExpression.php index 52ba5242c6..1cf73f613d 100644 --- a/app/TransactionRules/Expressions/ActionExpression.php +++ b/app/TransactionRules/Expressions/ActionExpression.php @@ -81,19 +81,19 @@ class ActionExpression 'due_date', 'process_date', // 'destination_transaction_id', - 'notes' + 'notes', ]; private readonly ExpressionLanguage $expressionLanguage; private readonly bool $isExpression; - private readonly null|SyntaxError $validationError; + private readonly ?SyntaxError $validationError; public function __construct( private readonly string $expr ) { $this->expressionLanguage = app(ExpressionLanguage::class); - $this->isExpression = $this->isExpression($this->expr); - $this->validationError = $this->validate(); + $this->isExpression = $this->isExpression($this->expr); + $this->validationError = $this->validate(); } private function isExpression(string $expr): bool @@ -101,7 +101,7 @@ class ActionExpression return str_starts_with($expr, '=') && strlen($expr) > 1; } - private function validate(): null|SyntaxError + private function validate(): ?SyntaxError { if (!$this->isExpression) { return null; @@ -130,7 +130,7 @@ class ActionExpression $this->expressionLanguage->lint($expr, self::$NAMES); } - public function getValidationError(): null|SyntaxError + public function getValidationError(): ?SyntaxError { return $this->validationError; } diff --git a/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php b/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php index 0974c1faa5..55445e0def 100644 --- a/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php +++ b/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php @@ -39,16 +39,16 @@ class ActionExpressionLanguageProvider implements ExpressionFunctionProviderInte return (string) $str; } - return strtolower($str . '!'); + return strtolower($str.'!'); }; return [ - new ExpressionFunction('constant2', static fn($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str . '!'), $function), - new ExpressionFunction('constant', static fn($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str . '!'), $function), + new ExpressionFunction('constant2', static fn ($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str.'!'), $function), + new ExpressionFunction('constant', static fn ($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str.'!'), $function), ExpressionFunction::fromPhp('substr'), ExpressionFunction::fromPhp('strlen'), - ExpressionFunction::fromPhp('strpos') + ExpressionFunction::fromPhp('strpos'), ]; } } diff --git a/app/TransactionRules/Factory/ActionFactory.php b/app/TransactionRules/Factory/ActionFactory.php index 9a8d21656f..ca5823f478 100644 --- a/app/TransactionRules/Factory/ActionFactory.php +++ b/app/TransactionRules/Factory/ActionFactory.php @@ -65,12 +65,12 @@ class ActionFactory $actionTypes = self::getActionTypes(); if (!array_key_exists($actionType, $actionTypes)) { - throw new FireflyException('No such action exists ("' . e($actionType) . '").'); + throw new FireflyException('No such action exists ("'.e($actionType).'").'); } - $class = $actionTypes[$actionType]; + $class = $actionTypes[$actionType]; if (!class_exists($class)) { - throw new FireflyException('Could not instantiate class for rule action type "' . e($actionType) . '" (' . e($class) . ').'); + throw new FireflyException('Could not instantiate class for rule action type "'.e($actionType).'" ('.e($class).').'); } return $class; diff --git a/app/TransactionRules/Traits/RefreshNotesTrait.php b/app/TransactionRules/Traits/RefreshNotesTrait.php index ca1fe44ca0..5782475a22 100644 --- a/app/TransactionRules/Traits/RefreshNotesTrait.php +++ b/app/TransactionRules/Traits/RefreshNotesTrait.php @@ -33,9 +33,10 @@ trait RefreshNotesTrait final protected function refreshNotes(array $transaction): array { $transaction['notes'] = ''; - $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) + $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) - ->first(['notes.*']); + ->first(['notes.*']) + ; if (null !== $dbNote) { $transaction['notes'] = $dbNote->text; } diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 2f568098cb..535ac867e3 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -45,9 +45,9 @@ class AccountTransformer extends AbstractTransformer */ public function __construct() { - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->convertToPrimary = Amount::convertToPrimary(); - $this->primary = Amount::getPrimaryCurrency(); + $this->primary = Amount::getPrimaryCurrency(); } /** @@ -62,20 +62,20 @@ class AccountTransformer extends AbstractTransformer } // get account type: - $accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $account->full_account_type)); - $liabilityType = (string) config(sprintf('firefly.shortLiabilityNameByFullName.%s', $account->full_account_type)); - $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); - $liabilityDirection = $account->meta['liability_direction'] ?? null; - $accountRole = $this->getAccountRole($account, $accountType); - $hasCurrencySettings = null !== $account->meta['currency']; - $includeNetWorth = 1 === (int) ($account->meta['include_net_worth'] ?? 0); - $longitude = $account->meta['location']['longitude'] ?? null; - $latitude = $account->meta['location']['latitude'] ?? null; - $zoomLevel = $account->meta['location']['zoom_level'] ?? null; - $order = $account->order; + $accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $account->full_account_type)); + $liabilityType = (string) config(sprintf('firefly.shortLiabilityNameByFullName.%s', $account->full_account_type)); + $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); + $liabilityDirection = $account->meta['liability_direction'] ?? null; + $accountRole = $this->getAccountRole($account, $accountType); + $hasCurrencySettings = null !== $account->meta['currency']; + $includeNetWorth = 1 === (int) ($account->meta['include_net_worth'] ?? 0); + $longitude = $account->meta['location']['longitude'] ?? null; + $latitude = $account->meta['location']['latitude'] ?? null; + $zoomLevel = $account->meta['location']['zoom_level'] ?? null; + $order = $account->order; // get primary currency as fallback: - $currency = $this->primary; // assume primary currency + $currency = $this->primary; // assume primary currency if ($hasCurrencySettings) { $currency = $account->meta['currency']; } @@ -87,32 +87,32 @@ class AccountTransformer extends AbstractTransformer // get some listed information from the account meta-data: [$creditCardType, $monthlyPaymentDate] = $this->getCCInfo($account, $accountRole, $accountType); - $openingBalanceDate = $this->getOpeningBalance($account, $accountType); - [$interest, $interestPeriod] = $this->getInterest($account, $accountType); + $openingBalanceDate = $this->getOpeningBalance($account, $accountType); + [$interest, $interestPeriod] = $this->getInterest($account, $accountType); return [ - 'id' => (string) $account->id, - 'created_at' => $account->created_at->toAtomString(), - 'updated_at' => $account->updated_at->toAtomString(), - 'active' => $account->active, - 'order' => $order, - 'name' => $account->name, - 'type' => strtolower($accountType), - 'account_role' => $accountRole, + 'id' => (string) $account->id, + 'created_at' => $account->created_at->toAtomString(), + 'updated_at' => $account->updated_at->toAtomString(), + 'active' => $account->active, + 'order' => $order, + 'name' => $account->name, + 'type' => strtolower($accountType), + 'account_role' => $accountRole, - 'object_group_id' => $account->meta['object_group_id'], - 'object_group_order' => $account->meta['object_group_order'], - 'object_group_title' => $account->meta['object_group_title'], + 'object_group_id' => $account->meta['object_group_id'], + 'object_group_order' => $account->meta['object_group_order'], + 'object_group_title' => $account->meta['object_group_title'], // currency information, structured for 6.3.0. - 'object_has_currency_setting' => $hasCurrencySettings, + 'object_has_currency_setting' => $hasCurrencySettings, // currency is object specific or primary, already determined above. - 'currency_id' => (string) $currency['id'], - 'currency_name' => $currency['name'], - 'currency_code' => $currency['code'], - 'currency_symbol' => $currency['symbol'], - 'currency_decimal_places' => $currency['decimal_places'], + 'currency_id' => (string) $currency['id'], + 'currency_name' => $currency['name'], + 'currency_code' => $currency['code'], + 'currency_symbol' => $currency['symbol'], + 'currency_decimal_places' => $currency['decimal_places'], 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, @@ -121,43 +121,43 @@ class AccountTransformer extends AbstractTransformer 'primary_currency_decimal_places' => $this->primary->decimal_places, // balances, structured for 6.3.0. - 'current_balance' => $account->meta['balances']['current_balance'], - 'pc_current_balance' => $account->meta['balances']['pc_current_balance'], + 'current_balance' => $account->meta['balances']['current_balance'], + 'pc_current_balance' => $account->meta['balances']['pc_current_balance'], - 'opening_balance' => $account->meta['balances']['opening_balance'], - 'pc_opening_balance' => $account->meta['balances']['pc_opening_balance'], + 'opening_balance' => $account->meta['balances']['opening_balance'], + 'pc_opening_balance' => $account->meta['balances']['pc_opening_balance'], - 'virtual_balance' => $account->meta['balances']['virtual_balance'], - 'pc_virtual_balance' => $account->meta['balances']['pc_virtual_balance'], + 'virtual_balance' => $account->meta['balances']['virtual_balance'], + 'pc_virtual_balance' => $account->meta['balances']['pc_virtual_balance'], - 'debt_amount' => $account->meta['balances']['debt_amount'], - 'pc_debt_amount' => $account->meta['balances']['pc_debt_amount'], + 'debt_amount' => $account->meta['balances']['debt_amount'], + 'pc_debt_amount' => $account->meta['balances']['pc_debt_amount'], - 'balance_difference' => $account->meta['balances']['balance_difference'], - 'pc_balance_difference' => $account->meta['balances']['pc_balance_difference'], + 'balance_difference' => $account->meta['balances']['balance_difference'], + 'pc_balance_difference' => $account->meta['balances']['pc_balance_difference'], - 'current_balance_date' => $account->meta['current_balance_date']->toAtomString(), - 'notes' => $account->meta['notes'] ?? null, - 'monthly_payment_date' => $monthlyPaymentDate, - 'credit_card_type' => $creditCardType, - 'account_number' => $account->meta['account_number'], - 'iban' => '' === $account->iban ? null : $account->iban, - 'bic' => $account->meta['BIC'] ?? null, - 'opening_balance_date' => $openingBalanceDate, - 'liability_type' => $liabilityType, - 'liability_direction' => $liabilityDirection, - 'interest' => $interest, - 'interest_period' => $interestPeriod, - 'include_net_worth' => $includeNetWorth, - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel, - 'last_activity' => $account->meta['last_activity']?->toAtomString(), - 'links' => [['rel' => 'self', 'uri' => sprintf('/accounts/%d', $account->id)]] + 'current_balance_date' => $account->meta['current_balance_date']->toAtomString(), + 'notes' => $account->meta['notes'] ?? null, + 'monthly_payment_date' => $monthlyPaymentDate, + 'credit_card_type' => $creditCardType, + 'account_number' => $account->meta['account_number'], + 'iban' => '' === $account->iban ? null : $account->iban, + 'bic' => $account->meta['BIC'] ?? null, + 'opening_balance_date' => $openingBalanceDate, + 'liability_type' => $liabilityType, + 'liability_direction' => $liabilityDirection, + 'interest' => $interest, + 'interest_period' => $interestPeriod, + 'include_net_worth' => $includeNetWorth, + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoom_level' => $zoomLevel, + 'last_activity' => $account->meta['last_activity']?->toAtomString(), + 'links' => [['rel' => 'self', 'uri' => sprintf('/accounts/%d', $account->id)]], ]; } - private function getAccountRole(Account $account, string $accountType): null|string + private function getAccountRole(Account $account, string $accountType): ?string { $accountRole = $account->meta['account_role'] ?? null; if ('asset' !== $accountType || '' === (string) $accountRole) { @@ -167,7 +167,7 @@ class AccountTransformer extends AbstractTransformer return $accountRole; } - private function getCCInfo(Account $account, null|string $accountRole, string $accountType): array + private function getCCInfo(Account $account, ?string $accountRole, string $accountType): array { $monthlyPaymentDate = null; $creditCardType = null; @@ -178,7 +178,7 @@ class AccountTransformer extends AbstractTransformer if (null !== $monthlyPaymentDate) { // try classic date: if (10 === strlen($monthlyPaymentDate)) { - $object = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone')); + $object = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone')); if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } @@ -192,14 +192,14 @@ class AccountTransformer extends AbstractTransformer return [$creditCardType, $monthlyPaymentDate]; } - private function getOpeningBalance(Account $account, string $accountType): null|string + private function getOpeningBalance(Account $account, string $accountType): ?string { $openingBalanceDate = null; if (in_array($accountType, ['asset', 'liabilities'], true)) { $openingBalanceDate = $account->meta['opening_balance_date'] ?? null; } if (null !== $openingBalanceDate) { - $object = Carbon::createFromFormat('Y-m-d H:i:s', $openingBalanceDate, config('app.timezone')); + $object = Carbon::createFromFormat('Y-m-d H:i:s', $openingBalanceDate, config('app.timezone')); if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } diff --git a/app/Transformers/AttachmentTransformer.php b/app/Transformers/AttachmentTransformer.php index 05c7292035..60f74d0652 100644 --- a/app/Transformers/AttachmentTransformer.php +++ b/app/Transformers/AttachmentTransformer.php @@ -63,7 +63,7 @@ class AttachmentTransformer extends AbstractTransformer 'notes' => $this->repository->getNoteText($attachment), 'mime' => $attachment->mime, 'size' => (int) $attachment->size, - 'links' => [['rel' => 'self', 'uri' => '/attachment/' . $attachment->id]] + 'links' => [['rel' => 'self', 'uri' => '/attachment/'.$attachment->id]], ]; } } diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index 5f7ce0d594..955494d1ee 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -42,7 +42,7 @@ class AvailableBudgetTransformer extends AbstractTransformer */ public function __construct() { - $this->primary = Amount::getPrimaryCurrency(); + $this->primary = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -60,17 +60,17 @@ class AvailableBudgetTransformer extends AbstractTransformer } return [ - 'id' => (string) $availableBudget->id, - 'created_at' => $availableBudget->created_at->toAtomString(), - 'updated_at' => $availableBudget->updated_at->toAtomString(), + 'id' => (string) $availableBudget->id, + 'created_at' => $availableBudget->created_at->toAtomString(), + 'updated_at' => $availableBudget->updated_at->toAtomString(), // currencies according to 6.3.0 - 'object_has_currency_setting' => true, - 'currency_id' => (string) $currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, @@ -78,15 +78,15 @@ class AvailableBudgetTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primary->symbol, 'primary_currency_decimal_places' => $this->primary->decimal_places, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'start' => $availableBudget->start_date->toAtomString(), - 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), - 'spent_in_budgets' => $availableBudget->meta['spent_in_budgets'], - 'pc_spent_in_budgets' => $availableBudget->meta['pc_spent_in_budgets'], - 'spent_outside_budgets' => $availableBudget->meta['spent_outside_budgets'], - 'pc_spent_outside_budgets' => $availableBudget->meta['pc_spent_outside_budgets'], - 'links' => [['rel' => 'self', 'uri' => '/available_budgets/' . $availableBudget->id]] + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'start' => $availableBudget->start_date->toAtomString(), + 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), + 'spent_in_budgets' => $availableBudget->meta['spent_in_budgets'], + 'pc_spent_in_budgets' => $availableBudget->meta['pc_spent_in_budgets'], + 'spent_outside_budgets' => $availableBudget->meta['spent_outside_budgets'], + 'pc_spent_outside_budgets' => $availableBudget->meta['pc_spent_outside_budgets'], + 'links' => [['rel' => 'self', 'uri' => '/available_budgets/'.$availableBudget->id]], ]; } } diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index a7fc401cf8..07bdd650ab 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -51,18 +51,18 @@ class BillTransformer extends AbstractTransformer $currency = $bill->transactionCurrency; return [ - 'id' => $bill->id, - 'created_at' => $bill->created_at->toAtomString(), - 'updated_at' => $bill->updated_at->toAtomString(), - 'name' => $bill->name, + 'id' => $bill->id, + 'created_at' => $bill->created_at->toAtomString(), + 'updated_at' => $bill->updated_at->toAtomString(), + 'name' => $bill->name, // currencies according to 6.3.0 - 'object_has_currency_setting' => true, - 'currency_id' => (string) $bill->transaction_currency_id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $bill->transaction_currency_id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, @@ -71,33 +71,33 @@ class BillTransformer extends AbstractTransformer 'primary_currency_decimal_places' => $this->primary->decimal_places, // amounts according to 6.3.0 - 'amount_min' => $bill->amounts['amount_min'], - 'pc_amount_min' => $bill->amounts['pc_amount_min'], + 'amount_min' => $bill->amounts['amount_min'], + 'pc_amount_min' => $bill->amounts['pc_amount_min'], - 'amount_max' => $bill->amounts['amount_max'], - 'pc_amount_max' => $bill->amounts['pc_amount_max'], + 'amount_max' => $bill->amounts['amount_max'], + 'pc_amount_max' => $bill->amounts['pc_amount_max'], - 'amount_avg' => $bill->amounts['average'], - 'pc_amount_avg' => $bill->amounts['pc_average'], + 'amount_avg' => $bill->amounts['average'], + 'pc_amount_avg' => $bill->amounts['pc_average'], - 'date' => $bill->date->toAtomString(), - 'end_date' => $bill->end_date?->toAtomString(), - 'extension_date' => $bill->extension_date?->toAtomString(), - 'repeat_freq' => $bill->repeat_freq, - 'skip' => $bill->skip, - 'active' => $bill->active, - 'order' => $bill->order, - 'notes' => $bill->meta['notes'], - 'object_group_id' => $bill->meta['object_group_id'], - 'object_group_order' => $bill->meta['object_group_order'], - 'object_group_title' => $bill->meta['object_group_title'], + 'date' => $bill->date->toAtomString(), + 'end_date' => $bill->end_date?->toAtomString(), + 'extension_date' => $bill->extension_date?->toAtomString(), + 'repeat_freq' => $bill->repeat_freq, + 'skip' => $bill->skip, + 'active' => $bill->active, + 'order' => $bill->order, + 'notes' => $bill->meta['notes'], + 'object_group_id' => $bill->meta['object_group_id'], + 'object_group_order' => $bill->meta['object_group_order'], + 'object_group_title' => $bill->meta['object_group_title'], - 'paid_dates' => $bill->meta['paid_dates'], - 'pay_dates' => $bill->meta['pay_dates'], - 'next_expected_match' => $bill->meta['nem']?->toAtomString(), - 'next_expected_match_diff' => $bill->meta['nem_diff'], + 'paid_dates' => $bill->meta['paid_dates'], + 'pay_dates' => $bill->meta['pay_dates'], + 'next_expected_match' => $bill->meta['nem']?->toAtomString(), + 'next_expected_match_diff' => $bill->meta['nem_diff'], - 'links' => [['rel' => 'self', 'uri' => '/bills/' . $bill->id]] + 'links' => [['rel' => 'self', 'uri' => '/bills/'.$bill->id]], ]; } } diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index bc642c5a6c..19dc0e7c36 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -42,7 +42,7 @@ class BudgetLimitTransformer extends AbstractTransformer public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -57,7 +57,7 @@ class BudgetLimitTransformer extends AbstractTransformer $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $enrichment->setUser($budget->user); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); return $this->item($budget, new BudgetTransformer(), 'budgets'); } @@ -78,21 +78,21 @@ class BudgetLimitTransformer extends AbstractTransformer } return [ - 'id' => (string) $budgetLimit->id, - 'created_at' => $budgetLimit->created_at->toAtomString(), - 'updated_at' => $budgetLimit->updated_at->toAtomString(), - 'start' => $budgetLimit->start_date->toAtomString(), - 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), - 'budget_id' => (string) $budgetLimit->budget_id, + 'id' => (string) $budgetLimit->id, + 'created_at' => $budgetLimit->created_at->toAtomString(), + 'updated_at' => $budgetLimit->updated_at->toAtomString(), + 'start' => $budgetLimit->start_date->toAtomString(), + 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), + 'budget_id' => (string) $budgetLimit->budget_id, // currency settings according to 6.3.0 - 'object_has_currency_setting' => true, + 'object_has_currency_setting' => true, - 'currency_id' => (string) $currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -100,13 +100,13 @@ class BudgetLimitTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'period' => $budgetLimit->period, - 'spent' => $budgetLimit->meta['spent'], - 'pc_spent' => $budgetLimit->meta['pc_spent'], - 'notes' => $budgetLimit->meta['notes'], - 'links' => [['rel' => 'self', 'uri' => '/budgets/limits/' . $budgetLimit->id]] + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'period' => $budgetLimit->period, + 'spent' => $budgetLimit->meta['spent'], + 'pc_spent' => $budgetLimit->meta['pc_spent'], + 'notes' => $budgetLimit->meta['notes'], + 'links' => [['rel' => 'self', 'uri' => '/budgets/limits/'.$budgetLimit->id]], ]; } } diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index 9b97f6802c..9d7aae3a5b 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -45,13 +45,13 @@ class BudgetTransformer extends AbstractTransformer */ public function __construct() { - $this->parameters = new ParameterBag(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->parameters = new ParameterBag(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); - $this->types = [ + $this->types = [ AutoBudgetType::AUTO_BUDGET_RESET->value => 'reset', AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => 'rollover', - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => 'adjusted' + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => 'adjusted', ]; } @@ -66,7 +66,7 @@ class BudgetTransformer extends AbstractTransformer $abPrimary = null; $abPeriod = null; - $currency = $budget->meta['currency'] ?? null; + $currency = $budget->meta['currency'] ?? null; if (null !== $budget->meta['auto_budget']) { $abType = $this->types[$budget->meta['auto_budget']['type']]; @@ -76,26 +76,26 @@ class BudgetTransformer extends AbstractTransformer } return [ - 'id' => (string) $budget->id, - 'created_at' => $budget->created_at->toAtomString(), - 'updated_at' => $budget->updated_at->toAtomString(), - 'active' => $budget->active, - 'name' => $budget->name, - 'order' => $budget->order, - 'notes' => $budget->meta['notes'], - 'auto_budget_type' => $abType, - 'auto_budget_period' => $abPeriod, - 'object_group_id' => $budget->meta['object_group_id'], - 'object_group_order' => $budget->meta['object_group_order'], - 'object_group_title' => $budget->meta['object_group_title'], + 'id' => (string) $budget->id, + 'created_at' => $budget->created_at->toAtomString(), + 'updated_at' => $budget->updated_at->toAtomString(), + 'active' => $budget->active, + 'name' => $budget->name, + 'order' => $budget->order, + 'notes' => $budget->meta['notes'], + 'auto_budget_type' => $abType, + 'auto_budget_period' => $abPeriod, + 'object_group_id' => $budget->meta['object_group_id'], + 'object_group_order' => $budget->meta['object_group_order'], + 'object_group_title' => $budget->meta['object_group_title'], // new currency settings. - 'object_has_currency_setting' => null !== $budget->meta['currency'], - 'currency_id' => null === $currency ? null : (string) $currency->id, - 'currency_code' => $currency?->code, - 'currency_name' => $currency?->name, - 'currency_symbol' => $currency?->symbol, - 'currency_decimal_places' => $currency?->decimal_places, + 'object_has_currency_setting' => null !== $budget->meta['currency'], + 'currency_id' => null === $currency ? null : (string) $currency->id, + 'currency_code' => $currency?->code, + 'currency_name' => $currency?->name, + 'currency_symbol' => $currency?->symbol, + 'currency_decimal_places' => $currency?->decimal_places, 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -103,11 +103,11 @@ class BudgetTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'auto_budget_amount' => $abAmount, - 'pc_auto_budget_amount' => $abPrimary, - 'spent' => null === $budget->meta['spent'] ? null : $this->beautify($budget->meta['spent']), - 'pc_spent' => null === $budget->meta['pc_spent'] ? null : $this->beautify($budget->meta['pc_spent']), - 'links' => [['rel' => 'self', 'uri' => '/budgets/' . $budget->id]] + 'auto_budget_amount' => $abAmount, + 'pc_auto_budget_amount' => $abPrimary, + 'spent' => null === $budget->meta['spent'] ? null : $this->beautify($budget->meta['spent']), + 'pc_spent' => null === $budget->meta['pc_spent'] ? null : $this->beautify($budget->meta['pc_spent']), + 'links' => [['rel' => 'self', 'uri' => '/budgets/'.$budget->id]], ]; } @@ -116,7 +116,7 @@ class BudgetTransformer extends AbstractTransformer $return = []; foreach ($array as $data) { $data['sum'] = Steam::bcround($data['sum'], (int) $data['currency_decimal_places']); - $return[] = $data; + $return[] = $data; } return $return; diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php index 1bb2a013ec..7e0baff43c 100644 --- a/app/Transformers/CategoryTransformer.php +++ b/app/Transformers/CategoryTransformer.php @@ -50,11 +50,11 @@ class CategoryTransformer extends AbstractTransformer public function transform(Category $category): array { return [ - 'id' => $category->id, - 'created_at' => $category->created_at->toAtomString(), - 'updated_at' => $category->updated_at->toAtomString(), - 'name' => $category->name, - 'notes' => $category->meta['notes'], + 'id' => $category->id, + 'created_at' => $category->created_at->toAtomString(), + 'updated_at' => $category->updated_at->toAtomString(), + 'name' => $category->name, + 'notes' => $category->meta['notes'], // category never has currency settings. 'object_has_currency_setting' => false, @@ -69,11 +69,11 @@ class CategoryTransformer extends AbstractTransformer 'pc_earned' => $this->beautify($category->meta['pc_earned']), 'transferred' => $this->beautify($category->meta['transfers']), 'pc_transferred' => $this->beautify($category->meta['pc_transfers']), - 'links' => [['rel' => 'self', 'uri' => '/categories/' . $category->id]] + 'links' => [['rel' => 'self', 'uri' => '/categories/'.$category->id]], ]; } - private function beautify(null|array $array): null|array + private function beautify(?array $array): ?array { if (null === $array) { return null; @@ -81,7 +81,7 @@ class CategoryTransformer extends AbstractTransformer $return = []; foreach ($array as $data) { $data['sum'] = Steam::bcround($data['sum'], (int) $data['currency_decimal_places']); - $return[] = $data; + $return[] = $data; } return $return; diff --git a/app/Transformers/CurrencyTransformer.php b/app/Transformers/CurrencyTransformer.php index 17bc259da3..190834cdd5 100644 --- a/app/Transformers/CurrencyTransformer.php +++ b/app/Transformers/CurrencyTransformer.php @@ -48,7 +48,7 @@ class CurrencyTransformer extends AbstractTransformer 'code' => $currency->code, 'symbol' => $currency->symbol, 'decimal_places' => $currency->decimal_places, - 'links' => [['rel' => 'self', 'uri' => '/currencies/' . $currency->id]] + 'links' => [['rel' => 'self', 'uri' => '/currencies/'.$currency->id]], ]; } } diff --git a/app/Transformers/ExchangeRateTransformer.php b/app/Transformers/ExchangeRateTransformer.php index f9317d3bc3..84d670d06e 100644 --- a/app/Transformers/ExchangeRateTransformer.php +++ b/app/Transformers/ExchangeRateTransformer.php @@ -42,9 +42,9 @@ class ExchangeRateTransformer extends AbstractTransformer */ public function transform(CurrencyExchangeRate $rate): array { - return ['id' => (string) $rate->id, 'created_at' => $rate->created_at->toAtomString(), 'updated_at' => $rate->updated_at->toAtomString(), + return ['id' => (string) $rate->id, 'created_at' => $rate->created_at->toAtomString(), 'updated_at' => $rate->updated_at->toAtomString(), 'from_currency_id' => (string) $rate->fromCurrency->id, 'from_currency_name' => $rate->fromCurrency->name, 'from_currency_code' => $rate->fromCurrency->code, 'from_currency_symbol' => $rate->fromCurrency->symbol, 'from_currency_decimal_places' => $rate->fromCurrency->decimal_places, - 'to_currency_id' => (string) $rate->toCurrency->id, 'to_currency_name' => $rate->toCurrency->name, 'to_currency_code' => $rate->toCurrency->code, 'to_currency_symbol' => $rate->toCurrency->symbol, 'to_currency_decimal_places' => $rate->toCurrency->decimal_places, - 'rate' => $rate->rate, 'date' => $rate->date->toAtomString(), 'links' => [['rel' => 'self', 'uri' => sprintf('/exchange-rates/%s', $rate->id)]]]; + 'to_currency_id' => (string) $rate->toCurrency->id, 'to_currency_name' => $rate->toCurrency->name, 'to_currency_code' => $rate->toCurrency->code, 'to_currency_symbol' => $rate->toCurrency->symbol, 'to_currency_decimal_places' => $rate->toCurrency->decimal_places, + 'rate' => $rate->rate, 'date' => $rate->date->toAtomString(), 'links' => [['rel' => 'self', 'uri' => sprintf('/exchange-rates/%s', $rate->id)]]]; } } diff --git a/app/Transformers/LinkTypeTransformer.php b/app/Transformers/LinkTypeTransformer.php index b325426a5f..453ce823af 100644 --- a/app/Transformers/LinkTypeTransformer.php +++ b/app/Transformers/LinkTypeTransformer.php @@ -44,7 +44,7 @@ class LinkTypeTransformer extends AbstractTransformer 'inward' => $linkType->inward, 'outward' => $linkType->outward, 'editable' => $linkType->editable, - 'links' => [['rel' => 'self', 'uri' => '/link_types/' . $linkType->id]] + 'links' => [['rel' => 'self', 'uri' => '/link_types/'.$linkType->id]], ]; } } diff --git a/app/Transformers/ObjectGroupTransformer.php b/app/Transformers/ObjectGroupTransformer.php index 86ae348c61..4745f80e75 100644 --- a/app/Transformers/ObjectGroupTransformer.php +++ b/app/Transformers/ObjectGroupTransformer.php @@ -55,7 +55,7 @@ class ObjectGroupTransformer extends AbstractTransformer 'updated_at' => $objectGroup->updated_at?->toAtomString(), 'title' => $objectGroup->title, 'order' => $objectGroup->order, - 'links' => [['rel' => 'self', 'uri' => '/object_groups/' . $objectGroup->id]] + 'links' => [['rel' => 'self', 'uri' => '/object_groups/'.$objectGroup->id]], ]; } } diff --git a/app/Transformers/PiggyBankEventTransformer.php b/app/Transformers/PiggyBankEventTransformer.php index 95c6a4b807..338de7c8a2 100644 --- a/app/Transformers/PiggyBankEventTransformer.php +++ b/app/Transformers/PiggyBankEventTransformer.php @@ -43,7 +43,7 @@ class PiggyBankEventTransformer extends AbstractTransformer */ public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -65,19 +65,19 @@ class PiggyBankEventTransformer extends AbstractTransformer } return [ - 'id' => (string) $event->id, - 'created_at' => $event->created_at?->toAtomString(), - 'updated_at' => $event->updated_at?->toAtomString(), - 'amount' => $amount, - 'pc_amount' => $primaryAmount, + 'id' => (string) $event->id, + 'created_at' => $event->created_at?->toAtomString(), + 'updated_at' => $event->updated_at?->toAtomString(), + 'amount' => $amount, + 'pc_amount' => $primaryAmount, // currencies according to 6.3.0 - 'has_currency_setting' => true, - 'currency_id' => (string) $currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'has_currency_setting' => true, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -85,9 +85,9 @@ class PiggyBankEventTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'transaction_journal_id' => null !== $event->transaction_journal_id ? (string) $event->transaction_journal_id : null, - 'transaction_group_id' => $event->meta['transaction_group_id'], - 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d/events/%s', $event->piggy_bank_id, $event->id)]] + 'transaction_journal_id' => null !== $event->transaction_journal_id ? (string) $event->transaction_journal_id : null, + 'transaction_group_id' => $event->meta['transaction_group_id'], + 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d/events/%s', $event->piggy_bank_id, $event->id)]], ]; } } diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php index cb3ab73d67..d7bfaae68d 100644 --- a/app/Transformers/PiggyBankTransformer.php +++ b/app/Transformers/PiggyBankTransformer.php @@ -57,28 +57,28 @@ class PiggyBankTransformer extends AbstractTransformer $targetDate = $piggyBank->target_date?->toAtomString(); return [ - 'id' => (string) $piggyBank->id, - 'created_at' => $piggyBank->created_at->toAtomString(), - 'updated_at' => $piggyBank->updated_at->toAtomString(), - 'name' => $piggyBank->name, - 'percentage' => $percentage, - 'start_date' => $startDate, - 'target_date' => $targetDate, - 'order' => $piggyBank->order, - 'active' => true, - 'notes' => $piggyBank->meta['notes'], - 'object_group_id' => $piggyBank->meta['object_group_id'], - 'object_group_order' => $piggyBank->meta['object_group_order'], - 'object_group_title' => $piggyBank->meta['object_group_title'], - 'accounts' => $piggyBank->meta['accounts'], + 'id' => (string) $piggyBank->id, + 'created_at' => $piggyBank->created_at->toAtomString(), + 'updated_at' => $piggyBank->updated_at->toAtomString(), + 'name' => $piggyBank->name, + 'percentage' => $percentage, + 'start_date' => $startDate, + 'target_date' => $targetDate, + 'order' => $piggyBank->order, + 'active' => true, + 'notes' => $piggyBank->meta['notes'], + 'object_group_id' => $piggyBank->meta['object_group_id'], + 'object_group_order' => $piggyBank->meta['object_group_order'], + 'object_group_title' => $piggyBank->meta['object_group_title'], + 'accounts' => $piggyBank->meta['accounts'], // currency settings, 6.3.0. - 'object_has_currency_setting' => true, - 'currency_id' => (string) $piggyBank->meta['currency']->id, - 'currency_name' => $piggyBank->meta['currency']->name, - 'currency_code' => $piggyBank->meta['currency']->code, - 'currency_symbol' => $piggyBank->meta['currency']->symbol, - 'currency_decimal_places' => $piggyBank->meta['currency']->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $piggyBank->meta['currency']->id, + 'currency_name' => $piggyBank->meta['currency']->name, + 'currency_code' => $piggyBank->meta['currency']->code, + 'currency_symbol' => $piggyBank->meta['currency']->symbol, + 'currency_decimal_places' => $piggyBank->meta['currency']->decimal_places, 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -86,16 +86,16 @@ class PiggyBankTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => (int) $this->primaryCurrency->decimal_places, - 'target_amount' => $piggyBank->meta['target_amount'], - 'pc_target_amount' => $piggyBank->meta['pc_target_amount'], - 'current_amount' => $piggyBank->meta['current_amount'], - 'pc_current_amount' => $piggyBank->meta['pc_current_amount'], - 'left_to_save' => $piggyBank->meta['left_to_save'], - 'pc_left_to_save' => $piggyBank->meta['pc_left_to_save'], - 'save_per_month' => $piggyBank->meta['save_per_month'], - 'pc_save_per_month' => $piggyBank->meta['pc_save_per_month'], + 'target_amount' => $piggyBank->meta['target_amount'], + 'pc_target_amount' => $piggyBank->meta['pc_target_amount'], + 'current_amount' => $piggyBank->meta['current_amount'], + 'pc_current_amount' => $piggyBank->meta['pc_current_amount'], + 'left_to_save' => $piggyBank->meta['left_to_save'], + 'pc_left_to_save' => $piggyBank->meta['pc_left_to_save'], + 'save_per_month' => $piggyBank->meta['save_per_month'], + 'pc_save_per_month' => $piggyBank->meta['pc_save_per_month'], - 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d', $piggyBank->id)]] + 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d', $piggyBank->id)]], ]; } } diff --git a/app/Transformers/PreferenceTransformer.php b/app/Transformers/PreferenceTransformer.php index 2e9823c423..78dead2380 100644 --- a/app/Transformers/PreferenceTransformer.php +++ b/app/Transformers/PreferenceTransformer.php @@ -44,7 +44,7 @@ class PreferenceTransformer extends AbstractTransformer 'updated_at' => $preference->updated_at->toAtomString(), 'user_group_id' => $userGroupId, 'name' => $preference->name, - 'data' => $preference->data + 'data' => $preference->data, ]; } } diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index 98ed926b02..7b05b0b0e1 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -60,7 +60,7 @@ class RecurrenceTransformer extends AbstractTransformer 'notes' => $recurrence->meta['notes'], 'repetitions' => $recurrence->meta['repetitions'], 'transactions' => $recurrence->meta['transactions'], - 'links' => [['rel' => 'self', 'uri' => '/recurring/' . $recurrence->id]] + 'links' => [['rel' => 'self', 'uri' => '/recurring/'.$recurrence->id]], ]; } } diff --git a/app/Transformers/RuleGroupTransformer.php b/app/Transformers/RuleGroupTransformer.php index b3cb484a62..034785328e 100644 --- a/app/Transformers/RuleGroupTransformer.php +++ b/app/Transformers/RuleGroupTransformer.php @@ -44,7 +44,7 @@ class RuleGroupTransformer extends AbstractTransformer 'description' => $ruleGroup->description, 'order' => $ruleGroup->order, 'active' => $ruleGroup->active, - 'links' => [['rel' => 'self', 'uri' => '/rule_groups/' . $ruleGroup->id]] + 'links' => [['rel' => 'self', 'uri' => '/rule_groups/'.$ruleGroup->id]], ]; } } diff --git a/app/Transformers/RuleTransformer.php b/app/Transformers/RuleTransformer.php index 8a69e1ba39..1c37d87cb3 100644 --- a/app/Transformers/RuleTransformer.php +++ b/app/Transformers/RuleTransformer.php @@ -69,7 +69,7 @@ class RuleTransformer extends AbstractTransformer 'trigger' => $this->getRuleTrigger($rule), 'triggers' => $this->triggers($rule), 'actions' => $this->actions($rule), - 'links' => [['rel' => 'self', 'uri' => '/rules/' . $rule->id]] + 'links' => [['rel' => 'self', 'uri' => '/rules/'.$rule->id]], ]; } @@ -118,7 +118,7 @@ class RuleTransformer extends AbstractTransformer $triggerValue = 'true'; } - $result[] = [ + $result[] = [ 'id' => (string) $ruleTrigger->id, 'created_at' => $ruleTrigger->created_at->toAtomString(), 'updated_at' => $ruleTrigger->updated_at->toAtomString(), @@ -127,7 +127,7 @@ class RuleTransformer extends AbstractTransformer 'prohibited' => $prohibited, 'order' => $ruleTrigger->order, 'active' => $ruleTrigger->active, - 'stop_processing' => $ruleTrigger->stop_processing + 'stop_processing' => $ruleTrigger->stop_processing, ]; } @@ -149,7 +149,7 @@ class RuleTransformer extends AbstractTransformer 'value' => $ruleAction->action_value, 'order' => $ruleAction->order, 'active' => $ruleAction->active, - 'stop_processing' => $ruleAction->stop_processing + 'stop_processing' => $ruleAction->stop_processing, ]; } diff --git a/app/Transformers/TagTransformer.php b/app/Transformers/TagTransformer.php index 5778023fd4..6f203829fe 100644 --- a/app/Transformers/TagTransformer.php +++ b/app/Transformers/TagTransformer.php @@ -39,7 +39,7 @@ class TagTransformer extends AbstractTransformer */ public function transform(Tag $tag): array { - $date = $tag->date?->format('Y-m-d'); + $date = $tag->date?->format('Y-m-d'); /** @var null|Location $location */ $location = $tag->locations()->first(); @@ -62,7 +62,7 @@ class TagTransformer extends AbstractTransformer 'longitude' => $longitude, 'latitude' => $latitude, 'zoom_level' => $zoomLevel, - 'links' => [['rel' => 'self', 'uri' => '/tags/' . $tag->id]] + 'links' => [['rel' => 'self', 'uri' => '/tags/'.$tag->id]], ]; } } diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index 55897b2ffb..27d7e07df4 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -55,8 +55,8 @@ class TransactionGroupTransformer extends AbstractTransformer public function __construct() { Log::debug('TransactionGroupTransformer constructor.'); - $this->groupRepos = app(TransactionGroupRepositoryInterface::class); - $this->metaFields = [ + $this->groupRepos = app(TransactionGroupRepositoryInterface::class); + $this->metaFields = [ 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', @@ -73,7 +73,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'original_source', 'external_url', 'recurrence_count', - 'recurrence_total' + 'recurrence_total', ]; $this->metaDateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date', '_internal_previous_date']; } @@ -91,7 +91,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'user_group' => (string) $data['user_group_id'], 'group_title' => $data['title'], 'transactions' => $this->transformTransactions($data), - 'links' => [['rel' => 'self', 'uri' => '/transactions/' . $first['transaction_group_id']]] + 'links' => [['rel' => 'self', 'uri' => '/transactions/'.$first['transaction_group_id']]], ]; } @@ -112,8 +112,8 @@ class TransactionGroupTransformer extends AbstractTransformer private function transformTransaction(array $transaction): array { // amount: - $amount = Steam::positive((string) ($transaction['amount'] ?? '0')); - $foreignAmount = null; + $amount = Steam::positive((string) ($transaction['amount'] ?? '0')); + $foreignAmount = null; if (null !== $transaction['foreign_amount'] && '' !== $transaction['foreign_amount'] && 0 !== bccomp('0', (string) $transaction['foreign_amount'])) { $foreignAmount = Steam::positive($transaction['foreign_amount']); } @@ -126,7 +126,7 @@ class TransactionGroupTransformer extends AbstractTransformer if (array_key_exists('pc_amount', $transaction) && null !== $transaction['pc_amount']) { $transaction['pc_amount'] = Steam::positive($transaction['pc_amount']); } - $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); + $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); // must be 0 (int) or NULL $recurrenceTotal = $transaction['meta']['recurrence_total'] ?? null; @@ -135,20 +135,20 @@ class TransactionGroupTransformer extends AbstractTransformer $recurrenceCount = null !== $recurrenceCount ? (int) $recurrenceCount : null; return [ - 'user' => (string) $transaction['user_id'], - 'transaction_journal_id' => (string) $transaction['transaction_journal_id'], - 'type' => strtolower((string) $type), - 'date' => $transaction['date']->toAtomString(), - 'order' => $transaction['order'], + 'user' => (string) $transaction['user_id'], + 'transaction_journal_id' => (string) $transaction['transaction_journal_id'], + 'type' => strtolower((string) $type), + 'date' => $transaction['date']->toAtomString(), + 'order' => $transaction['order'], // currency information, structured for 6.3.0. - 'object_has_currency_setting' => true, + 'object_has_currency_setting' => true, - 'currency_id' => (string) $transaction['currency_id'], - 'currency_code' => $transaction['currency_code'], - 'currency_name' => $transaction['currency_name'], - 'currency_symbol' => $transaction['currency_symbol'], - 'currency_decimal_places' => (int) $transaction['currency_decimal_places'], + 'currency_id' => (string) $transaction['currency_id'], + 'currency_code' => $transaction['currency_code'], + 'currency_name' => $transaction['currency_name'], + 'currency_symbol' => $transaction['currency_symbol'], + 'currency_decimal_places' => (int) $transaction['currency_decimal_places'], 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_code' => $transaction['foreign_currency_code'], @@ -163,83 +163,83 @@ class TransactionGroupTransformer extends AbstractTransformer 'primary_currency_decimal_places' => $transaction['primary_currency']['decimal_places'] ?? null, // amounts, structured for 6.3.0. - 'amount' => $amount, - 'pc_amount' => $transaction['pc_amount'] ?? null, + 'amount' => $amount, + 'pc_amount' => $transaction['pc_amount'] ?? null, - 'foreign_amount' => $foreignAmount, - 'pc_foreign_amount' => null, + 'foreign_amount' => $foreignAmount, + 'pc_foreign_amount' => null, - 'source_balance_after' => $transaction['source_balance_after'] ?? null, - 'pc_source_balance_after' => null, + 'source_balance_after' => $transaction['source_balance_after'] ?? null, + 'pc_source_balance_after' => null, // destination balance after - 'destination_balance_after' => $transaction['destination_balance_after'] ?? null, - 'pc_destination_balance_after' => null, + 'destination_balance_after' => $transaction['destination_balance_after'] ?? null, + 'pc_destination_balance_after' => null, - 'source_balance_dirty' => $transaction['source_balance_dirty'], - 'destination_balance_dirty' => $transaction['destination_balance_dirty'], + 'source_balance_dirty' => $transaction['source_balance_dirty'], + 'destination_balance_dirty' => $transaction['destination_balance_dirty'], - 'description' => $transaction['description'], + 'description' => $transaction['description'], - 'source_id' => (string) $transaction['source_account_id'], - 'source_name' => $transaction['source_account_name'], - 'source_iban' => $transaction['source_account_iban'], - 'source_type' => $transaction['source_account_type'], + 'source_id' => (string) $transaction['source_account_id'], + 'source_name' => $transaction['source_account_name'], + 'source_iban' => $transaction['source_account_iban'], + 'source_type' => $transaction['source_account_type'], - 'destination_id' => (string) $transaction['destination_account_id'], - 'destination_name' => $transaction['destination_account_name'], - 'destination_iban' => $transaction['destination_account_iban'], - 'destination_type' => $transaction['destination_account_type'], + 'destination_id' => (string) $transaction['destination_account_id'], + 'destination_name' => $transaction['destination_account_name'], + 'destination_iban' => $transaction['destination_account_iban'], + 'destination_type' => $transaction['destination_account_type'], - 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null), - 'budget_name' => $transaction['budget_name'], + 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null), + 'budget_name' => $transaction['budget_name'], - 'category_id' => $this->stringFromArray($transaction, 'category_id', null), - 'category_name' => $transaction['category_name'], + 'category_id' => $this->stringFromArray($transaction, 'category_id', null), + 'category_name' => $transaction['category_name'], - 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null), - 'bill_name' => $transaction['bill_name'], - 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null), - 'subscription_name' => $transaction['bill_name'], + 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null), + 'bill_name' => $transaction['bill_name'], + 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null), + 'subscription_name' => $transaction['bill_name'], - 'reconciled' => $transaction['reconciled'], - 'notes' => $transaction['notes'], - 'tags' => $transaction['tags'], + 'reconciled' => $transaction['reconciled'], + 'notes' => $transaction['notes'], + 'tags' => $transaction['tags'], - 'internal_reference' => $transaction['meta']['internal_reference'] ?? null, - 'external_id' => $transaction['meta']['external_id'] ?? null, - 'original_source' => $transaction['meta']['original_source'] ?? null, - 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null, - 'recurrence_total' => $recurrenceTotal, - 'recurrence_count' => $recurrenceCount, - 'external_url' => $transaction['meta']['external_url'] ?? null, - 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null, + 'internal_reference' => $transaction['meta']['internal_reference'] ?? null, + 'external_id' => $transaction['meta']['external_id'] ?? null, + 'original_source' => $transaction['meta']['original_source'] ?? null, + 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null, + 'recurrence_total' => $recurrenceTotal, + 'recurrence_count' => $recurrenceCount, + 'external_url' => $transaction['meta']['external_url'] ?? null, + 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null, - 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null, - 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null, - 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null, - 'sepa_db' => $transaction['meta']['sepa_db'] ?? null, - 'sepa_country' => $transaction['meta']['sepa_country'] ?? null, - 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null, - 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null, - 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null, + 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null, + 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null, + 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null, + 'sepa_db' => $transaction['meta']['sepa_db'] ?? null, + 'sepa_country' => $transaction['meta']['sepa_country'] ?? null, + 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null, + 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null, + 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null, - 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null, - 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null, - 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null, - 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null, - 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null, - 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null, + 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null, + 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null, + 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null, + 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null, + 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null, + 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null, // location data - 'longitude' => $transaction['location']['longitude'], - 'latitude' => $transaction['location']['latitude'], - 'zoom_level' => $transaction['location']['zoom_level'], - 'has_attachments' => $transaction['attachment_count'] > 0 + 'longitude' => $transaction['location']['longitude'], + 'latitude' => $transaction['location']['latitude'], + 'zoom_level' => $transaction['location']['zoom_level'], + 'has_attachments' => $transaction['attachment_count'] > 0, ]; } - private function stringFromArray(array $array, string $key, null|string $default): null|string + private function stringFromArray(array $array, string $key, ?string $default): ?string { if (array_key_exists($key, $array) && null === $array[$key]) { return null; @@ -271,7 +271,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'user' => $group->user_id, 'group_title' => $group->title, 'transactions' => $this->transformJournals($group->transactionJournals), - 'links' => [['rel' => 'self', 'uri' => '/transactions/' . $group->id]] + 'links' => [['rel' => 'self', 'uri' => '/transactions/'.$group->id]], ]; } catch (FireflyException $e) { Log::error($e->getMessage()); @@ -324,10 +324,10 @@ class TransactionGroupTransformer extends AbstractTransformer $foreignAmount = Steam::bcround($foreignAmount, $foreignCurrency['decimal_places'] ?? 0); } - $longitude = null; - $latitude = null; - $zoomLevel = null; - $location = $this->getLocation($journal); + $longitude = null; + $latitude = null; + $zoomLevel = null; + $location = $this->getLocation($journal); if ($location instanceof Location) { $longitude = $location->longitude; $latitude = $location->latitude; @@ -335,77 +335,77 @@ class TransactionGroupTransformer extends AbstractTransformer } return [ - 'user' => $journal->user_id, - 'transaction_journal_id' => (string) $journal->id, - 'type' => strtolower((string) $type), - 'date' => $journal->date->toAtomString(), - 'order' => $journal->order, + 'user' => $journal->user_id, + 'transaction_journal_id' => (string) $journal->id, + 'type' => strtolower((string) $type), + 'date' => $journal->date->toAtomString(), + 'order' => $journal->order, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_id' => (string) $currency->id, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'foreign_currency_id' => (string) $foreignCurrency['id'], 'foreign_currency_code' => $foreignCurrency['code'], 'foreign_currency_symbol' => $foreignCurrency['symbol'], 'foreign_currency_decimal_places' => $foreignCurrency['decimal_places'], - 'amount' => Steam::bcround($amount, $currency->decimal_places), - 'foreign_amount' => $foreignAmount, + 'amount' => Steam::bcround($amount, $currency->decimal_places), + 'foreign_amount' => $foreignAmount, - 'description' => $journal->description, + 'description' => $journal->description, - 'source_id' => (string) $source->account_id, - 'source_name' => $source->account->name, - 'source_iban' => $source->account->iban, - 'source_type' => $source->account->accountType->type, + 'source_id' => (string) $source->account_id, + 'source_name' => $source->account->name, + 'source_iban' => $source->account->iban, + 'source_type' => $source->account->accountType->type, - 'destination_id' => (string) $destination->account_id, - 'destination_name' => $destination->account->name, - 'destination_iban' => $destination->account->iban, - 'destination_type' => $destination->account->accountType->type, + 'destination_id' => (string) $destination->account_id, + 'destination_name' => $destination->account->name, + 'destination_iban' => $destination->account->iban, + 'destination_type' => $destination->account->accountType->type, - 'budget_id' => (string) $budget['id'], - 'budget_name' => $budget['name'], + 'budget_id' => (string) $budget['id'], + 'budget_name' => $budget['name'], - 'category_id' => (string) $category['id'], - 'category_name' => $category['name'], + 'category_id' => (string) $category['id'], + 'category_name' => $category['name'], - 'bill_id' => (string) $bill['id'], - 'bill_name' => $bill['name'], + 'bill_id' => (string) $bill['id'], + 'bill_name' => $bill['name'], - 'reconciled' => $source->reconciled, - 'notes' => $this->groupRepos->getNoteText($journal->id), - 'tags' => $this->groupRepos->getTags($journal->id), + 'reconciled' => $source->reconciled, + 'notes' => $this->groupRepos->getNoteText($journal->id), + 'tags' => $this->groupRepos->getTags($journal->id), - 'internal_reference' => $metaFieldData['internal_reference'], - 'external_id' => $metaFieldData['external_id'], - 'original_source' => $metaFieldData['original_source'], - 'recurrence_id' => $metaFieldData['recurrence_id'], - 'bunq_payment_id' => $metaFieldData['bunq_payment_id'], - 'import_hash_v2' => $metaFieldData['import_hash_v2'], + 'internal_reference' => $metaFieldData['internal_reference'], + 'external_id' => $metaFieldData['external_id'], + 'original_source' => $metaFieldData['original_source'], + 'recurrence_id' => $metaFieldData['recurrence_id'], + 'bunq_payment_id' => $metaFieldData['bunq_payment_id'], + 'import_hash_v2' => $metaFieldData['import_hash_v2'], - 'sepa_cc' => $metaFieldData['sepa_cc'], - 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], - 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], - 'sepa_db' => $metaFieldData['sepa_db'], - 'sepa_country' => $metaFieldData['sepa_country'], - 'sepa_ep' => $metaFieldData['sepa_ep'], - 'sepa_ci' => $metaFieldData['sepa_ci'], - 'sepa_batch_id' => $metaFieldData['sepa_batch_id'], + 'sepa_cc' => $metaFieldData['sepa_cc'], + 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], + 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], + 'sepa_db' => $metaFieldData['sepa_db'], + 'sepa_country' => $metaFieldData['sepa_country'], + 'sepa_ep' => $metaFieldData['sepa_ep'], + 'sepa_ci' => $metaFieldData['sepa_ci'], + 'sepa_batch_id' => $metaFieldData['sepa_batch_id'], - 'interest_date' => $metaDates['interest_date'], - 'book_date' => $metaDates['book_date'], - 'process_date' => $metaDates['process_date'], - 'due_date' => $metaDates['due_date'], - 'payment_date' => $metaDates['payment_date'], - 'invoice_date' => $metaDates['invoice_date'], + 'interest_date' => $metaDates['interest_date'], + 'book_date' => $metaDates['book_date'], + 'process_date' => $metaDates['process_date'], + 'due_date' => $metaDates['due_date'], + 'payment_date' => $metaDates['payment_date'], + 'invoice_date' => $metaDates['invoice_date'], // location data - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoom_level' => $zoomLevel, ]; } @@ -414,7 +414,7 @@ class TransactionGroupTransformer extends AbstractTransformer */ private function getSourceTransaction(TransactionJournal $journal): Transaction { - $result = $journal->transactions->first(static fn(Transaction $transaction): bool => (float) $transaction->amount < 0); + $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount < 0); if (null === $result) { throw new FireflyException(sprintf('Journal #%d unexpectedly has no source transaction.', $journal->id)); } @@ -427,7 +427,7 @@ class TransactionGroupTransformer extends AbstractTransformer */ private function getDestinationTransaction(TransactionJournal $journal): Transaction { - $result = $journal->transactions->first(static fn(Transaction $transaction): bool => (float) $transaction->amount > 0); + $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount > 0); if (null === $result) { throw new FireflyException(sprintf('Journal #%d unexpectedly has no destination transaction.', $journal->id)); } @@ -440,7 +440,7 @@ class TransactionGroupTransformer extends AbstractTransformer return Steam::positive($amount); } - private function getForeignAmount(null|string $foreignAmount): null|string + private function getForeignAmount(?string $foreignAmount): ?string { if (null !== $foreignAmount && '' !== $foreignAmount && 0 !== bccomp('0', $foreignAmount)) { return Steam::positive($foreignAmount); @@ -463,57 +463,57 @@ class TransactionGroupTransformer extends AbstractTransformer return $return; } - private function getForeignCurrency(null|TransactionCurrency $currency): array + private function getForeignCurrency(?TransactionCurrency $currency): array { - $array = ['id' => null, 'code' => null, 'symbol' => null, 'decimal_places' => null]; + $array = ['id' => null, 'code' => null, 'symbol' => null, 'decimal_places' => null]; if (!$currency instanceof TransactionCurrency) { return $array; } - $array['id'] = $currency->id; - $array['code'] = $currency->code; - $array['symbol'] = $currency->symbol; + $array['id'] = $currency->id; + $array['code'] = $currency->code; + $array['symbol'] = $currency->symbol; $array['decimal_places'] = $currency->decimal_places; return $array; } - private function getBudget(null|Budget $budget): array + private function getBudget(?Budget $budget): array { - $array = ['id' => null, 'name' => null]; + $array = ['id' => null, 'name' => null]; if (!$budget instanceof Budget) { return $array; } - $array['id'] = $budget->id; + $array['id'] = $budget->id; $array['name'] = $budget->name; return $array; } - private function getCategory(null|Category $category): array + private function getCategory(?Category $category): array { - $array = ['id' => null, 'name' => null]; + $array = ['id' => null, 'name' => null]; if (!$category instanceof Category) { return $array; } - $array['id'] = $category->id; + $array['id'] = $category->id; $array['name'] = $category->name; return $array; } - private function getBill(null|Bill $bill): array + private function getBill(?Bill $bill): array { - $array = ['id' => null, 'name' => null]; + $array = ['id' => null, 'name' => null]; if (!$bill instanceof Bill) { return $array; } - $array['id'] = (string) $bill->id; + $array['id'] = (string) $bill->id; $array['name'] = $bill->name; return $array; } - private function getLocation(TransactionJournal $journal): null|Location + private function getLocation(TransactionJournal $journal): ?Location { /** @var null|Location */ return $journal->locations()->first(); diff --git a/app/Transformers/TransactionLinkTransformer.php b/app/Transformers/TransactionLinkTransformer.php index c3f8a62b5b..2511b5b959 100644 --- a/app/Transformers/TransactionLinkTransformer.php +++ b/app/Transformers/TransactionLinkTransformer.php @@ -55,7 +55,7 @@ class TransactionLinkTransformer extends AbstractTransformer 'outward_id' => (string) $link->destination_id, 'link_type_id' => (string) $link->link_type_id, 'notes' => '' === $notes ? null : $notes, - 'links' => [['rel' => 'self', 'uri' => '/transaction_links/' . $link->id]] + 'links' => [['rel' => 'self', 'uri' => '/transaction_links/'.$link->id]], ]; } } diff --git a/app/Transformers/UserGroupTransformer.php b/app/Transformers/UserGroupTransformer.php index 091ee9a565..63be3fe689 100644 --- a/app/Transformers/UserGroupTransformer.php +++ b/app/Transformers/UserGroupTransformer.php @@ -49,9 +49,9 @@ class UserGroupTransformer extends AbstractTransformer /** @var UserGroup $userGroup */ foreach ($objects as $userGroup) { - $userGroupId = $userGroup->id; - $this->inUse[$userGroupId] = $user->user_group_id === $userGroupId; - $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::VIEW_MEMBERSHIPS) || $user->hasRole('owner'); + $userGroupId = $userGroup->id; + $this->inUse[$userGroupId] = $user->user_group_id === $userGroupId; + $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::VIEW_MEMBERSHIPS) || $user->hasRole('owner'); $this->membershipsVisible[$userGroupId] = $access; if ($access) { $groupMemberships = $userGroup->groupMemberships()->get(); @@ -62,7 +62,7 @@ class UserGroupTransformer extends AbstractTransformer 'user_id' => (string) $groupMembership->user_id, 'user_email' => $groupMembership->user->email, 'role' => $groupMembership->userRole->title, - 'you' => $groupMembership->user_id === $user->id + 'you' => $groupMembership->user_id === $user->id, ]; } } @@ -75,17 +75,17 @@ class UserGroupTransformer extends AbstractTransformer private function mergeMemberships(): void { - $new = []; + $new = []; foreach ($this->memberships as $groupId => $members) { $new[$groupId] ??= []; foreach ($members as $member) { - $mail = $member['user_email']; + $mail = $member['user_email']; $new[$groupId][$mail] ??= [ 'user_id' => (string) $member['user_id'], 'user_email' => $member['user_email'], 'you' => $member['you'], - 'roles' => [] + 'roles' => [], ]; $new[$groupId][$mail]['roles'][] = $member['role']; } @@ -112,7 +112,7 @@ class UserGroupTransformer extends AbstractTransformer 'primary_currency_code' => $currency->code, 'primary_currency_symbol' => $currency->symbol, 'primary_currency_decimal_places' => $currency->decimal_places, - 'members' => array_values($this->memberships[$userGroup->id] ?? []) + 'members' => array_values($this->memberships[$userGroup->id] ?? []), ]; // if the user has a specific role in this group, then collect the memberships. diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index a896b2657d..7c0ef2546f 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -49,7 +49,7 @@ class UserTransformer extends AbstractTransformer 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code, 'role' => $this->repository->getRoleByUser($user), - 'links' => [['rel' => 'self', 'uri' => '/users/' . $user->id]] + 'links' => [['rel' => 'self', 'uri' => '/users/'.$user->id]], ]; } } diff --git a/app/Transformers/WebhookAttemptTransformer.php b/app/Transformers/WebhookAttemptTransformer.php index 5309d6ab94..2ab04f184a 100644 --- a/app/Transformers/WebhookAttemptTransformer.php +++ b/app/Transformers/WebhookAttemptTransformer.php @@ -43,7 +43,7 @@ class WebhookAttemptTransformer extends AbstractTransformer 'webhook_message_id' => (string) $attempt->webhook_message_id, 'status_code' => (int) $attempt->status_code, 'logs' => $attempt->logs, - 'response' => $attempt->response + 'response' => $attempt->response, ]; } } diff --git a/app/Transformers/WebhookMessageTransformer.php b/app/Transformers/WebhookMessageTransformer.php index a17c403042..24bc25d4c2 100644 --- a/app/Transformers/WebhookMessageTransformer.php +++ b/app/Transformers/WebhookMessageTransformer.php @@ -56,7 +56,7 @@ class WebhookMessageTransformer extends AbstractTransformer 'errored' => $message->errored, 'webhook_id' => (string) $message->webhook_id, 'uuid' => $message->uuid, - 'message' => $json + 'message' => $json, ]; } } diff --git a/app/Transformers/WebhookTransformer.php b/app/Transformers/WebhookTransformer.php index f9f6b62a4c..ba921363d1 100644 --- a/app/Transformers/WebhookTransformer.php +++ b/app/Transformers/WebhookTransformer.php @@ -47,7 +47,7 @@ class WebhookTransformer extends AbstractTransformer 'deliveries' => $webhook->meta['deliveries'], 'responses' => $webhook->meta['responses'], 'url' => $webhook->url, - 'links' => [['rel' => 'self', 'uri' => sprintf('/webhooks/%d', $webhook->id)]] + 'links' => [['rel' => 'self', 'uri' => sprintf('/webhooks/%d', $webhook->id)]], ]; } } diff --git a/app/User.php b/app/User.php index 286ae83ca4..0e8ebbb748 100644 --- a/app/User.php +++ b/app/User.php @@ -251,20 +251,21 @@ class User extends Authenticatable Log::debug(sprintf('in hasAnyRoleInGroup(%s)', implode(', ', $roles))); /** @var Collection $dbRoles */ - $dbRoles = UserRole::whereIn('title', $roles)->get(); + $dbRoles = UserRole::whereIn('title', $roles)->get(); if (0 === $dbRoles->count()) { Log::error(sprintf('Could not find role(s): %s. Probably migration mishap.', implode(', ', $roles))); return false; } - $dbRolesIds = $dbRoles->pluck('id')->toArray(); - $dbRolesTitles = $dbRoles->pluck('title')->toArray(); + $dbRolesIds = $dbRoles->pluck('id')->toArray(); + $dbRolesTitles = $dbRoles->pluck('title')->toArray(); $groupMemberships = $this ->groupMemberships() ->whereIn('user_role_id', $dbRolesIds) ->where('user_group_id', $userGroup->id) - ->get(); + ->get() + ; if (0 === $groupMemberships->count()) { Log::error(sprintf( 'User #%d "%s" does not have roles %s in user group #%d "%s"', @@ -359,13 +360,13 @@ class User extends Authenticatable */ public function routeNotificationFor($driver, $notification = null) { - $method = 'routeNotificationFor' . Str::studly($driver); + $method = 'routeNotificationFor'.Str::studly($driver); if (method_exists($this, $method)) { return $this->{$method}($notification); // @phpstan-ignore-line } - $email = $this->email; + $email = $this->email; // see if user has alternative email address: - $pref = Preferences::getForUser($this, 'remote_guard_alt_email'); + $pref = Preferences::getForUser($this, 'remote_guard_alt_email'); if (null !== $pref) { $email = $pref->data; } @@ -375,7 +376,7 @@ class User extends Authenticatable } return match ($driver) { - 'mail' => $email, + 'mail' => $email, default => null }; } @@ -407,14 +408,14 @@ class User extends Authenticatable /** * Route notifications for the Slack channel. */ - public function routeNotificationForSlack(Notification $notification): null|string + public function routeNotificationForSlack(Notification $notification): ?string { // this check does not validate if the user is owner, Should be done by notification itself. - $res = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; + $res = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; if (is_array($res)) { $res = ''; } - $res = (string) $res; + $res = (string) $res; if (property_exists($notification, 'type') && 'owner' === $notification->type) { return $res; diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php index f419db53f2..068a9c0217 100644 --- a/app/Validation/Account/DepositValidation.php +++ b/app/Validation/Account/DepositValidation.php @@ -44,13 +44,13 @@ trait DepositValidation Log::debug('Now in validateDepositDestination', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; + $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 deposit can't be created. $this->destError = (string) trans('validation.deposit_dest_need_data'); Log::error('Both values are NULL, cant create deposit destination.'); - $result = false; + $result = false; } // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { @@ -64,7 +64,7 @@ trait DepositValidation if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.'); $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $result = false; } if (null !== $search) { Log::debug(sprintf('findExistingAccount() returned #%d ("%s"), so the result is true.', $search->id, $search->name)); @@ -79,7 +79,7 @@ trait DepositValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; + abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; /** * Pretty complex unfortunately. @@ -97,16 +97,16 @@ trait DepositValidation // null = we found nothing at all or didn't even search // false = invalid results - $result = null; + $result = null; // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). $this->sourceError = (string) trans('validation.deposit_source_need_data'); - $result = false; + $result = false; } // if there is an iban, it can only be in use by a valid source type, or we will fail. @@ -129,7 +129,7 @@ trait DepositValidation Log::debug(sprintf('Firefly III does not accept ID #%d as valid account data.', $accountId)); // #10921 Set result false $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $result = false; } if (null !== $search && in_array($search->accountType->type, $validTypes, true)) { Log::debug('ID result is not null and seems valid, save as source account.'); @@ -172,11 +172,11 @@ trait DepositValidation // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { - $result = true; + $result = true; // set the source to be a (dummy) revenue account. - $account = new Account(); - $accountType = AccountType::whereType(AccountTypeEnum::REVENUE->value)->first(); + $account = new Account(); + $accountType = AccountType::whereType(AccountTypeEnum::REVENUE->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/LiabilityValidation.php b/app/Validation/Account/LiabilityValidation.php index 228b9694ea..a57b874f73 100644 --- a/app/Validation/Account/LiabilityValidation.php +++ b/app/Validation/Account/LiabilityValidation.php @@ -78,7 +78,7 @@ trait LiabilityValidation 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['id'] ?? null; + $accountId = $array['id'] ?? null; if (null !== $accountId) { Log::debug('Source ID is not null, assume were looking for a liability.'); // find liability credit: @@ -97,7 +97,7 @@ trait LiabilityValidation // if array has name and is not null, return true. $accountName = $array['name'] ?? null; - $result = true; + $result = true; if ('' === $accountName || null === $accountName) { Log::error('Array must have a name, is not the case, return false.'); $result = false; @@ -105,8 +105,8 @@ trait LiabilityValidation 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(); + $account = new Account(); + $accountType = AccountType::whereType(AccountTypeEnum::LIABILITY_CREDIT->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php index b404c9bf1a..526141833a 100644 --- a/app/Validation/Account/OBValidation.php +++ b/app/Validation/Account/OBValidation.php @@ -42,13 +42,13 @@ trait OBValidation Log::debug('Now in validateOBDestination', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source?->accountType->type] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source?->accountType->type] ?? []; if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a deposit can't be created. $this->destError = (string) trans('validation.ob_dest_need_data'); Log::error('Both values are NULL, cant create OB destination.'); - $result = false; + $result = false; } // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { @@ -62,7 +62,7 @@ trait OBValidation if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes); $this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $result = false; } if (null !== $search) { Log::debug(sprintf('findExistingAccount() returned #%d ("%s"), so the result is true.', $search->id, $search->name)); @@ -86,16 +86,16 @@ trait OBValidation $accountId = $array['id'] ?? null; $accountName = $array['name'] ?? null; Log::debug('Now in validateOBSource', $array); - $result = null; + $result = null; // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). $this->sourceError = (string) trans('validation.ob_source_need_data'); - $result = false; + $result = false; } // if the user submits an ID only but that ID is not of the correct type, @@ -106,10 +106,10 @@ trait OBValidation // the source resulted in an account, but it's not of a valid type. if (null !== $search && !in_array($search->accountType->type, $validTypes, true)) { - $message = sprintf('User submitted only an ID (#%d), which is a "%s", so this is not a valid source.', $accountId, $search->accountType->type); + $message = sprintf('User submitted only an ID (#%d), which is a "%s", so this is not a valid source.', $accountId, $search->accountType->type); Log::debug($message); $this->sourceError = $message; - $result = false; + $result = false; } // the source resulted in an account, AND it's of a valid type. if (null !== $search && in_array($search->accountType->type, $validTypes, true)) { @@ -122,13 +122,13 @@ trait OBValidation // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { Log::debug('Result is still null.'); - $result = true; + $result = true; // set the source to be a (dummy) initial balance account. - $account = new Account(); + $account = new Account(); /** @var AccountType $accountType */ - $accountType = AccountType::whereType(AccountTypeEnum::INITIAL_BALANCE->value)->first(); + $accountType = AccountType::whereType(AccountTypeEnum::INITIAL_BALANCE->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/ReconciliationValidation.php b/app/Validation/Account/ReconciliationValidation.php index 08913680aa..8c911df112 100644 --- a/app/Validation/Account/ReconciliationValidation.php +++ b/app/Validation/Account/ReconciliationValidation.php @@ -32,8 +32,8 @@ use Illuminate\Support\Facades\Log; */ trait ReconciliationValidation { - public null|Account $destination = null; - public null|Account $source = null; + public ?Account $destination = null; + public ?Account $source = null; protected function validateReconciliationDestination(array $array): bool { @@ -51,8 +51,8 @@ trait ReconciliationValidation 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); + $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]); Log::warning('Not a valid source. Cant find it.', $validTypes); @@ -86,8 +86,8 @@ trait ReconciliationValidation 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); + $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]); Log::warning('Not a valid source. Cant find it.', $validTypes); diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php index d174133eaa..c4aeeb2dc1 100644 --- a/app/Validation/Account/TransferValidation.php +++ b/app/Validation/Account/TransferValidation.php @@ -39,7 +39,7 @@ trait TransferValidation $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] ?? []; + $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. @@ -50,7 +50,7 @@ trait TransferValidation } // or try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); @@ -61,7 +61,7 @@ trait TransferValidation // must not be the same as the source account if (null !== $this->source && $this->source->id === $this->destination->id) { $this->sourceError = 'Source and destination are the same.'; - $this->destError = 'Source and destination are the same.'; + $this->destError = 'Source and destination are the same.'; return false; } @@ -71,7 +71,7 @@ trait TransferValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; + abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; protected function validateTransferSource(array $array): bool { @@ -81,7 +81,7 @@ trait TransferValidation $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]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. @@ -92,7 +92,7 @@ trait TransferValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source, cant find it.', $validTypes); diff --git a/app/Validation/Account/WithdrawalValidation.php b/app/Validation/Account/WithdrawalValidation.php index 0a9f624334..668037010d 100644 --- a/app/Validation/Account/WithdrawalValidation.php +++ b/app/Validation/Account/WithdrawalValidation.php @@ -40,12 +40,12 @@ trait WithdrawalValidation $accountIban = $array['iban'] ?? null; Log::debug('Now in validateGenericSource', $array); // source can be any of the following types. - $validTypes = [ + $validTypes = [ AccountTypeEnum::ASSET->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value + AccountTypeEnum::MORTGAGE->value, ]; if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return TRUE @@ -57,7 +57,7 @@ trait WithdrawalValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); @@ -72,7 +72,7 @@ trait WithdrawalValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; + abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; protected function validateWithdrawalDestination(array $array): bool { @@ -82,7 +82,7 @@ trait WithdrawalValidation $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] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; Log::debug('Source type can be: ', $validTypes); if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, @@ -96,7 +96,7 @@ trait WithdrawalValidation if (null !== $accountId && 0 !== $accountId && $accountId !== $this->source->id) { $found = $this->accountRepository->find($accountId); if (null !== $found) { - $type = $found->accountType->type; + $type = $found->accountType->type; if (in_array($type, $validTypes, true)) { $this->setDestination($found); @@ -134,7 +134,7 @@ trait WithdrawalValidation Log::debug('Now in validateWithdrawalSource', $array); // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && null === $accountNumber && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. @@ -145,7 +145,7 @@ trait WithdrawalValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index 403db6612b..166a577d08 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -52,8 +52,8 @@ class AccountValidator public bool $createMode = false; public string $destError = 'No error yet.'; - public null|Account $destination = null; - public null|Account $source = null; + public ?Account $destination = null; + public ?Account $source = null; public string $sourceError = 'No error yet.'; private AccountRepositoryInterface $accountRepository; private array $combinations; @@ -64,16 +64,16 @@ class AccountValidator */ public function __construct() { - $this->combinations = config('firefly.source_dests'); + $this->combinations = config('firefly.source_dests'); $this->accountRepository = app(AccountRepositoryInterface::class); } - public function getSource(): null|Account + public function getSource(): ?Account { return $this->source; } - public function setSource(null|Account $account): void + public function setSource(?Account $account): void { if (!$account instanceof Account) { Log::debug('AccountValidator source is set to NULL'); @@ -84,7 +84,7 @@ class AccountValidator $this->source = $account; } - public function setDestination(null|Account $account): void + public function setDestination(?Account $account): void { if (!$account instanceof Account) { Log::debug('AccountValidator destination is set to NULL'); @@ -126,37 +126,37 @@ class AccountValidator $this->destError = sprintf('AccountValidator::validateDestination cannot handle "%s", so it will always return false.', $this->transactionType); Log::error(sprintf('AccountValidator::validateDestination cannot handle "%s", so it will always return false.', $this->transactionType)); - $result = false; + $result = false; break; case TransactionTypeEnum::WITHDRAWAL->value: - $result = $this->validateWithdrawalDestination($array); + $result = $this->validateWithdrawalDestination($array); break; case TransactionTypeEnum::DEPOSIT->value: - $result = $this->validateDepositDestination($array); + $result = $this->validateDepositDestination($array); break; case TransactionTypeEnum::TRANSFER->value: - $result = $this->validateTransferDestination($array); + $result = $this->validateTransferDestination($array); break; case TransactionTypeEnum::OPENING_BALANCE->value: - $result = $this->validateOBDestination($array); + $result = $this->validateOBDestination($array); break; case TransactionTypeEnum::LIABILITY_CREDIT->value: - $result = $this->validateLCDestination($array); + $result = $this->validateLCDestination($array); break; case TransactionTypeEnum::RECONCILIATION->value: - $result = $this->validateReconciliationDestination($array); + $result = $this->validateReconciliationDestination($array); break; } @@ -233,7 +233,7 @@ class AccountValidator AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::INITIAL_BALANCE->value, - AccountTypeEnum::LIABILITY_CREDIT->value + AccountTypeEnum::LIABILITY_CREDIT->value, ]; return in_array($accountType, $canCreate, true); @@ -246,7 +246,7 @@ class AccountValidator * @SuppressWarnings("PHPMD.BooleanArgumentFlag") * @SuppressWarnings("PHPMD.NPathComplexity") */ - protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): null|Account + protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): ?Account { Log::debug('Now in findExistingAccount', [$validTypes, $data]); Log::debug('The search will be reversed!'); diff --git a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php index 52812f9b1f..93bff7105c 100644 --- a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php +++ b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php @@ -33,7 +33,7 @@ trait ValidatesBulkTransactionQuery { protected function validateTransactionQuery(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); // assumption is all validation has already taken place and the query key exists. $query = $data['query'] ?? '[]'; $json = json_decode($query, true, 8, JSON_THROW_ON_ERROR); @@ -46,9 +46,9 @@ trait ValidatesBulkTransactionQuery ) { // find both accounts, must be same type. // already validated: belongs to this user. - $repository = app(AccountRepositoryInterface::class); - $source = $repository->find((int) $json['where']['account_id']); - $dest = $repository->find((int) $json['update']['account_id']); + $repository = app(AccountRepositoryInterface::class); + $source = $repository->find((int) $json['where']['account_id']); + $dest = $repository->find((int) $json['update']['account_id']); if (null === $source) { $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'where', 'account_id')); diff --git a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php index dcbffa2545..28bad253e3 100644 --- a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php +++ b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php @@ -36,8 +36,8 @@ trait ValidatesAutoBudgetRequest */ protected function validateAutoBudgetAmount(Validator $validator): void { - $data = $validator->getData(); - $type = $data['auto_budget_type'] ?? ''; + $data = $validator->getData(); + $type = $data['auto_budget_type'] ?? ''; /** @var null|float|int|string $amount */ $amount = $data['auto_budget_amount'] ?? null; diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php index 4e312f4bf2..d663dc95d8 100644 --- a/app/Validation/CurrencyValidation.php +++ b/app/Validation/CurrencyValidation.php @@ -70,27 +70,27 @@ trait CurrencyValidation (array_key_exists('foreign_currency_id', $transaction) || array_key_exists('foreign_currency_code', $transaction)) && (null !== $foreignId || null !== $foreignCode) ) { - $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.' . $index . '.foreign_currency_id', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.' . $index . '.foreign_currency_code', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_currency_id', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_currency_code', (string) trans('validation.require_currency_amount')); } continue; } - $compare = bccomp('0', $foreignAmount); + $compare = bccomp('0', $foreignAmount); if (-1 === $compare) { Log::debug('validateForeignCurrencyInformation: array contains foreign amount info.'); if (!array_key_exists('foreign_currency_id', $transaction) && !array_key_exists('foreign_currency_code', $transaction)) { Log::debug('validateForeignCurrencyInformation: array contains NO foreign currency info.'); - $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_info')); + $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_info')); } } if (0 === $compare && ('' !== (string) $foreignId || '' !== (string) $foreignCode)) { Log::debug('validateForeignCurrencyInformation: array contains foreign currency info, but zero amount.'); - $validator->errors()->add('transactions.' . $index . '.foreign_currency_id', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.' . $index . '.foreign_currency_code', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_currency_id', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_currency_code', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_amount')); } } } diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index 5bdbe629b9..641bb73668 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -80,7 +80,7 @@ class FireflyValidator extends Validator if (!is_string($value) || 6 !== strlen($value)) { return false; } - $user = auth()->user(); + $user = auth()->user(); if (null === $user) { Log::error('No user during validate2faCode'); @@ -91,7 +91,7 @@ class FireflyValidator extends Validator if (is_array($secret)) { $secret = ''; } - $secret = (string) $secret; + $secret = (string) $secret; return (bool) Facade::verifyKey($secret, $value); } @@ -113,7 +113,8 @@ class FireflyValidator extends Validator $count = DB::table($parameters[0]) ->where('user_id', auth()->user()->id) ->where($field, $value) - ->count(); + ->count() + ; return 1 === $count; } @@ -137,7 +138,7 @@ class FireflyValidator extends Validator if (!is_string($value) || 6 !== strlen($value)) { return false; } - $user = auth()->user(); + $user = auth()->user(); if (null === $user) { Log::error('No user during validate2faCode'); @@ -207,7 +208,7 @@ class FireflyValidator extends Validator "\u{FEFF}", // zero width no -break space ' ', '-', - '?' + '?', ]; $replace = ''; $value = str_replace($search, $replace, $value); @@ -248,14 +249,14 @@ class FireflyValidator extends Validator '32', '33', '34', - '35' + '35', ]; // take - $first = substr($value, 0, 4); - $last = substr($value, 4); - $iban = $last . $first; - $iban = trim(str_replace($search, $replace, $iban)); + $first = substr($value, 0, 4); + $last = substr($value, 4); + $iban = $last.$first; + $iban = trim(str_replace($search, $replace, $iban)); if ('' === $iban) { return false; } @@ -322,12 +323,12 @@ class FireflyValidator extends Validator return 1 === $count; } - public function validateRuleActionValue(string $attribute, null|string $value = null): bool + public function validateRuleActionValue(string $attribute, ?string $value = null): bool { // first, get the index from this string: $value ??= ''; - $parts = explode('.', $attribute); - $index = (int) ($parts[1] ?? '0'); + $parts = explode('.', $attribute); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $actionType = $this->data['actions'][$index]['type'] ?? 'invalid'; @@ -369,7 +370,7 @@ class FireflyValidator extends Validator AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value + AccountTypeEnum::CREDITCARD->value, ]); return null !== $account; @@ -390,11 +391,11 @@ class FireflyValidator extends Validator /** * $attribute has the format triggers.%d.value. */ - public function validateRuleTriggerValue(string $attribute, null|string $value = null): bool + public function validateRuleTriggerValue(string $attribute, ?string $value = null): bool { // first, get the index from this string: - $parts = explode('.', $attribute); - $index = (int) ($parts[1] ?? '0'); + $parts = explode('.', $attribute); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $triggerType = $this->data['triggers'][$index]['type'] ?? 'invalid'; @@ -405,14 +406,14 @@ class FireflyValidator extends Validator } // these trigger types need a numerical check: - $numerical = ['amount_less', 'amount_more', 'amount_exactly']; + $numerical = ['amount_less', 'amount_more', 'amount_exactly']; if (in_array($triggerType, $numerical, true)) { return is_numeric($value); } // these triggers need just the word "true": // TODO create a helper to automatically return these. - $needTrue = [ + $needTrue = [ 'reconciled', 'has_attachments', 'has_any_category', @@ -433,7 +434,7 @@ class FireflyValidator extends Validator 'account_is_cash', 'exists', 'no_external_id', - 'any_external_id' + 'any_external_id', ]; if (in_array($triggerType, $needTrue, true)) { return 'true' === $value; @@ -441,7 +442,7 @@ class FireflyValidator extends Validator // these trigger types need a simple strlen check: // TODO create a helper to automatically return these. - $length = [ + $length = [ 'source_account_starts', 'source_account_ends', 'source_account_is', @@ -461,7 +462,7 @@ class FireflyValidator extends Validator 'notes_contain', 'notes_start', 'notes_end', - 'notes_are' + 'notes_are', ]; if (in_array($triggerType, $length, true)) { return '' !== $value; @@ -505,7 +506,7 @@ class FireflyValidator extends Validator * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validateSecurePassword($attribute, null|string $value): bool + public function validateSecurePassword($attribute, ?string $value): bool { $value = (string) $value; $verify = false; @@ -582,9 +583,9 @@ class FireflyValidator extends Validator } /** @var User $user */ - $user = User::find($this->data['user_id']); - $type = AccountType::find($this->data['account_type_id'])->first(); - $value = $this->data['name']; + $user = User::find($this->data['user_id']); + $type = AccountType::find($this->data['account_type_id'])->first(); + $value = $this->data['name']; /** @var null|Account $result */ $result = $user->accounts()->where('account_type_id', $type->id)->where('name', $value)->first(); @@ -595,7 +596,7 @@ class FireflyValidator extends Validator private function validateByAccountTypeString(string $value, array $parameters, string $type): bool { /** @var null|array $search */ - $search = Config::get('firefly.accountTypeByIdentifier.' . $type); + $search = Config::get('firefly.accountTypeByIdentifier.'.$type); if (null === $search) { return false; @@ -606,7 +607,7 @@ class FireflyValidator extends Validator $accountTypeIds = $accountTypes->pluck('id')->toArray(); /** @var null|Account $result */ - $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->where('name', $value)->first(); + $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $result; } @@ -634,10 +635,10 @@ class FireflyValidator extends Validator /** @var Account $existingAccount */ $existingAccount = Account::find($accountId); - $type = $existingAccount->accountType; - $ignore = $existingAccount->id; + $type = $existingAccount->accountType; + $ignore = $existingAccount->id; - $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); + $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $entry; } @@ -650,10 +651,10 @@ class FireflyValidator extends Validator /** @var Account $existingAccount */ $existingAccount = Account::find($this->data['id']); - $type = $existingAccount->accountType; - $ignore = $existingAccount->id; + $type = $existingAccount->accountType; + $ignore = $existingAccount->id; - $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); + $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $entry; } @@ -679,18 +680,19 @@ class FireflyValidator extends Validator $accountId = (int) ($parameters[0] ?? 0.0); } - $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') ->where('accounts.user_id', auth()->user()->id) ->where('account_meta.name', 'account_number') - ->where('account_meta.data', json_encode($value)); + ->where('account_meta.data', json_encode($value)) + ; if ($accountId > 0) { // exclude current account from check. $query->where('account_meta.account_id', '!=', $accountId); } - $set = $query->get(['account_meta.*']); - $count = $set->count(); + $set = $query->get(['account_meta.*']); + $count = $set->count(); if (0 === $count) { return true; } @@ -698,7 +700,7 @@ class FireflyValidator extends Validator // pretty much impossible but still. return false; } - $type = $this->data['objectType'] ?? 'unknown'; + $type = $this->data['objectType'] ?? 'unknown'; if ('expense' !== $type && 'revenue' !== $type) { Log::warning(sprintf('Account number "%s" is not unique and account type "%s" cannot share its account number.', $value, $type)); @@ -725,7 +727,7 @@ class FireflyValidator extends Validator /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validateUniqueCurrencyCode(null|string $attribute, null|string $value): bool + public function validateUniqueCurrencyCode(?string $attribute, ?string $value): bool { return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value); } @@ -738,15 +740,16 @@ class FireflyValidator extends Validator return 0 === DB::table('transaction_currencies') ->where($field, $value) ->whereNull('deleted_at') - ->count(); + ->count() + ; } - public function validateUniqueCurrencyName(null|string $attribute, null|string $value): bool + public function validateUniqueCurrencyName(?string $attribute, ?string $value): bool { return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value); } - public function validateUniqueCurrencySymbol(null|string $attribute, null|string $value): bool + public function validateUniqueCurrencySymbol(?string $attribute, ?string $value): bool { return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value); } @@ -771,7 +774,7 @@ class FireflyValidator extends Validator // get existing webhook value: if (0 !== $existingId) { /** @var null|Webhook $webhook */ - $webhook = auth()->user()->webhooks()->find($existingId); + $webhook = auth()->user()->webhooks()->find($existingId); if (null === $webhook) { return false; } @@ -794,7 +797,8 @@ class FireflyValidator extends Validator ->where('delivery', $delivery) ->where('id', '!=', $existingId) ->where('url', $url) - ->count(); + ->count() + ; } return false; @@ -816,23 +820,24 @@ class FireflyValidator extends Validator public function validateUniqueObjectForUser($attribute, $value, $parameters): bool { [$table, $field] = $parameters; - $exclude = (int) ($parameters[2] ?? 0.0); + $exclude = (int) ($parameters[2] ?? 0.0); /* * If other data (in $this->getData()) contains * ID field, set that field to be the $exclude. */ - $data = $this->getData(); + $data = $this->getData(); if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int) $data['id'] > 0) { $exclude = (int) $data['id']; } // get entries from table - $result = DB::table($table) + $result = DB::table($table) ->where('user_id', auth()->user()->id) ->whereNull('deleted_at') ->where('id', '!=', $exclude) ->where($field, $value) - ->first([$field]); + ->first([$field]) + ; if (null === $result) { return true; // not found, so true. } @@ -854,7 +859,8 @@ class FireflyValidator extends Validator $query = DB::table('object_groups') ->whereNull('object_groups.deleted_at') ->where('object_groups.user_id', auth()->user()->id) - ->where('object_groups.title', $value); + ->where('object_groups.title', $value) + ; if (null !== $exclude) { $query->where('object_groups.id', '!=', (int) $exclude); } @@ -874,7 +880,8 @@ class FireflyValidator extends Validator $exclude = $parameters[0] ?? null; $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') - ->where('accounts.user_id', auth()->user()->id); + ->where('accounts.user_id', auth()->user()->id) + ; if (null !== $exclude) { $query->where('piggy_banks.id', '!=', (int) $exclude); } @@ -897,11 +904,11 @@ class FireflyValidator extends Validator $deliveries = Webhook::getDeliveriesForValidation(); // integers - $trigger = $triggers[$this->data['trigger']] ?? 0; - $response = $responses[$this->data['response']] ?? 0; - $delivery = $deliveries[$this->data['delivery']] ?? 0; - $url = $this->data['url']; - $userId = auth()->user()->id; + $trigger = $triggers[$this->data['trigger']] ?? 0; + $response = $responses[$this->data['response']] ?? 0; + $delivery = $deliveries[$this->data['delivery']] ?? 0; + $url = $this->data['url']; + $userId = auth()->user()->id; return 0 === Webhook::whereUserId($userId) ->where('trigger', $trigger) diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php index 11dfba4b42..87372dcd1c 100644 --- a/app/Validation/GroupValidation.php +++ b/app/Validation/GroupValidation.php @@ -56,7 +56,7 @@ trait GroupValidation 'source_iban', 'destination_iban', 'source_number', - 'destination_number' + 'destination_number', ]; /** @var null|array $transaction */ @@ -87,12 +87,13 @@ trait GroupValidation { Log::debug(sprintf('Now in %s', __METHOD__)); - $count = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id') + $count = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id') ->leftJoin('transaction_groups', 'transaction_groups.id', 'transaction_journals.transaction_group_id') ->where('transaction_journals.transaction_group_id', $transactionGroup->id) ->where('transactions.reconciled', 1) ->where('transactions.amount', '<', 0) - ->count('transactions.id'); + ->count('transactions.id') + ; if (0 === $count) { Log::debug(sprintf('Transaction is not reconciled, done with %s', __METHOD__)); @@ -113,7 +114,7 @@ trait GroupValidation 'destination_id', 'destination_name', 'destination_number', - 'destination_iban' + 'destination_iban', ]; // stop protesting when reconciliation is set to FALSE. @@ -171,7 +172,7 @@ trait GroupValidation $data = $validator->getData(); $transactions = $this->getTransactionsArray($validator); - $groupTitle = $data['group_title'] ?? ''; + $groupTitle = $data['group_title'] ?? ''; if ('' === $groupTitle && count($transactions) > 1) { $validator->errors()->add('group_title', (string) trans('validation.group_title_mandatory')); } diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index 90d430b476..6a0925124e 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -45,9 +45,9 @@ trait RecurrenceValidation */ public function valUpdateAccountInfo(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); - $transactionType = $data['type'] ?? 'invalid'; + $transactionType = $data['type'] ?? 'invalid'; // grab model from parameter and try to set the transaction type from it if ('invalid' === $transactionType) { @@ -72,14 +72,14 @@ trait RecurrenceValidation } } - $transactions = $data['transactions'] ?? []; + $transactions = $data['transactions'] ?? []; /** @var AccountValidator $accountValidator */ $accountValidator = app(AccountValidator::class); Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions))); foreach ($transactions as $index => $transaction) { - $transactionType = $transaction['type'] ?? $transactionType; + $transactionType = $transaction['type'] ?? $transactionType; $accountValidator->setTransactionType($transactionType); if ( @@ -91,9 +91,9 @@ trait RecurrenceValidation continue; } // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; - $sourceName = $transaction['source_name'] ?? null; - $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; + $sourceName = $transaction['source_name'] ?? null; + $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); // do something with result: if (false === $validSource) { @@ -267,8 +267,8 @@ trait RecurrenceValidation return; } - $nthDay = (int) $parameters[0]; - $dayOfWeek = (int) $parameters[1]; + $nthDay = (int) $parameters[0]; + $dayOfWeek = (int) $parameters[1]; if ($nthDay < 1 || $nthDay > 5) { $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); @@ -317,15 +317,15 @@ trait RecurrenceValidation return; } - $originalTrCount = $recurrence->recurrenceTransactions()->count(); + $originalTrCount = $recurrence->recurrenceTransactions()->count(); if (1 === $submittedTrCount && 1 === $originalTrCount) { - $first = $transactions[0]; // can safely assume index 0. + $first = $transactions[0]; // can safely assume index 0. if (!array_key_exists('id', $first)) { Log::debug('Single count and no ID, done.'); return; // home safe! } - $id = $first['id']; + $id = $first['id']; if ('' === (string) $id) { Log::debug('Single count and empty ID, done.'); @@ -343,7 +343,7 @@ trait RecurrenceValidation } Log::debug('Multi ID validation.'); - $idsMandatory = false; + $idsMandatory = false; if ($submittedTrCount < $originalTrCount) { Log::debug(sprintf('User submits %d transaction, recurrence has %d transactions. All entries must have ID.', $submittedTrCount, $originalTrCount)); $idsMandatory = true; @@ -360,7 +360,7 @@ trait RecurrenceValidation * 2. If the user submits more transactions than already present, count the number of existing transactions. At least those must be matched. After that, submit as many as you like. * 3. If the user submits the same number of transactions as already present, all but one must have an ID. */ - $unmatchedIds = 0; + $unmatchedIds = 0; foreach ($transactions as $index => $transaction) { Log::debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount)); @@ -390,7 +390,7 @@ trait RecurrenceValidation } } // if too many don't match, but you haven't submitted more than already present: - $maxUnmatched = max(1, $submittedTrCount - $originalTrCount); + $maxUnmatched = max(1, $submittedTrCount - $originalTrCount); Log::debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched)); if ($unmatchedIds > $maxUnmatched) { Log::warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds)); diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index fe82eb95f1..098f72ae4c 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -49,7 +49,7 @@ trait TransactionValidation * * Inclusion of user and/or group is optional. */ - public function validateAccountInformation(Validator $validator, null|User $user = null, null|UserGroup $userGroup = null): void + public function validateAccountInformation(Validator $validator, ?User $user = null, ?UserGroup $userGroup = null): void { if ($validator->errors()->count() > 0) { return; @@ -66,7 +66,7 @@ trait TransactionValidation * @var array $transaction */ foreach ($transactions as $index => $transaction) { - $transaction['user'] = $user; + $transaction['user'] = $user; $transaction['user_group'] = $userGroup; if (!is_int($index)) { continue; @@ -99,7 +99,7 @@ trait TransactionValidation Log::debug(sprintf('Now in validateSingleAccount(%d)', $index)); /** @var AccountValidator $accountValidator */ - $accountValidator = app(AccountValidator::class); + $accountValidator = app(AccountValidator::class); if (array_key_exists('user', $transaction) && null !== $transaction['user']) { $accountValidator->setUser($transaction['user']); @@ -108,16 +108,16 @@ trait TransactionValidation $accountValidator->setUserGroup($transaction['user_group']); } - $transactionType = $transaction['type'] ?? $transactionType; + $transactionType = $transaction['type'] ?? $transactionType; $accountValidator->setTransactionType($transactionType); // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; - $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; - $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; - $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; - $source = ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber]; - $validSource = $accountValidator->validateSource($source); + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; + $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; + $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; + $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; + $source = ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber]; + $validSource = $accountValidator->validateSource($source); // do something with result: if (false === $validSource) { @@ -207,8 +207,8 @@ trait TransactionValidation return; } - $source = $accountValidator->source; - $destination = $accountValidator->destination; + $source = $accountValidator->source; + $destination = $accountValidator->destination; Log::debug(sprintf('Source: #%d "%s (%s)"', $source->id, $source->name, $source->accountType->type)); Log::debug(sprintf('Destination: #%d "%s" (%s)', $destination->id, $destination->name, $destination->accountType->type)); @@ -374,8 +374,8 @@ trait TransactionValidation $accountValidator = app(AccountValidator::class); // 2025-01-29 grab the transaction type from the update array. - $originalType = $this->getTransactionType($transactionGroup, []); - $transactionType = $transaction['type'] ?? $originalType; + $originalType = $this->getTransactionType($transactionGroup, []); + $transactionType = $transaction['type'] ?? $originalType; Log::debug(sprintf('Determined transaction type to be "%s"', $transactionType)); // get the transaction type using the original transaction group: @@ -397,7 +397,7 @@ trait TransactionValidation 'id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, - 'number' => $sourceNumber + 'number' => $sourceNumber, ]); // do something with result: @@ -462,7 +462,7 @@ trait TransactionValidation return $transactions[0]['type'] ?? strtolower((string) $group->transactionJournals()->first()?->transactionType->type); } - private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): null|Account + private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account { if (1 === $transactionGroup->transactionJournals->count()) { $journal = $transactionGroup->transactionJournals->first(); @@ -544,17 +544,17 @@ trait TransactionValidation Log::debug('Now in validateTransactionTypes()'); $transactions = $this->getTransactionsArray($validator); - $types = []; + $types = []; foreach ($transactions as $transaction) { $types[] = $transaction['type'] ?? 'invalid'; } - $unique = array_unique($types); + $unique = array_unique($types); if (count($unique) > 1) { $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); return; } - $first = $unique[0] ?? 'invalid'; + $first = $unique[0] ?? 'invalid'; if ('invalid' === $first) { $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type')); } @@ -571,9 +571,9 @@ trait TransactionValidation foreach ($transactions as $transaction) { $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0)); // if type is not set, fall back to the type of the journal, if one is given. - $types[] = $transaction['type'] ?? $originalType; + $types[] = $transaction['type'] ?? $originalType; } - $unique = array_unique($types); + $unique = array_unique($types); if (count($unique) > 1) { Log::warning('Add error for mismatch transaction types.'); $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); @@ -610,15 +610,15 @@ trait TransactionValidation if (count($transactions) < 2) { return; } - $type = $transactions[0]['type'] ?? 'withdrawal'; - $sources = []; - $dests = []; + $type = $transactions[0]['type'] ?? 'withdrawal'; + $sources = []; + $dests = []; foreach ($transactions as $transaction) { $sources[] = sprintf('%d-%s', $transaction['source_id'] ?? 0, $transaction['source_name'] ?? ''); - $dests[] = sprintf('%d-%s', $transaction['destination_id'] ?? 0, $transaction['destination_name'] ?? ''); + $dests[] = sprintf('%d-%s', $transaction['destination_id'] ?? 0, $transaction['destination_name'] ?? ''); } - $sources = array_unique($sources); - $dests = array_unique($dests); + $sources = array_unique($sources); + $dests = array_unique($dests); switch ($type) { default: @@ -662,15 +662,15 @@ trait TransactionValidation return; } - $type = $this->getTransactionType($transactionGroup, $transactions); + $type = $this->getTransactionType($transactionGroup, $transactions); // compare source IDs, destination IDs, source names and destination names. // I think I can get away with one combination being equal, as long as the rest // of the code picks up on this as well. // either way all fields must be blank or all equal // but if IDs are equal don't bother with the names. - $comparison = $this->collectComparisonData($transactions); - $result = $this->compareAccountData($type, $comparison); + $comparison = $this->collectComparisonData($transactions); + $result = $this->compareAccountData($type, $comparison); if (false === $result) { if ('withdrawal' === $type) { $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); @@ -699,7 +699,7 @@ trait TransactionValidation /** @var array $transaction */ foreach ($transactions as $transaction) { // source or destination may be omitted. If this is the case, use the original source / destination name + ID. - $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0)); + $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0)); // get field. $comparison[$field][] = $transaction[$field] ?? $originalData[$field]; @@ -711,18 +711,19 @@ trait TransactionValidation private function getOriginalData(int $journalId): array { - $return = ['source_id' => 0, 'source_name' => '', 'destination_id' => 0, 'destination_name' => '']; + $return = ['source_id' => 0, 'source_name' => '', 'destination_id' => 0, 'destination_name' => '']; if (0 === $journalId) { return $return; } /** @var null|Transaction $source */ - $source = Transaction::where('transaction_journal_id', $journalId) + $source = Transaction::where('transaction_journal_id', $journalId) ->where('amount', '<', 0) ->with(['account']) - ->first(); + ->first() + ; if (null !== $source) { - $return['source_id'] = $source->account_id; + $return['source_id'] = $source->account_id; $return['source_name'] = $source->account->name; } @@ -730,9 +731,10 @@ trait TransactionValidation $destination = Transaction::where('transaction_journal_id', $journalId) ->where('amount', '>', 0) ->with(['account']) - ->first(); + ->first() + ; if (null !== $destination) { - $return['destination_id'] = $destination->account_id; + $return['destination_id'] = $destination->account_id; $return['destination_name'] = $destination->account->name; } @@ -742,8 +744,8 @@ trait TransactionValidation private function compareAccountData(string $type, array $comparison): bool { return match ($type) { - default => $this->compareAccountDataWithdrawal($comparison), - 'deposit' => $this->compareAccountDataDeposit($comparison), + default => $this->compareAccountDataWithdrawal($comparison), + 'deposit' => $this->compareAccountDataDeposit($comparison), 'transfer' => $this->compareAccountDataTransfer($comparison) }; } diff --git a/composer.lock b/composer.lock index 9432a6ee1a..e8a00540c6 100644 --- a/composer.lock +++ b/composer.lock @@ -10079,16 +10079,16 @@ "packages-dev": [ { "name": "barryvdh/laravel-debugbar", - "version": "v3.16.3", + "version": "v3.16.4", "source": { "type": "git", "url": "https://github.com/fruitcake/laravel-debugbar.git", - "reference": "c91e57ea113edd6526f5b8cd6b1c6ee02c67b28e" + "reference": "8c24feb48f26c830c433abf3f98947d828c7ed29" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/fruitcake/laravel-debugbar/zipball/c91e57ea113edd6526f5b8cd6b1c6ee02c67b28e", - "reference": "c91e57ea113edd6526f5b8cd6b1c6ee02c67b28e", + "url": "https://api.github.com/repos/fruitcake/laravel-debugbar/zipball/8c24feb48f26c830c433abf3f98947d828c7ed29", + "reference": "8c24feb48f26c830c433abf3f98947d828c7ed29", "shasum": "" }, "require": { @@ -10148,7 +10148,7 @@ ], "support": { "issues": "https://github.com/fruitcake/laravel-debugbar/issues", - "source": "https://github.com/fruitcake/laravel-debugbar/tree/v3.16.3" + "source": "https://github.com/fruitcake/laravel-debugbar/tree/v3.16.4" }, "funding": [ { @@ -10160,7 +10160,7 @@ "type": "github" } ], - "time": "2025-12-23T17:37:00+00:00" + "time": "2026-01-23T10:40:24+00:00" }, { "name": "barryvdh/laravel-ide-helper", diff --git a/config/firefly.php b/config/firefly.php index bb4d08777f..324e230fa0 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -78,8 +78,8 @@ return [ 'running_balance_column' => (bool)envNonEmpty('USE_RUNNING_BALANCE', true), // this is only the default value, is not used. // see cer.php for exchange rates feature flag. ], - 'version' => 'develop/2026-01-21', - 'build_time' => 1769021100, + 'version' => 'develop/2026-01-23', + 'build_time' => 1769177534, 'api_version' => '2.1.0', // field is no longer used. 'db_version' => 28, // field is no longer used. diff --git a/package-lock.json b/package-lock.json index 7b89f2cabc..d17b7fbaaf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2272,9 +2272,9 @@ } }, "node_modules/@parcel/watcher": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.4.tgz", - "integrity": "sha512-WYa2tUVV5HiArWPB3ydlOc4R2ivq0IDrlqhMi3l7mVsFEXNcTfxYFPIHXHXIh/ca/y/V5N4E1zecyxdIBjYnkQ==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz", + "integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -2293,25 +2293,25 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "@parcel/watcher-android-arm64": "2.5.4", - "@parcel/watcher-darwin-arm64": "2.5.4", - "@parcel/watcher-darwin-x64": "2.5.4", - "@parcel/watcher-freebsd-x64": "2.5.4", - "@parcel/watcher-linux-arm-glibc": "2.5.4", - "@parcel/watcher-linux-arm-musl": "2.5.4", - "@parcel/watcher-linux-arm64-glibc": "2.5.4", - "@parcel/watcher-linux-arm64-musl": "2.5.4", - "@parcel/watcher-linux-x64-glibc": "2.5.4", - "@parcel/watcher-linux-x64-musl": "2.5.4", - "@parcel/watcher-win32-arm64": "2.5.4", - "@parcel/watcher-win32-ia32": "2.5.4", - "@parcel/watcher-win32-x64": "2.5.4" + "@parcel/watcher-android-arm64": "2.5.6", + "@parcel/watcher-darwin-arm64": "2.5.6", + "@parcel/watcher-darwin-x64": "2.5.6", + "@parcel/watcher-freebsd-x64": "2.5.6", + "@parcel/watcher-linux-arm-glibc": "2.5.6", + "@parcel/watcher-linux-arm-musl": "2.5.6", + "@parcel/watcher-linux-arm64-glibc": "2.5.6", + "@parcel/watcher-linux-arm64-musl": "2.5.6", + "@parcel/watcher-linux-x64-glibc": "2.5.6", + "@parcel/watcher-linux-x64-musl": "2.5.6", + "@parcel/watcher-win32-arm64": "2.5.6", + "@parcel/watcher-win32-ia32": "2.5.6", + "@parcel/watcher-win32-x64": "2.5.6" } }, "node_modules/@parcel/watcher-android-arm64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.4.tgz", - "integrity": "sha512-hoh0vx4v+b3BNI7Cjoy2/B0ARqcwVNrzN/n7DLq9ZB4I3lrsvhrkCViJyfTj/Qi5xM9YFiH4AmHGK6pgH1ss7g==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.6.tgz", + "integrity": "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==", "cpu": [ "arm64" ], @@ -2330,9 +2330,9 @@ } }, "node_modules/@parcel/watcher-darwin-arm64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.4.tgz", - "integrity": "sha512-kphKy377pZiWpAOyTgQYPE5/XEKVMaj6VUjKT5VkNyUJlr2qZAn8gIc7CPzx+kbhvqHDT9d7EqdOqRXT6vk0zw==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.6.tgz", + "integrity": "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==", "cpu": [ "arm64" ], @@ -2351,9 +2351,9 @@ } }, "node_modules/@parcel/watcher-darwin-x64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.4.tgz", - "integrity": "sha512-UKaQFhCtNJW1A9YyVz3Ju7ydf6QgrpNQfRZ35wNKUhTQ3dxJ/3MULXN5JN/0Z80V/KUBDGa3RZaKq1EQT2a2gg==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.6.tgz", + "integrity": "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==", "cpu": [ "x64" ], @@ -2372,9 +2372,9 @@ } }, "node_modules/@parcel/watcher-freebsd-x64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.4.tgz", - "integrity": "sha512-Dib0Wv3Ow/m2/ttvLdeI2DBXloO7t3Z0oCp4bAb2aqyqOjKPPGrg10pMJJAQ7tt8P4V2rwYwywkDhUia/FgS+Q==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.6.tgz", + "integrity": "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==", "cpu": [ "x64" ], @@ -2393,9 +2393,9 @@ } }, "node_modules/@parcel/watcher-linux-arm-glibc": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.4.tgz", - "integrity": "sha512-I5Vb769pdf7Q7Sf4KNy8Pogl/URRCKu9ImMmnVKYayhynuyGYMzuI4UOWnegQNa2sGpsPSbzDsqbHNMyeyPCgw==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.6.tgz", + "integrity": "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==", "cpu": [ "arm" ], @@ -2414,9 +2414,9 @@ } }, "node_modules/@parcel/watcher-linux-arm-musl": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.4.tgz", - "integrity": "sha512-kGO8RPvVrcAotV4QcWh8kZuHr9bXi9a3bSZw7kFarYR0+fGliU7hd/zevhjw8fnvIKG3J9EO5G6sXNGCSNMYPQ==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.6.tgz", + "integrity": "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==", "cpu": [ "arm" ], @@ -2435,9 +2435,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-glibc": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.4.tgz", - "integrity": "sha512-KU75aooXhqGFY2W5/p8DYYHt4hrjHZod8AhcGAmhzPn/etTa+lYCDB2b1sJy3sWJ8ahFVTdy+EbqSBvMx3iFlw==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.6.tgz", + "integrity": "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==", "cpu": [ "arm64" ], @@ -2456,9 +2456,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-musl": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.4.tgz", - "integrity": "sha512-Qx8uNiIekVutnzbVdrgSanM+cbpDD3boB1f8vMtnuG5Zau4/bdDbXyKwIn0ToqFhIuob73bcxV9NwRm04/hzHQ==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.6.tgz", + "integrity": "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==", "cpu": [ "arm64" ], @@ -2477,9 +2477,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-glibc": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.4.tgz", - "integrity": "sha512-UYBQvhYmgAv61LNUn24qGQdjtycFBKSK3EXr72DbJqX9aaLbtCOO8+1SkKhD/GNiJ97ExgcHBrukcYhVjrnogA==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.6.tgz", + "integrity": "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==", "cpu": [ "x64" ], @@ -2498,9 +2498,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-musl": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.4.tgz", - "integrity": "sha512-YoRWCVgxv8akZrMhdyVi6/TyoeeMkQ0PGGOf2E4omODrvd1wxniXP+DBynKoHryStks7l+fDAMUBRzqNHrVOpg==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.6.tgz", + "integrity": "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==", "cpu": [ "x64" ], @@ -2519,9 +2519,9 @@ } }, "node_modules/@parcel/watcher-win32-arm64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.4.tgz", - "integrity": "sha512-iby+D/YNXWkiQNYcIhg8P5hSjzXEHaQrk2SLrWOUD7VeC4Ohu0WQvmV+HDJokZVJ2UjJ4AGXW3bx7Lls9Ln4TQ==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.6.tgz", + "integrity": "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==", "cpu": [ "arm64" ], @@ -2540,9 +2540,9 @@ } }, "node_modules/@parcel/watcher-win32-ia32": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.4.tgz", - "integrity": "sha512-vQN+KIReG0a2ZDpVv8cgddlf67J8hk1WfZMMP7sMeZmJRSmEax5xNDNWKdgqSe2brOKTQQAs3aCCUal2qBHAyg==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.6.tgz", + "integrity": "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==", "cpu": [ "ia32" ], @@ -2561,9 +2561,9 @@ } }, "node_modules/@parcel/watcher-win32-x64": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.4.tgz", - "integrity": "sha512-3A6efb6BOKwyw7yk9ro2vus2YTt2nvcd56AuzxdMiVOxL9umDyN5PKkKfZ/gZ9row41SjVmTVQNWQhaRRGpOKw==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.6.tgz", + "integrity": "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==", "cpu": [ "x64" ], @@ -2606,9 +2606,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.55.3.tgz", - "integrity": "sha512-qyX8+93kK/7R5BEXPC2PjUt0+fS/VO2BVHjEHyIEWiYn88rcRBHmdLgoJjktBltgAf+NY7RfCGB1SoyKS/p9kg==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.56.0.tgz", + "integrity": "sha512-LNKIPA5k8PF1+jAFomGe3qN3bbIgJe/IlpDBwuVjrDKrJhVWywgnJvflMt/zkbVNLFtF1+94SljYQS6e99klnw==", "cpu": [ "arm" ], @@ -2620,9 +2620,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.55.3.tgz", - "integrity": "sha512-6sHrL42bjt5dHQzJ12Q4vMKfN+kUnZ0atHHnv4V0Wd9JMTk7FDzSY35+7qbz3ypQYMBPANbpGK7JpnWNnhGt8g==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.56.0.tgz", + "integrity": "sha512-lfbVUbelYqXlYiU/HApNMJzT1E87UPGvzveGg2h0ktUNlOCxKlWuJ9jtfvs1sKHdwU4fzY7Pl8sAl49/XaEk6Q==", "cpu": [ "arm64" ], @@ -2634,9 +2634,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.55.3.tgz", - "integrity": "sha512-1ht2SpGIjEl2igJ9AbNpPIKzb1B5goXOcmtD0RFxnwNuMxqkR6AUaaErZz+4o+FKmzxcSNBOLrzsICZVNYa1Rw==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.56.0.tgz", + "integrity": "sha512-EgxD1ocWfhoD6xSOeEEwyE7tDvwTgZc8Bss7wCWe+uc7wO8G34HHCUH+Q6cHqJubxIAnQzAsyUsClt0yFLu06w==", "cpu": [ "arm64" ], @@ -2648,9 +2648,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.55.3.tgz", - "integrity": "sha512-FYZ4iVunXxtT+CZqQoPVwPhH7549e/Gy7PIRRtq4t5f/vt54pX6eG9ebttRH6QSH7r/zxAFA4EZGlQ0h0FvXiA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.56.0.tgz", + "integrity": "sha512-1vXe1vcMOssb/hOF8iv52A7feWW2xnu+c8BV4t1F//m9QVLTfNVpEdja5ia762j/UEJe2Z1jAmEqZAK42tVW3g==", "cpu": [ "x64" ], @@ -2662,9 +2662,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.55.3.tgz", - "integrity": "sha512-M/mwDCJ4wLsIgyxv2Lj7Len+UMHd4zAXu4GQ2UaCdksStglWhP61U3uowkaYBQBhVoNpwx5Hputo8eSqM7K82Q==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.56.0.tgz", + "integrity": "sha512-bof7fbIlvqsyv/DtaXSck4VYQ9lPtoWNFCB/JY4snlFuJREXfZnm+Ej6yaCHfQvofJDXLDMTVxWscVSuQvVWUQ==", "cpu": [ "arm64" ], @@ -2676,9 +2676,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.55.3.tgz", - "integrity": "sha512-5jZT2c7jBCrMegKYTYTpni8mg8y3uY8gzeq2ndFOANwNuC/xJbVAoGKR9LhMDA0H3nIhvaqUoBEuJoICBudFrA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.56.0.tgz", + "integrity": "sha512-KNa6lYHloW+7lTEkYGa37fpvPq+NKG/EHKM8+G/g9WDU7ls4sMqbVRV78J6LdNuVaeeK5WB9/9VAFbKxcbXKYg==", "cpu": [ "x64" ], @@ -2690,9 +2690,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.55.3.tgz", - "integrity": "sha512-YeGUhkN1oA+iSPzzhEjVPS29YbViOr8s4lSsFaZKLHswgqP911xx25fPOyE9+khmN6W4VeM0aevbDp4kkEoHiA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.56.0.tgz", + "integrity": "sha512-E8jKK87uOvLrrLN28jnAAAChNq5LeCd2mGgZF+fGF5D507WlG/Noct3lP/QzQ6MrqJ5BCKNwI9ipADB6jyiq2A==", "cpu": [ "arm" ], @@ -2704,9 +2704,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.55.3.tgz", - "integrity": "sha512-eo0iOIOvcAlWB3Z3eh8pVM8hZ0oVkK3AjEM9nSrkSug2l15qHzF3TOwT0747omI6+CJJvl7drwZepT+re6Fy/w==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.56.0.tgz", + "integrity": "sha512-jQosa5FMYF5Z6prEpTCCmzCXz6eKr/tCBssSmQGEeozA9tkRUty/5Vx06ibaOP9RCrW1Pvb8yp3gvZhHwTDsJw==", "cpu": [ "arm" ], @@ -2718,9 +2718,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.55.3.tgz", - "integrity": "sha512-DJay3ep76bKUDImmn//W5SvpjRN5LmK/ntWyeJs/dcnwiiHESd3N4uteK9FDLf0S0W8E6Y0sVRXpOCoQclQqNg==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.56.0.tgz", + "integrity": "sha512-uQVoKkrC1KGEV6udrdVahASIsaF8h7iLG0U0W+Xn14ucFwi6uS539PsAr24IEF9/FoDtzMeeJXJIBo5RkbNWvQ==", "cpu": [ "arm64" ], @@ -2732,9 +2732,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.55.3.tgz", - "integrity": "sha512-BKKWQkY2WgJ5MC/ayvIJTHjy0JUGb5efaHCUiG/39sSUvAYRBaO3+/EK0AZT1RF3pSj86O24GLLik9mAYu0IJg==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.56.0.tgz", + "integrity": "sha512-vLZ1yJKLxhQLFKTs42RwTwa6zkGln+bnXc8ueFGMYmBTLfNu58sl5/eXyxRa2RarTkJbXl8TKPgfS6V5ijNqEA==", "cpu": [ "arm64" ], @@ -2746,9 +2746,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.55.3.tgz", - "integrity": "sha512-Q9nVlWtKAG7ISW80OiZGxTr6rYtyDSkauHUtvkQI6TNOJjFvpj4gcH+KaJihqYInnAzEEUetPQubRwHef4exVg==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.56.0.tgz", + "integrity": "sha512-FWfHOCub564kSE3xJQLLIC/hbKqHSVxy8vY75/YHHzWvbJL7aYJkdgwD/xGfUlL5UV2SB7otapLrcCj2xnF1dg==", "cpu": [ "loong64" ], @@ -2760,9 +2760,9 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.55.3.tgz", - "integrity": "sha512-2H5LmhzrpC4fFRNwknzmmTvvyJPHwESoJgyReXeFoYYuIDfBhP29TEXOkCJE/KxHi27mj7wDUClNq78ue3QEBQ==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.56.0.tgz", + "integrity": "sha512-z1EkujxIh7nbrKL1lmIpqFTc/sr0u8Uk0zK/qIEFldbt6EDKWFk/pxFq3gYj4Bjn3aa9eEhYRlL3H8ZbPT1xvA==", "cpu": [ "loong64" ], @@ -2774,9 +2774,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.55.3.tgz", - "integrity": "sha512-9S542V0ie9LCTznPYlvaeySwBeIEa7rDBgLHKZ5S9DBgcqdJYburabm8TqiqG6mrdTzfV5uttQRHcbKff9lWtA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.56.0.tgz", + "integrity": "sha512-iNFTluqgdoQC7AIE8Q34R3AuPrJGJirj5wMUErxj22deOcY7XwZRaqYmB6ZKFHoVGqRcRd0mqO+845jAibKCkw==", "cpu": [ "ppc64" ], @@ -2788,9 +2788,9 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.55.3.tgz", - "integrity": "sha512-ukxw+YH3XXpcezLgbJeasgxyTbdpnNAkrIlFGDl7t+pgCxZ89/6n1a+MxlY7CegU+nDgrgdqDelPRNQ/47zs0g==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.56.0.tgz", + "integrity": "sha512-MtMeFVlD2LIKjp2sE2xM2slq3Zxf9zwVuw0jemsxvh1QOpHSsSzfNOTH9uYW9i1MXFxUSMmLpeVeUzoNOKBaWg==", "cpu": [ "ppc64" ], @@ -2802,9 +2802,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.55.3.tgz", - "integrity": "sha512-Iauw9UsTTvlF++FhghFJjqYxyXdggXsOqGpFBylaRopVpcbfyIIsNvkf9oGwfgIcf57z3m8+/oSYTo6HutBFNw==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.56.0.tgz", + "integrity": "sha512-in+v6wiHdzzVhYKXIk5U74dEZHdKN9KH0Q4ANHOTvyXPG41bajYRsy7a8TPKbYPl34hU7PP7hMVHRvv/5aCSew==", "cpu": [ "riscv64" ], @@ -2816,9 +2816,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.55.3.tgz", - "integrity": "sha512-3OqKAHSEQXKdq9mQ4eajqUgNIK27VZPW3I26EP8miIzuKzCJ3aW3oEn2pzF+4/Hj/Moc0YDsOtBgT5bZ56/vcA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.56.0.tgz", + "integrity": "sha512-yni2raKHB8m9NQpI9fPVwN754mn6dHQSbDTwxdr9SE0ks38DTjLMMBjrwvB5+mXrX+C0npX0CVeCUcvvvD8CNQ==", "cpu": [ "riscv64" ], @@ -2830,9 +2830,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.55.3.tgz", - "integrity": "sha512-0CM8dSVzVIaqMcXIFej8zZrSFLnGrAE8qlNbbHfTw1EEPnFTg1U1ekI0JdzjPyzSfUsHWtodilQQG/RA55berA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.56.0.tgz", + "integrity": "sha512-zhLLJx9nQPu7wezbxt2ut+CI4YlXi68ndEve16tPc/iwoylWS9B3FxpLS2PkmfYgDQtosah07Mj9E0khc3Y+vQ==", "cpu": [ "s390x" ], @@ -2844,9 +2844,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.55.3.tgz", - "integrity": "sha512-+fgJE12FZMIgBaKIAGd45rxf+5ftcycANJRWk8Vz0NnMTM5rADPGuRFTYar+Mqs560xuART7XsX2lSACa1iOmQ==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.56.0.tgz", + "integrity": "sha512-MVC6UDp16ZSH7x4rtuJPAEoE1RwS8N4oK9DLHy3FTEdFoUTCFVzMfJl/BVJ330C+hx8FfprA5Wqx4FhZXkj2Kw==", "cpu": [ "x64" ], @@ -2858,9 +2858,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.55.3.tgz", - "integrity": "sha512-tMD7NnbAolWPzQlJQJjVFh/fNH3K/KnA7K8gv2dJWCwwnaK6DFCYST1QXYWfu5V0cDwarWC8Sf/cfMHniNq21A==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.56.0.tgz", + "integrity": "sha512-ZhGH1eA4Qv0lxaV00azCIS1ChedK0V32952Md3FtnxSqZTBTd6tgil4nZT5cU8B+SIw3PFYkvyR4FKo2oyZIHA==", "cpu": [ "x64" ], @@ -2872,9 +2872,9 @@ ] }, "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.55.3.tgz", - "integrity": "sha512-u5KsqxOxjEeIbn7bUK1MPM34jrnPwjeqgyin4/N6e/KzXKfpE9Mi0nCxcQjaM9lLmPcHmn/xx1yOjgTMtu1jWQ==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.56.0.tgz", + "integrity": "sha512-O16XcmyDeFI9879pEcmtWvD/2nyxR9mF7Gs44lf1vGGx8Vg2DRNx11aVXBEqOQhWb92WN4z7fW/q4+2NYzCbBA==", "cpu": [ "x64" ], @@ -2886,9 +2886,9 @@ ] }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.55.3.tgz", - "integrity": "sha512-vo54aXwjpTtsAnb3ca7Yxs9t2INZg7QdXN/7yaoG7nPGbOBXYXQY41Km+S1Ov26vzOAzLcAjmMdjyEqS1JkVhw==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.56.0.tgz", + "integrity": "sha512-LhN/Reh+7F3RCgQIRbgw8ZMwUwyqJM+8pXNT6IIJAqm2IdKkzpCh/V9EdgOMBKuebIrzswqy4ATlrDgiOwbRcQ==", "cpu": [ "arm64" ], @@ -2900,9 +2900,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.55.3.tgz", - "integrity": "sha512-HI+PIVZ+m+9AgpnY3pt6rinUdRYrGHvmVdsNQ4odNqQ/eRF78DVpMR7mOq7nW06QxpczibwBmeQzB68wJ+4W4A==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.56.0.tgz", + "integrity": "sha512-kbFsOObXp3LBULg1d3JIUQMa9Kv4UitDmpS+k0tinPBz3watcUiV2/LUDMMucA6pZO3WGE27P7DsfaN54l9ing==", "cpu": [ "arm64" ], @@ -2914,9 +2914,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.55.3.tgz", - "integrity": "sha512-vRByotbdMo3Wdi+8oC2nVxtc3RkkFKrGaok+a62AT8lz/YBuQjaVYAS5Zcs3tPzW43Vsf9J0wehJbUY5xRSekA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.56.0.tgz", + "integrity": "sha512-vSSgny54D6P4vf2izbtFm/TcWYedw7f8eBrOiGGecyHyQB9q4Kqentjaj8hToe+995nob/Wv48pDqL5a62EWtg==", "cpu": [ "ia32" ], @@ -2928,9 +2928,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.55.3.tgz", - "integrity": "sha512-POZHq7UeuzMJljC5NjKi8vKMFN6/5EOqcX1yGntNLp7rUTpBAXQ1hW8kWPFxYLv07QMcNM75xqVLGPWQq6TKFA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.56.0.tgz", + "integrity": "sha512-FeCnkPCTHQJFbiGG49KjV5YGW/8b9rrXAM2Mz2kiIoktq2qsJxRD5giEMEOD2lPdgs72upzefaUvS+nc8E3UzQ==", "cpu": [ "x64" ], @@ -2942,9 +2942,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.55.3.tgz", - "integrity": "sha512-aPFONczE4fUFKNXszdvnd2GqKEYQdV5oEsIbKPujJmWlCI9zEsv1Otig8RKK+X9bed9gFUN6LAeN4ZcNuu4zjg==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.56.0.tgz", + "integrity": "sha512-H8AE9Ur/t0+1VXujj90w0HrSOuv0Nq9r1vSZF2t5km20NTfosQsGGUXDaKdQZzwuLts7IyL1fYT4hM95TI9c4g==", "cpu": [ "x64" ], @@ -3232,9 +3232,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "25.0.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.9.tgz", - "integrity": "sha512-/rpCXHlCWeqClNBwUhDcusJxXYDjZTyE8v5oTO7WbL8eij2nKhUeU89/6xgjU7N4/Vh3He0BtyhJdQbDyhiXAw==", + "version": "25.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.10.tgz", + "integrity": "sha512-zWW5KPngR/yvakJgGOmZ5vTBemDoSqF3AcV/LrO5u5wTWyEAVVh+IT39G4gtyAkh3CtTZs8aX/yRM82OfzHJRg==", "dev": true, "license": "MIT", "dependencies": { @@ -4564,9 +4564,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001765", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001765.tgz", - "integrity": "sha512-LWcNtSyZrakjECqmpP4qdg0MMGdN368D7X8XvvAqOcqMv0RxnlqVKZl2V6/mBR68oYMxOZPLw/gO7DuisMHUvQ==", + "version": "1.0.30001766", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001766.tgz", + "integrity": "sha512-4C0lfJ0/YPjJQHagaE9x2Elb69CIqEPZeG0anQt9SIvIoOH4a4uaRl73IavyO+0qZh6MDLH//DrXThEYKHkmYA==", "dev": true, "funding": [ { @@ -5769,9 +5769,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.267", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", - "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "version": "1.5.278", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.278.tgz", + "integrity": "sha512-dQ0tM1svDRQOwxnXxm+twlGTjr9Upvt8UFWAgmLsxEzFQxhbti4VwxmMjsDxVC51Zo84swW7FVCXEV+VAkhuPw==", "dev": true, "license": "ISC" }, @@ -10089,9 +10089,9 @@ } }, "node_modules/rollup": { - "version": "4.55.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.55.3.tgz", - "integrity": "sha512-y9yUpfQvetAjiDLtNMf1hL9NXchIJgWt6zIKeoB+tCd3npX08Eqfzg60V9DhIGVMtQ0AlMkFw5xa+AQ37zxnAA==", + "version": "4.56.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.56.0.tgz", + "integrity": "sha512-9FwVqlgUHzbXtDg9RCMgodF3Ua4Na6Gau+Sdt9vyCN4RhHfVKX2DCHy3BjMLTDd47ITDhYAnTwGulWTblJSDLg==", "dev": true, "license": "MIT", "dependencies": { @@ -10105,31 +10105,31 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.55.3", - "@rollup/rollup-android-arm64": "4.55.3", - "@rollup/rollup-darwin-arm64": "4.55.3", - "@rollup/rollup-darwin-x64": "4.55.3", - "@rollup/rollup-freebsd-arm64": "4.55.3", - "@rollup/rollup-freebsd-x64": "4.55.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.55.3", - "@rollup/rollup-linux-arm-musleabihf": "4.55.3", - "@rollup/rollup-linux-arm64-gnu": "4.55.3", - "@rollup/rollup-linux-arm64-musl": "4.55.3", - "@rollup/rollup-linux-loong64-gnu": "4.55.3", - "@rollup/rollup-linux-loong64-musl": "4.55.3", - "@rollup/rollup-linux-ppc64-gnu": "4.55.3", - "@rollup/rollup-linux-ppc64-musl": "4.55.3", - "@rollup/rollup-linux-riscv64-gnu": "4.55.3", - "@rollup/rollup-linux-riscv64-musl": "4.55.3", - "@rollup/rollup-linux-s390x-gnu": "4.55.3", - "@rollup/rollup-linux-x64-gnu": "4.55.3", - "@rollup/rollup-linux-x64-musl": "4.55.3", - "@rollup/rollup-openbsd-x64": "4.55.3", - "@rollup/rollup-openharmony-arm64": "4.55.3", - "@rollup/rollup-win32-arm64-msvc": "4.55.3", - "@rollup/rollup-win32-ia32-msvc": "4.55.3", - "@rollup/rollup-win32-x64-gnu": "4.55.3", - "@rollup/rollup-win32-x64-msvc": "4.55.3", + "@rollup/rollup-android-arm-eabi": "4.56.0", + "@rollup/rollup-android-arm64": "4.56.0", + "@rollup/rollup-darwin-arm64": "4.56.0", + "@rollup/rollup-darwin-x64": "4.56.0", + "@rollup/rollup-freebsd-arm64": "4.56.0", + "@rollup/rollup-freebsd-x64": "4.56.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.56.0", + "@rollup/rollup-linux-arm-musleabihf": "4.56.0", + "@rollup/rollup-linux-arm64-gnu": "4.56.0", + "@rollup/rollup-linux-arm64-musl": "4.56.0", + "@rollup/rollup-linux-loong64-gnu": "4.56.0", + "@rollup/rollup-linux-loong64-musl": "4.56.0", + "@rollup/rollup-linux-ppc64-gnu": "4.56.0", + "@rollup/rollup-linux-ppc64-musl": "4.56.0", + "@rollup/rollup-linux-riscv64-gnu": "4.56.0", + "@rollup/rollup-linux-riscv64-musl": "4.56.0", + "@rollup/rollup-linux-s390x-gnu": "4.56.0", + "@rollup/rollup-linux-x64-gnu": "4.56.0", + "@rollup/rollup-linux-x64-musl": "4.56.0", + "@rollup/rollup-openbsd-x64": "4.56.0", + "@rollup/rollup-openharmony-arm64": "4.56.0", + "@rollup/rollup-win32-arm64-msvc": "4.56.0", + "@rollup/rollup-win32-ia32-msvc": "4.56.0", + "@rollup/rollup-win32-x64-gnu": "4.56.0", + "@rollup/rollup-win32-x64-msvc": "4.56.0", "fsevents": "~2.3.2" } }, @@ -10185,9 +10185,9 @@ "license": "MIT" }, "node_modules/sass": { - "version": "1.97.2", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.97.2.tgz", - "integrity": "sha512-y5LWb0IlbO4e97Zr7c3mlpabcbBtS+ieiZ9iwDooShpFKWXf62zz5pEPdwrLYm+Bxn1fnbwFGzHuCLSA9tBmrw==", + "version": "1.97.3", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.97.3.tgz", + "integrity": "sha512-fDz1zJpd5GycprAbu4Q2PV/RprsRtKC/0z82z0JLgdytmcq0+ujJbJ/09bPGDxCLkKY3Np5cRAOcWiVkLXJURg==", "dev": true, "license": "MIT", "dependencies": { @@ -10340,22 +10340,26 @@ } }, "node_modules/serve-index": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", - "integrity": "sha512-pXHfKNP4qujrtteMrSBb0rc8HJ9Ms/GrXwcUtUtD5s4ewDJI8bT3Cz2zTVRMKtri49pLx2e0Ya8ziP5Ya2pZZw==", + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.2.tgz", + "integrity": "sha512-KDj11HScOaLmrPxl70KYNW1PksP4Nb/CLL2yvC+Qd2kHMPEEpfc4Re2e4FOay+bC/+XQl/7zAcWON3JVo5v3KQ==", "dev": true, "license": "MIT", "dependencies": { - "accepts": "~1.3.4", + "accepts": "~1.3.8", "batch": "0.6.1", "debug": "2.6.9", "escape-html": "~1.0.3", - "http-errors": "~1.6.2", - "mime-types": "~2.1.17", - "parseurl": "~1.3.2" + "http-errors": "~1.8.0", + "mime-types": "~2.1.35", + "parseurl": "~1.3.3" }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/serve-index/node_modules/debug": { @@ -10379,28 +10383,22 @@ } }, "node_modules/serve-index/node_modules/http-errors": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", - "integrity": "sha512-lks+lVC8dgGyh97jxvxeYTWQFvh4uw4yC12gVl63Cg30sjPX4wuGcdkICVXDAESr6OJGjqGA8Iz5mkeN6zlD7A==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", "dev": true, "license": "MIT", "dependencies": { "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.0", - "statuses": ">= 1.4.0 < 2" + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" }, "engines": { "node": ">= 0.6" } }, - "node_modules/serve-index/node_modules/inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", - "dev": true, - "license": "ISC" - }, "node_modules/serve-index/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", @@ -10408,13 +10406,6 @@ "dev": true, "license": "MIT" }, - "node_modules/serve-index/node_modules/setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", - "dev": true, - "license": "ISC" - }, "node_modules/serve-index/node_modules/statuses": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", diff --git a/resources/assets/v1/src/locales/id.json b/resources/assets/v1/src/locales/id.json index f291279b53..d3bfe042f0 100644 --- a/resources/assets/v1/src/locales/id.json +++ b/resources/assets/v1/src/locales/id.json @@ -22,8 +22,8 @@ "not_enough_currencies": "Not enough currencies", "not_enough_currencies_enabled": "Jika Anda hanya mengaktifkan satu mata uang, tidak perlu menambahkan nilai tukar.", "transaction_stored_link": "Transaction #{ID} (\"{title}\")<\/a> has been stored.", - "webhook_stored_link": "Webhook #{ID} (\"{title}\")<\/a> has been stored.", - "webhook_updated_link": "Webhook #{ID}<\/a> (\"{title}\") has been updated.", + "webhook_stored_link": "Webhook #{ID} (\"{title}\")<\/a> telah disimpan.", + "webhook_updated_link": "Webhook #{ID}<\/a> (\"{title}\") telah diperbarui.", "transaction_updated_link": "Transaction #{ID}<\/a> (\"{title}\") has been updated.", "transaction_new_stored_link": "Transaction #{ID}<\/a> has been stored.", "transaction_journal_information": "Informasi transaksi", @@ -32,9 +32,9 @@ "fire_webhooks_checkbox": "Fire webhooks", "no_budget_pointer": "Anda tampaknya belum memiliki anggaran. Anda harus membuat beberapa di halaman-anggaran<\/a>. Anggaran dapat membantu anda melacak pengeluaran.", "no_bill_pointer": "Sepertinya Anda belum memiliki langganan. Buat beberapa di halaman Langganan<\/a>. Langganan dapat membantu Anda melacak pengeluaran.", - "source_account": "Akun sumber", + "source_account": "Rekening sumber", "hidden_fields_preferences": "You can enable more transaction options in your preferences<\/a>.", - "destination_account": "Akun tujuan", + "destination_account": "Rekening tujuan", "add_another_split": "Tambahkan perpecahan lagi", "submission": "Submission", "stored_journal": "Berhasil membuat transaksi baru \":description\"", @@ -46,7 +46,7 @@ "is_reconciled_fields_dropped": "Because this transaction is reconciled, you will not be able to update the accounts, nor the amount(s) unless you remove the reconciliation flag.", "tags": "Tag", "no_budget": "(no budget)", - "no_bill": "(no subscription)", + "no_bill": "(tidak ada langganan)", "category": "Kategori", "attachments": "Lampiran", "notes": "Notes", @@ -60,9 +60,9 @@ "description": "Deskripsi", "split_transaction_title_help": "If you create a split transaction, there must be a global description for all splits of the transaction.", "destination_account_reconciliation": "Anda tidak dapat mengubah rekening tujuan pada transaksi rekonsiliasi.", - "source_account_reconciliation": "Anda tidak dapat mengedit akun sumber dari transaksi rekonsiliasi.", + "source_account_reconciliation": "Anda tidak dapat mengubah rekening sumber dari transaksi rekonsiliasi.", "budget": "Anggaran", - "bill": "Subscription", + "bill": "Langganan", "you_create_withdrawal": "You're creating a withdrawal.", "you_create_transfer": "You're creating a transfer.", "you_create_deposit": "You're creating a deposit.", @@ -122,30 +122,30 @@ "webhook_delivery_JSON": "JSON", "actions": "Tindakan", "meta_data": "Data meta", - "webhook_messages": "Webhook message", + "webhook_messages": "Pesan webhook", "inactive": "Tidak-aktif", "no_webhook_messages": "Tidak ada pesan webhook.", "inspect": "Periksa", - "create_new_webhook": "Create new webhook", + "create_new_webhook": "Buat webhook baru", "webhooks": "Webhooks", - "webhook_trigger_form_help": "Indicate on what event the webhook will trigger", - "webhook_response_form_help": "Indicate what the webhook must submit to the URL.", - "webhook_delivery_form_help": "Which format the webhook must deliver data in.", - "webhook_active_form_help": "The webhook must be active or it won't be called.", + "webhook_trigger_form_help": "Menunjukkan peristiwa yang memicu webhook", + "webhook_response_form_help": "Menunjukkan apa yang harus dikirimkan webhook ke URL.", + "webhook_delivery_form_help": "Format data yang harus digunakan webhook saat mengirimkan data.", + "webhook_active_form_help": "Webhook harus aktif agar dapat dipanggil.", "edit_webhook_js": "Edit webhook \"{title}\"", - "webhook_was_triggered": "The webhook was triggered on the indicated transaction. Please wait for results to appear.", + "webhook_was_triggered": "Webhook dipicu pada transaksi yang ditentukan. Silakan tunggu hasilnya muncul.", "view_message": "Lihat pesan", "view_attempts": "Lihat upaya yang gagal", - "message_content_title": "Webhook message content", - "message_content_help": "This is the content of the message that was sent (or tried) using this webhook.", - "attempt_content_title": "Webhook attempts", - "attempt_content_help": "These are all the unsuccessful attempts of this webhook message to submit to the configured URL. After some time, Firefly III will stop trying.", - "no_attempts": "There are no unsuccessful attempts. That's a good thing!", - "webhook_attempt_at": "Attempt at {moment}", + "message_content_title": "Konten pesan webhook", + "message_content_help": "Ini adalah isi pesan yang dikirim (atau dicoba dikirim) menggunakan webhook ini.", + "attempt_content_title": "Percobaan webhook", + "attempt_content_help": "Ini adalah semua percobaan gagal pengiriman pesan webhook ini ke URL yang dikonfigurasi. Setelah beberapa waktu, Firefly III akan berhenti mencoba.", + "no_attempts": "Tidak ada percobaan gagal. Itu hal yang bagus!", + "webhook_attempt_at": "Percobaan pada {moment}", "logs": "Log", "response": "Tanggapan", - "visit_webhook_url": "Visit webhook URL", - "reset_webhook_secret": "Reset webhook secret", + "visit_webhook_url": "Kunjungi URL webhook", + "reset_webhook_secret": "Reset rahasia webhook", "header_exchange_rates": "Nilai tukar", "exchange_rates_intro": "Firefly III mendukung pengunduhan dan penggunaan nilai tukar. Baca selengkapnya di dokumentasi<\/a>.", "exchange_rates_from_to": "Antara {from} dan {to} (dan sebaliknya)", @@ -160,7 +160,7 @@ "url": "URL", "active": "Aktif", "interest_date": "Tanggal bunga", - "administration_currency": "Primary currency", + "administration_currency": "Mata uang utama", "title": "Judul", "date": "Tanggal", "book_date": "Tanggal buku", @@ -170,22 +170,22 @@ "payment_date": "Tanggal pembayaran", "invoice_date": "Tanggal faktur", "internal_reference": "Referensi internal", - "webhook_response": "Response", - "webhook_trigger": "Trigger", - "webhook_delivery": "Delivery", + "webhook_response": "Respons", + "webhook_trigger": "Pemicu", + "webhook_delivery": "Pengiriman", "from_currency_to_currency": "{from} → {to}", "to_currency_from_currency": "{to} → {from}", - "rate": "Rate" + "rate": "Kurs" }, "list": { "title": "Judul", "active": "Aktif?", - "primary_currency": "Primary currency", - "trigger": "Trigger", - "response": "Response", - "delivery": "Delivery", + "primary_currency": "Mata uang utama", + "trigger": "Pemicu", + "response": "Respons", + "delivery": "Pengiriman", "url": "URL", - "secret": "Secret" + "secret": "Rahasia" }, "config": { "html_language": "id", diff --git a/resources/assets/v1/src/locales/ko.json b/resources/assets/v1/src/locales/ko.json index 543eace4d4..ef61654d8d 100644 --- a/resources/assets/v1/src/locales/ko.json +++ b/resources/assets/v1/src/locales/ko.json @@ -49,7 +49,7 @@ "no_bill": "(no subscription)", "category": "\uce74\ud14c\uace0\ub9ac", "attachments": "\ucca8\ubd80 \ud30c\uc77c", - "notes": "\ub178\ud2b8", + "notes": "\uba54\ubaa8", "external_url": "\uc678\ubd80 URL", "update_transaction": "\uac70\ub798 \uc5c5\ub370\uc774\ud2b8", "after_update_create_another": "\uc5c5\ub370\uc774\ud2b8 \ud6c4 \uc5ec\uae30\ub85c \ub3cc\uc544\uc640\uc11c \uc218\uc815\uc744 \uacc4\uc18d\ud569\ub2c8\ub2e4.", @@ -120,7 +120,7 @@ "webhook_response_ACCOUNTS": "\uacc4\uc815 \uc815\ubcf4", "webhook_response_NONE": "No details", "webhook_delivery_JSON": "JSON", - "actions": "\uc561\uc158", + "actions": "\ud589\ub3d9", "meta_data": "\uba54\ud0c0\ub370\uc774\ud130", "webhook_messages": "\uc6f9\ud6c5 \uba54\uc2dc\uc9c0", "inactive": "\ube44\ud65c\uc131\ud654", diff --git a/tests/integration/Api/Autocomplete/BillControllerTest.php b/tests/integration/Api/Autocomplete/BillControllerTest.php index 07b4418ff1..eba0e2b5cf 100644 --- a/tests/integration/Api/Autocomplete/BillControllerTest.php +++ b/tests/integration/Api/Autocomplete/BillControllerTest.php @@ -48,14 +48,14 @@ final class BillControllerTest extends TestCase for ($i = 1; $i <= $count; ++$i) { $bill = Bill::create([ 'user_id' => $user->id, - 'name' => 'Bill ' . $i, + 'name' => 'Bill '.$i, 'user_group_id' => $user->user_group_id, 'amount_min' => random_int(1, 100), // random amount - 'amount_max' => random_int(101, 200), // random amount - 'match' => 'MIGRATED_TO_RULES', - 'date' => '2024-01-01', - 'repeat_freq' => 'monthly', - 'automatch' => 1 + 'amount_max' => random_int(101, 200), // random amount + 'match' => 'MIGRATED_TO_RULES', + 'date' => '2024-01-01', + 'repeat_freq' => 'monthly', + 'automatch' => 1, ]); } } @@ -72,7 +72,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.bills'), ['Accept' => 'application/json']); @@ -82,7 +82,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointThenReturnsBills(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(5, $user); @@ -96,7 +96,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(5, $user); @@ -111,7 +111,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(20, $user); diff --git a/tests/integration/Api/Autocomplete/BudgetControllerTest.php b/tests/integration/Api/Autocomplete/BudgetControllerTest.php index 7730412c56..ddace5d35f 100644 --- a/tests/integration/Api/Autocomplete/BudgetControllerTest.php +++ b/tests/integration/Api/Autocomplete/BudgetControllerTest.php @@ -48,9 +48,9 @@ final class BudgetControllerTest extends TestCase for ($i = 1; $i <= $count; ++$i) { $budget = Budget::create([ 'user_id' => $user->id, - 'name' => 'Budget ' . $i, + 'name' => 'Budget '.$i, 'user_group_id' => $user->user_group_id, - 'active' => 1 + 'active' => 1, ]); } } @@ -67,7 +67,7 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.budgets'), ['Accept' => 'application/json']); @@ -77,7 +77,7 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturnsBudgets(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(5, $user); @@ -91,7 +91,7 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(5, $user); @@ -104,7 +104,7 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(20, $user); diff --git a/tests/integration/Api/Autocomplete/CategoryControllerTest.php b/tests/integration/Api/Autocomplete/CategoryControllerTest.php index e2899b9adb..79a9d4d012 100644 --- a/tests/integration/Api/Autocomplete/CategoryControllerTest.php +++ b/tests/integration/Api/Autocomplete/CategoryControllerTest.php @@ -46,7 +46,7 @@ final class CategoryControllerTest extends TestCase private function createTestCategories(int $count, User $user): void { for ($i = 1; $i <= $count; ++$i) { - $category = Category::create(['user_id' => $user->id, 'name' => 'Category ' . $i, 'user_group_id' => $user->user_group_id]); + $category = Category::create(['user_id' => $user->id, 'name' => 'Category '.$i, 'user_group_id' => $user->user_group_id]); } } @@ -62,7 +62,7 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.categories'), ['Accept' => 'application/json']); @@ -72,7 +72,7 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointThenReturnsCategories(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(5, $user); @@ -86,7 +86,7 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(5, $user); @@ -99,7 +99,7 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(20, $user); diff --git a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php index 85ad1a4c9e..8df8d87cdb 100644 --- a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php +++ b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php @@ -46,11 +46,11 @@ final class CurrencyControllerTest extends TestCase { for ($i = 1; $i <= $count; ++$i) { $currency = TransactionCurrency::create([ - 'name' => 'Currency ' . $i, - 'code' => 'CUR' . $i, - 'symbol' => 'C' . $i, + 'name' => 'Currency '.$i, + 'code' => 'CUR'.$i, + 'symbol' => 'C'.$i, 'decimal_places' => $i, - 'enabled' => $enabled + 'enabled' => $enabled, ]); } } @@ -67,7 +67,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // test API @@ -79,7 +79,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturnsACollectionOfEnabledCurrencies(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -99,7 +99,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointDoesNotReturnDisabledCurrencies(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -115,7 +115,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesWithLimit(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -133,7 +133,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCurrencies(20, true); diff --git a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php index 809e0e3e6f..7ff8f16f8e 100644 --- a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php +++ b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php @@ -47,10 +47,10 @@ final class ObjectGroupControllerTest extends TestCase { for ($i = 1; $i <= $count; ++$i) { $objectGroup = ObjectGroup::create([ - 'title' => 'Object Group ' . $i, + 'title' => 'Object Group '.$i, 'order' => $i, 'user_group_id' => $user->user_group_id, - 'user_id' => $user->id + 'user_id' => $user->id, ]); } } @@ -66,7 +66,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // test API @@ -77,7 +77,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointThenReturnsObjectGroups(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(5, $user); @@ -91,7 +91,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(5, $user); @@ -106,7 +106,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(20, $user); diff --git a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php index 74ee91f5a8..8d7d3614af 100644 --- a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php +++ b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php @@ -49,7 +49,7 @@ final class PiggyBankControllerTest extends TestCase private function createTestPiggyBanks(int $count, User $user): void { - $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first(); + $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first(); if (null === $type) { $type = AccountType::create(['type' => AccountTypeEnum::DEFAULT->value]); } @@ -60,19 +60,19 @@ final class PiggyBankControllerTest extends TestCase for ($i = 1; $i <= $count; ++$i) { $piggyBank = PiggyBank::create([ 'user_id' => $user->id, - 'name' => 'Piggy bank ' . $i, + 'name' => 'Piggy bank '.$i, 'target_amount' => 1000, 'transaction_currency_id' => $currency->id, 'target_date' => now()->addDays(30), 'user_group_id' => $user->user_group_id, - 'active' => 1 + 'active' => 1, ]); $account = Account::create([ 'user_id' => $user->id, - 'name' => 'Account ' . $i, + 'name' => 'Account '.$i, 'user_group_id' => $user->user_group_id, 'account_type_id' => $type->id, - 'active' => 1 + 'active' => 1, ]); $piggyBank->accounts()->save($account); } @@ -90,7 +90,7 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.piggy-banks'), ['Accept' => 'application/json']); @@ -100,7 +100,7 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturnsBudgets(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(5, $user); @@ -114,7 +114,7 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(5, $user); @@ -127,7 +127,7 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(20, $user); diff --git a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php index 6bb2f36d41..db9fa25329 100644 --- a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php +++ b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php @@ -50,12 +50,12 @@ final class RecurrenceControllerTest extends TestCase 'user_id' => $user->id, 'user_group_id' => $user->user_group_id, 'transaction_type_id' => 1, - 'title' => 'Recurrence ' . $i, - 'description' => 'Recurrence ' . $i, + 'title' => 'Recurrence '.$i, + 'description' => 'Recurrence '.$i, 'first_date' => today(), 'apply_rules' => 1, 'active' => 1, - 'repetitions' => 5 + 'repetitions' => 5, ]); } } @@ -72,7 +72,7 @@ final class RecurrenceControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.recurring'), ['Accept' => 'application/json']); @@ -82,7 +82,7 @@ final class RecurrenceControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(5, $user); @@ -96,7 +96,7 @@ final class RecurrenceControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(5, $user); @@ -111,7 +111,7 @@ final class RecurrenceControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(20, $user); diff --git a/tests/integration/Api/Autocomplete/RuleControllerTest.php b/tests/integration/Api/Autocomplete/RuleControllerTest.php index c999e9a8cf..76181d0925 100644 --- a/tests/integration/Api/Autocomplete/RuleControllerTest.php +++ b/tests/integration/Api/Autocomplete/RuleControllerTest.php @@ -51,19 +51,19 @@ final class RuleControllerTest extends TestCase 'description' => 'RuleGroup 1', 'order' => 1, 'active' => 1, - 'stop_processing' => 0 + 'stop_processing' => 0, ]); for ($i = 1; $i <= $count; ++$i) { $rule = Rule::create([ 'user_id' => $user->id, 'user_group_id' => $user->user_group_id, 'rule_group_id' => $ruleGroup->id, - 'title' => 'Rule ' . $i, - 'description' => 'Rule ' . $i, + 'title' => 'Rule '.$i, + 'description' => 'Rule '.$i, 'order' => 1, 'active' => 1, 'stop_processing' => 0, - 'strict' => 0 + 'strict' => 0, ]); } } @@ -80,7 +80,7 @@ final class RuleControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.rules'), ['Accept' => 'application/json']); @@ -90,7 +90,7 @@ final class RuleControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(5, $user); @@ -104,7 +104,7 @@ final class RuleControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(5, $user); @@ -119,7 +119,7 @@ final class RuleControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(20, $user); diff --git a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php index fcb3b88f6e..61ef3340d5 100644 --- a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php +++ b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php @@ -47,11 +47,11 @@ final class RuleGroupControllerTest extends TestCase $ruleGroup = RuleGroup::create([ 'user_id' => $user->id, 'user_group_id' => $user->user_group_id, - 'title' => 'RuleGroup ' . $i, - 'description' => 'RuleGroup ' . $i, + 'title' => 'RuleGroup '.$i, + 'description' => 'RuleGroup '.$i, 'order' => 1, 'active' => 1, - 'stop_processing' => 0 + 'stop_processing' => 0, ]); } } @@ -68,7 +68,7 @@ final class RuleGroupControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.rule-groups'), ['Accept' => 'application/json']); @@ -78,7 +78,7 @@ final class RuleGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(5, $user); @@ -92,7 +92,7 @@ final class RuleGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(5, $user); @@ -107,7 +107,7 @@ final class RuleGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(20, $user); diff --git a/tests/integration/Api/Autocomplete/TagControllerTest.php b/tests/integration/Api/Autocomplete/TagControllerTest.php index aaf04388c0..7904ec1ec6 100644 --- a/tests/integration/Api/Autocomplete/TagControllerTest.php +++ b/tests/integration/Api/Autocomplete/TagControllerTest.php @@ -47,8 +47,8 @@ final class TagControllerTest extends TestCase $tag = Tag::create([ 'user_id' => $user->id, 'user_group_id' => $user->user_group_id, - 'tag' => 'Tag ' . $i, - 'tag_mode' => 'nothing' + 'tag' => 'Tag '.$i, + 'tag_mode' => 'nothing', ]); } } @@ -65,7 +65,7 @@ final class TagControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.tags'), ['Accept' => 'application/json']); @@ -75,7 +75,7 @@ final class TagControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(5, $user); @@ -89,7 +89,7 @@ final class TagControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(5, $user); @@ -104,7 +104,7 @@ final class TagControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(20, $user); diff --git a/tests/integration/Api/Chart/AccountControllerTest.php b/tests/integration/Api/Chart/AccountControllerTest.php index 0389401578..3e609b6bbb 100644 --- a/tests/integration/Api/Chart/AccountControllerTest.php +++ b/tests/integration/Api/Chart/AccountControllerTest.php @@ -38,7 +38,7 @@ final class AccountControllerTest extends TestCase { use RefreshDatabase; - private null|User $user = null; + private ?User $user = null; #[Override] protected function setUp(): void @@ -62,7 +62,7 @@ final class AccountControllerTest extends TestCase { $this->actingAs($this->user); $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; - $response = $this->getJson(route('api.v1.chart.account.overview') . '?' . http_build_query($params)); + $response = $this->getJson(route('api.v1.chart.account.overview').'?'.http_build_query($params)); $response->assertStatus(200); } } diff --git a/tests/integration/Api/Chart/BalanceControllerTest.php b/tests/integration/Api/Chart/BalanceControllerTest.php index ffcba4996a..06f31505d7 100644 --- a/tests/integration/Api/Chart/BalanceControllerTest.php +++ b/tests/integration/Api/Chart/BalanceControllerTest.php @@ -38,7 +38,7 @@ final class BalanceControllerTest extends TestCase { use RefreshDatabase; - private null|User $user = null; + private ?User $user = null; #[Override] protected function setUp(): void @@ -62,7 +62,7 @@ final class BalanceControllerTest extends TestCase { $this->actingAs($this->user); $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; - $response = $this->getJson(route('api.v1.chart.balance.balance') . '?' . http_build_query($params)); + $response = $this->getJson(route('api.v1.chart.balance.balance').'?'.http_build_query($params)); $response->assertStatus(200); } } diff --git a/tests/integration/Api/Chart/BudgetControllerTest.php b/tests/integration/Api/Chart/BudgetControllerTest.php index 639b540931..fc275cc70a 100644 --- a/tests/integration/Api/Chart/BudgetControllerTest.php +++ b/tests/integration/Api/Chart/BudgetControllerTest.php @@ -38,7 +38,7 @@ final class BudgetControllerTest extends TestCase { use RefreshDatabase; - private null|User $user = null; + private ?User $user = null; #[Override] protected function setUp(): void @@ -62,7 +62,7 @@ final class BudgetControllerTest extends TestCase { $this->actingAs($this->user); $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; - $response = $this->getJson(route('api.v1.chart.budget.overview') . '?' . http_build_query($params)); + $response = $this->getJson(route('api.v1.chart.budget.overview').'?'.http_build_query($params)); $response->assertStatus(200); } } diff --git a/tests/integration/Api/Chart/CategoryControllerTest.php b/tests/integration/Api/Chart/CategoryControllerTest.php index 25e917ad3e..9ee47b495f 100644 --- a/tests/integration/Api/Chart/CategoryControllerTest.php +++ b/tests/integration/Api/Chart/CategoryControllerTest.php @@ -38,7 +38,7 @@ final class CategoryControllerTest extends TestCase { use RefreshDatabase; - private null|User $user = null; + private ?User $user = null; #[Override] protected function setUp(): void @@ -62,7 +62,7 @@ final class CategoryControllerTest extends TestCase { $this->actingAs($this->user); $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; - $response = $this->getJson(route('api.v1.chart.category.overview') . '?' . http_build_query($params)); + $response = $this->getJson(route('api.v1.chart.category.overview').'?'.http_build_query($params)); $response->assertStatus(200); } } diff --git a/tests/integration/Api/Models/Account/ListControllerTest.php b/tests/integration/Api/Models/Account/ListControllerTest.php index d04f0c183c..2c4c816876 100644 --- a/tests/integration/Api/Models/Account/ListControllerTest.php +++ b/tests/integration/Api/Models/Account/ListControllerTest.php @@ -49,29 +49,32 @@ final class ListControllerTest extends TestCase { parent::setUp(); - $this->user = $this->createAuthenticatedUser(); + $this->user = $this->createAuthenticatedUser(); $this->actingAs($this->user); $this->account = Account::factory() ->for($this->user) ->withType(AccountTypeEnum::ASSET) - ->create(); + ->create() + ; app(AttachmentFactory::class) ->setUser($this->user) ->create([ 'filename' => 'test 1', 'title' => 'test 1', 'attachable_type' => Account::class, - 'attachable_id' => $this->account->id - ]); + 'attachable_id' => $this->account->id, + ]) + ; app(AttachmentFactory::class) ->setUser($this->user) ->create([ 'filename' => 'test 2', 'title' => 'test 2', 'attachable_type' => Account::class, - 'attachable_id' => $this->account->id - ]); + 'attachable_id' => $this->account->id, + ]) + ; } public function testIndex(): void diff --git a/tests/integration/Api/Models/Account/ShowControllerTest.php b/tests/integration/Api/Models/Account/ShowControllerTest.php index 97a2397797..4963a14ed2 100644 --- a/tests/integration/Api/Models/Account/ShowControllerTest.php +++ b/tests/integration/Api/Models/Account/ShowControllerTest.php @@ -53,23 +53,28 @@ final class ShowControllerTest extends TestCase Account::factory() ->for($this->user) ->withType(AccountTypeEnum::ASSET) - ->create(); + ->create() + ; Account::factory() ->for($this->user) ->withType(AccountTypeEnum::REVENUE) - ->create(); + ->create() + ; Account::factory() ->for($this->user) ->withType(AccountTypeEnum::EXPENSE) - ->create(); + ->create() + ; Account::factory() ->for($this->user) ->withType(AccountTypeEnum::DEBT) - ->create(); + ->create() + ; Account::factory() ->for($this->user) ->withType(AccountTypeEnum::ASSET) - ->create(); + ->create() + ; } public function testIndex(): void @@ -83,7 +88,7 @@ final class ShowControllerTest extends TestCase public function testIndexFailsOnUnknownAccountType(): void { $this->actingAs($this->user); - $response = $this->getJson(route('api.v1.accounts.index') . '?type=foobar'); + $response = $this->getJson(route('api.v1.accounts.index').'?type=foobar'); $response->assertStatus(422); $response->assertJson(['errors' => ['type' => ['The selected type is invalid.']]]); } @@ -91,11 +96,11 @@ final class ShowControllerTest extends TestCase public function testIndexCanFilterOnAccountType(): void { $this->actingAs($this->user); - $response = $this->getJson(route('api.v1.accounts.index') . '?type=asset'); + $response = $this->getJson(route('api.v1.accounts.index').'?type=asset'); $response->assertStatus(200); $response->assertJson([ 'data' => [['attributes' => ['type' => 'asset']], ['attributes' => ['type' => 'asset']]], - 'meta' => ['pagination' => ['total' => 2]] + 'meta' => ['pagination' => ['total' => 2]], ]); } } diff --git a/tests/integration/Api/System/AboutControllerTest.php b/tests/integration/Api/System/AboutControllerTest.php index 3a41fee2ba..4e68500110 100644 --- a/tests/integration/Api/System/AboutControllerTest.php +++ b/tests/integration/Api/System/AboutControllerTest.php @@ -41,7 +41,7 @@ final class AboutControllerTest extends TestCase { use RefreshDatabase; - private null|User $user = null; + private ?User $user = null; #[Override] protected function setUp(): void @@ -67,7 +67,7 @@ final class AboutControllerTest extends TestCase $response = $this->getJson(route('api.v1.about.user')); $response->assertOk(); - $response->assertJson(fn(AssertableJson $json): AssertableJson => $json->where('data.attributes.email', $this->user->email)->where( + $response->assertJson(fn (AssertableJson $json): AssertableJson => $json->where('data.attributes.email', $this->user->email)->where( 'data.attributes.role', $this->user->role )); diff --git a/tests/integration/CreatesApplication.php b/tests/integration/CreatesApplication.php index 307527ac68..7c0e8f8d93 100644 --- a/tests/integration/CreatesApplication.php +++ b/tests/integration/CreatesApplication.php @@ -38,7 +38,7 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__ . '/../../bootstrap/app.php'; + $app = require __DIR__.'/../../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/tests/integration/Support/Models/BillDateCalculatorTest.php b/tests/integration/Support/Models/BillDateCalculatorTest.php index 99fcdfd521..98970a331a 100644 --- a/tests/integration/Support/Models/BillDateCalculatorTest.php +++ b/tests/integration/Support/Models/BillDateCalculatorTest.php @@ -58,7 +58,7 @@ final class BillDateCalculatorTest extends TestCase Carbon $billStart, string $period, int $skip, - null|Carbon $lastPaid, + ?Carbon $lastPaid, array $expected ): void { $result = $this->calculator->getPayDates($earliest, $latest, $billStart, $period, $skip, $lastPaid); @@ -79,7 +79,7 @@ final class BillDateCalculatorTest extends TestCase 'monthly', 0, Carbon::parse('2023-11-01'), - ['2023-12-01'] + ['2023-12-01'], ]; // already paid on the 12th, expect it next month. @@ -90,7 +90,7 @@ final class BillDateCalculatorTest extends TestCase 'monthly', 0, Carbon::parse('2023-11-12'), - ['2023-12-01'] + ['2023-12-01'], ]; // every month, start on 2024-01-30, view is quarterly @@ -101,7 +101,7 @@ final class BillDateCalculatorTest extends TestCase 'monthly', 0, null, - ['2023-01-29', '2023-02-28', '2023-03-29'] + ['2023-01-29', '2023-02-28', '2023-03-29'], ]; // every month, start on 2024-01-30, view is quarterly @@ -112,7 +112,7 @@ final class BillDateCalculatorTest extends TestCase 'monthly', 0, null, - ['2024-01-30', '2024-02-29', '2024-03-30'] + ['2024-01-30', '2024-02-29', '2024-03-30'], ]; // yearly not due this month. Should jump to next year. @@ -123,7 +123,7 @@ final class BillDateCalculatorTest extends TestCase 'yearly', 0, Carbon::parse('2023-05-02'), - ['2024-05-01'] + ['2024-05-01'], ]; } } diff --git a/tests/integration/Support/NavigationCustomEndOfPeriodTest.php b/tests/integration/Support/NavigationCustomEndOfPeriodTest.php index 2eb368022a..16102bc7fc 100644 --- a/tests/integration/Support/NavigationCustomEndOfPeriodTest.php +++ b/tests/integration/Support/NavigationCustomEndOfPeriodTest.php @@ -44,7 +44,7 @@ final class NavigationCustomEndOfPeriodTest extends TestCase $expected = Carbon::parse('2023-09-04'); $navigation = new Navigation(); - $period = $navigation->endOfPeriod($from, 'custom'); + $period = $navigation->endOfPeriod($from, 'custom'); $this->assertSame($expected->toDateString(), $period->toDateString()); } } diff --git a/tests/integration/TestCase.php b/tests/integration/TestCase.php index 95a31adcb8..3288708011 100644 --- a/tests/integration/TestCase.php +++ b/tests/integration/TestCase.php @@ -42,7 +42,7 @@ abstract class TestCase extends BaseTestCase protected const MAX_ITERATIONS = 2; - protected $seed = true; + protected $seed = true; public function dateRangeProvider(): array { @@ -53,7 +53,7 @@ abstract class TestCase extends BaseTestCase 'three months' => ['3M'], 'six months' => ['6M'], 'one year' => ['1Y'], - 'custom range' => ['custom'] + 'custom range' => ['custom'], ]; } diff --git a/tests/unit/Support/Calendar/CalculatorProvider.php b/tests/unit/Support/Calendar/CalculatorProvider.php index 72cd29cb39..3681275b8f 100644 --- a/tests/unit/Support/Calendar/CalculatorProvider.php +++ b/tests/unit/Support/Calendar/CalculatorProvider.php @@ -106,7 +106,7 @@ readonly class CalculatorProvider self::from(Periodicity::Yearly, new IntervalProvider(Carbon::now(), Carbon::now()->addYearsNoOverflow(3)), 2), self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2019-01-29'), Carbon::parse('2025-01-29')), 5), - self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2031-02-28')), 10) + self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2031-02-28')), 10), ]; /** @var IntervalProvider $interval */ diff --git a/tests/unit/Support/Calendar/CalculatorTest.php b/tests/unit/Support/Calendar/CalculatorTest.php index 78378ece04..d6d9677361 100644 --- a/tests/unit/Support/Calendar/CalculatorTest.php +++ b/tests/unit/Support/Calendar/CalculatorTest.php @@ -57,7 +57,7 @@ final class CalculatorTest extends TestCase /** @var IntervalProvider $interval */ foreach ($intervals as $index => $interval) { - $calculator = CalculatorProvider::from($periodicity, $interval); + $calculator = CalculatorProvider::from($periodicity, $interval); $periodicityIntervals["#{$index} {$calculator->label}"] = [$calculator]; } diff --git a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php index df9a8d4378..d3e415947f 100644 --- a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php @@ -57,7 +57,7 @@ final class BimonthlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-11-30'), Carbon::parse('2020-01-30')), new IntervalProvider(Carbon::parse('2020-12-29'), Carbon::parse('2021-02-28')), new IntervalProvider(Carbon::parse('2020-12-30'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-12-31'), Carbon::parse('2021-02-28')) + new IntervalProvider(Carbon::parse('2020-12-31'), Carbon::parse('2021-02-28')), ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php index 38c87def6c..83937f1a26 100644 --- a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php @@ -49,7 +49,7 @@ final class FortnightlyTest extends IntervalTestCase { return [ new IntervalProvider(Carbon::now(), Carbon::now()->addWeeks(2)), - new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-14')) + new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-14')), ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php index 8f9727bcd6..6c29bcbab1 100644 --- a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php @@ -57,7 +57,7 @@ final class HalfYearlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-08-30'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2019-08-31'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2020-08-29'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-08-30'), Carbon::parse('2021-02-28')) + new IntervalProvider(Carbon::parse('2020-08-30'), Carbon::parse('2021-02-28')), ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php index 85a5578ebd..f46d79ed69 100644 --- a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php @@ -59,7 +59,7 @@ final class MonthlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2023-03-31'), Carbon::parse('2023-04-30')), new IntervalProvider(Carbon::parse('2023-05-31'), Carbon::parse('2023-06-30')), // new IntervalProvider(Carbon::parse('2023-08-31'), Carbon::parse('2023-09-30')), - new IntervalProvider(Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')) + new IntervalProvider(Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')), ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php index cee10ce3db..5a077ff4e5 100644 --- a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php @@ -56,7 +56,7 @@ final class QuarterlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-11-29'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2019-11-30'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2020-11-29'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-11-30'), Carbon::parse('2021-02-28')) + new IntervalProvider(Carbon::parse('2020-11-30'), Carbon::parse('2021-02-28')), ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php index a8e369b654..80f7349d4c 100644 --- a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php @@ -50,7 +50,7 @@ final class YearlyTest extends IntervalTestCase return [ new IntervalProvider(Carbon::now(), Carbon::now()->addYears(1)), new IntervalProvider(Carbon::parse('2019-01-29'), Carbon::parse('2020-01-29')), - new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2021-02-28')) + new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2021-02-28')), ]; } } diff --git a/tests/unit/Support/NavigationAddPeriodTest.php b/tests/unit/Support/NavigationAddPeriodTest.php index e637145b6f..71acc3bd13 100644 --- a/tests/unit/Support/NavigationAddPeriodTest.php +++ b/tests/unit/Support/NavigationAddPeriodTest.php @@ -69,7 +69,7 @@ final class NavigationAddPeriodTest extends TestCase 'skip' => 10, 'frequency' => 'daily', 'from' => Carbon::parse('2019-01-31'), - 'expected' => Carbon::parse('2019-02-11') + 'expected' => Carbon::parse('2019-02-11'), ], '1D' => ['skip' => 1, 'frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], 'daily' => ['skip' => 1, 'frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], @@ -80,115 +80,115 @@ final class NavigationAddPeriodTest extends TestCase 'skip' => 1, 'frequency' => '1M', 'from' => Carbon::parse('2023-06-25'), - 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2), ], 'month' => [ 'skip' => 1, 'frequency' => 'month', 'from' => Carbon::parse('2023-06-25'), - 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2), ], 'monthly' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-06-25'), - 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2), ], '2019-01-29 to 2019-03-29' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-29'), - 'expected' => Carbon::parse('2019-03-29') + 'expected' => Carbon::parse('2019-03-29'), ], '2019-01-30 to 2019-03-30' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-30'), - 'expected' => Carbon::parse('2019-03-30') + 'expected' => Carbon::parse('2019-03-30'), ], '2019-01-31 to 2019-03-31' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-31'), - 'expected' => Carbon::parse('2019-03-31') + 'expected' => Carbon::parse('2019-03-31'), ], '2023-03-31 to 2023-05-31' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-03-31'), - 'expected' => Carbon::parse('2023-05-31') + 'expected' => Carbon::parse('2023-05-31'), ], '2023-05-31 to 2023-07-31' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-05-31'), - 'expected' => Carbon::parse('2023-07-31') + 'expected' => Carbon::parse('2023-07-31'), ], '2023-08-31 to 2023-10-31' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-08-31'), - 'expected' => Carbon::parse('2023-10-31') + 'expected' => Carbon::parse('2023-10-31'), ], '2023-10-31 to 2023-12-31' => [ 'skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-10-31'), - 'expected' => Carbon::parse('2023-12-31') + 'expected' => Carbon::parse('2023-12-31'), ], '2023-01-31 to 2023-03-30' => [ 'skip' => 2, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-01-31'), - 'expected' => Carbon::parse('2023-04-30') + 'expected' => Carbon::parse('2023-04-30'), ], '3M' => [ 'skip' => 1, 'frequency' => '3M', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(6) + 'expected' => Carbon::now()->addMonthsNoOverflow(6), ], 'quarter' => [ 'skip' => 1, 'frequency' => 'quarter', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(6) + 'expected' => Carbon::now()->addMonthsNoOverflow(6), ], 'quarterly' => [ 'skip' => 1, 'frequency' => 'quarterly', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(6) + 'expected' => Carbon::now()->addMonthsNoOverflow(6), ], 'quarter_2' => [ 'skip' => 2, 'frequency' => 'quarter', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(9) + 'expected' => Carbon::now()->addMonthsNoOverflow(9), ], 'quarterly_2' => [ 'skip' => 2, 'frequency' => 'quarterly', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(9) + 'expected' => Carbon::now()->addMonthsNoOverflow(9), ], 'quarter_3' => [ 'skip' => 2, 'frequency' => 'quarter', 'from' => Carbon::parse('2023-01-01'), - 'expected' => Carbon::parse('2023-10-01') + 'expected' => Carbon::parse('2023-10-01'), ], '6M' => [ 'skip' => 1, 'frequency' => '6M', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(12) + 'expected' => Carbon::now()->addMonthsNoOverflow(12), ], 'half-year' => [ 'skip' => 1, 'frequency' => 'half-year', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(12) + 'expected' => Carbon::now()->addMonthsNoOverflow(12), ], 'year' => ['skip' => 1, 'frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], 'yearly' => ['skip' => 1, 'frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], @@ -197,35 +197,35 @@ final class NavigationAddPeriodTest extends TestCase 'skip' => 1, 'frequency' => 'last7', 'from' => Carbon::parse('2023-02-01'), - 'expected' => Carbon::parse('2023-02-15') + 'expected' => Carbon::parse('2023-02-15'), ], 'last7' => ['skip' => 1, 'frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(14)], 'last30' => [ 'skip' => 1, 'frequency' => 'last30', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(2) + 'expected' => Carbon::now()->addMonthsNoOverflow(2), ], 'last90' => [ 'skip' => 1, 'frequency' => 'last90', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(6) + 'expected' => Carbon::now()->addMonthsNoOverflow(6), ], 'last365' => ['skip' => 1, 'frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], 'MTD' => [ 'skip' => 1, 'frequency' => 'MTD', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(2) + 'expected' => Carbon::now()->addMonthsNoOverflow(2), ], 'QTD' => [ 'skip' => 1, 'frequency' => 'QTD', 'from' => Carbon::now(), - 'expected' => Carbon::now()->addMonthsNoOverflow(6) + 'expected' => Carbon::now()->addMonthsNoOverflow(6), ], - 'YTD' => ['skip' => 1, 'frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)] + 'YTD' => ['skip' => 1, 'frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], ]; foreach ($intervals as $interval) { yield "{$interval['frequency']} {$interval['from']->toDateString()} to {$interval['expected']->toDateString()}" => $interval; diff --git a/tests/unit/Support/NavigationEndOfPeriodTest.php b/tests/unit/Support/NavigationEndOfPeriodTest.php index 74ecf8d0ba..5eb565387c 100644 --- a/tests/unit/Support/NavigationEndOfPeriodTest.php +++ b/tests/unit/Support/NavigationEndOfPeriodTest.php @@ -69,7 +69,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addWeek() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'week' => [ @@ -78,7 +78,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addWeek() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'weekly' => [ @@ -87,7 +87,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addWeek() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'month' => [ @@ -96,7 +96,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addMonth() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield '1M' => [ @@ -105,7 +105,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addMonth() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'monthly' => [ @@ -114,7 +114,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addMonth() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield '3M' => [ @@ -123,7 +123,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addQuarter() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'quarter' => [ @@ -132,7 +132,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addQuarter() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'quarterly' => [ @@ -141,7 +141,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addQuarter() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'year' => [ @@ -150,7 +150,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addYearNoOverflow() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'yearly' => [ @@ -159,7 +159,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addYearNoOverflow() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield '1Y' => [ @@ -168,7 +168,7 @@ final class NavigationEndOfPeriodTest extends TestCase Carbon::now() ->addYearNoOverflow() ->subDay() - ->endOfDay() + ->endOfDay(), ]; yield 'half-year' => ['half-year', Carbon::parse('2023-05-20'), Carbon::parse('2023-11-19')->endOfDay()]; @@ -200,7 +200,7 @@ final class NavigationEndOfPeriodTest extends TestCase ): void { Log::spy(); - $period = $this->navigation->endOfPeriod($from, $frequency); + $period = $this->navigation->endOfPeriod($from, $frequency); $this->assertSame($expected->toDateString(), $period->toDateString()); $expectedMessage = sprintf('Cannot do endOfPeriod for $repeat_freq "%s"', $frequency); diff --git a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php index 923cba3ee8..fd60b31039 100644 --- a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php +++ b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php @@ -64,7 +64,7 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase yield 'multiple words' => [ 'groceries shopping market', - new NodeGroup([new StringNode('groceries'), new StringNode('shopping'), new StringNode('market')]) + new NodeGroup([new StringNode('groceries'), new StringNode('shopping'), new StringNode('market')]), ]; yield 'field operator' => ['amount:100', new NodeGroup([new FieldNode('amount', '100')])]; @@ -75,43 +75,43 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase yield 'simple subquery' => [ '(amount:100 category:food)', - new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')])]) + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')])]), ]; yield 'prohibited subquery' => [ '-(amount:100 category:food)', - new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')], true)]) + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')], true)]), ]; yield 'nested subquery' => [ '(amount:100 (description:"test" category:food))', new NodeGroup([new NodeGroup([ new FieldNode('amount', '100'), - new NodeGroup([new FieldNode('description', 'test'), new FieldNode('category', 'food')]) - ])]) + new NodeGroup([new FieldNode('description', 'test'), new FieldNode('category', 'food')]), + ])]), ]; yield 'mixed words and operators' => [ 'groceries amount:50 shopping', - new NodeGroup([new StringNode('groceries'), new FieldNode('amount', '50'), new StringNode('shopping')]) + new NodeGroup([new StringNode('groceries'), new FieldNode('amount', '50'), new StringNode('shopping')]), ]; yield 'subquery after field value' => [ 'amount:100 (description:"market" category:food)', - new NodeGroup([new FieldNode('amount', '100'), new NodeGroup([new FieldNode('description', 'market'), new FieldNode('category', 'food')])]) + new NodeGroup([new FieldNode('amount', '100'), new NodeGroup([new FieldNode('description', 'market'), new FieldNode('category', 'food')])]), ]; yield 'word followed by subquery' => [ 'groceries (amount:100 description_contains:"test")', - new NodeGroup([new StringNode('groceries'), new NodeGroup([new FieldNode('amount', '100'), new FieldNode('description_contains', 'test')])]) + new NodeGroup([new StringNode('groceries'), new NodeGroup([new FieldNode('amount', '100'), new FieldNode('description_contains', 'test')])]), ]; yield 'nested subquery with prohibited field' => [ '(amount:100 (description_contains:"test payment" -has_attachments:true))', new NodeGroup([new NodeGroup([ new FieldNode('amount', '100'), - new NodeGroup([new FieldNode('description_contains', 'test payment'), new FieldNode('has_attachments', 'true', true)]) - ])]) + new NodeGroup([new FieldNode('description_contains', 'test payment'), new FieldNode('has_attachments', 'true', true)]), + ])]), ]; yield 'complex nested subqueries' => [ @@ -125,17 +125,17 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase new FieldNode('category', 'food', true), new StringNode('word'), new FieldNode('description', 'test phrase'), - new NodeGroup([new FieldNode('has_notes', 'true')]) - ]) - ]) - ]) + new NodeGroup([new FieldNode('has_notes', 'true')]), + ]), + ]), + ]), ]; yield 'word with multiple spaces' => ['"multiple spaces"', new NodeGroup([new StringNode('multiple spaces')])]; yield 'field with multiple spaces in value' => [ 'description:"multiple spaces here"', - new NodeGroup([new FieldNode('description', 'multiple spaces here')]) + new NodeGroup([new FieldNode('description', 'multiple spaces here')]), ]; yield 'unmatched right parenthesis in word' => ['test)word', new NodeGroup([new StringNode('test)word')])]; @@ -144,7 +144,7 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase yield 'subquery followed by word' => [ '(amount:100 category:food) shopping', - new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')]), new StringNode('shopping')]) + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')]), new StringNode('shopping')]), ]; } }