From 2cb14f6b725c653d5d3113d6c43a4f870e88102d Mon Sep 17 00:00:00 2001 From: James Cole Date: Tue, 27 May 2025 17:06:15 +0200 Subject: [PATCH] Fix various code. --- .ci/rector.php | 25 +++----- .../Events/Model/BudgetLimitHandler.php | 2 +- .../Events/Model/PiggyBankEventHandler.php | 3 +- .../Events/PreferencesEventHandler.php | 11 ++-- app/Handlers/Events/UserEventHandler.php | 2 +- .../Events/VersionCheckEventHandler.php | 17 +++--- app/Helpers/Attachments/AttachmentHelper.php | 24 +++++--- .../Collector/Extensions/MetaCollection.php | 58 ++++++++++--------- .../Collector/Extensions/TimeCollection.php | 12 ++-- app/Helpers/Collector/GroupCollector.php | 8 ++- app/Helpers/Report/PopupReport.php | 4 +- .../Webhook/Sha3SignatureGenerator.php | 7 ++- app/Jobs/CreateAutoBudgetLimits.php | 12 ++-- app/Jobs/CreateRecurringTransactions.php | 6 +- app/Jobs/DownloadExchangeRates.php | 15 +++-- app/Jobs/MailError.php | 22 ++++--- app/Jobs/WarnAboutBills.php | 2 +- app/Mail/InvitationMail.php | 4 +- app/Models/AccountMeta.php | 7 ++- app/Models/Configuration.php | 7 ++- app/Models/TransactionJournalMeta.php | 7 ++- .../ReturnsAvailableChannels.php | 2 +- app/Notifications/ReturnsSettings.php | 2 +- app/Notifications/User/BillReminder.php | 5 +- app/Providers/AppServiceProvider.php | 4 +- .../Account/AccountRepository.php | 4 +- .../Account/OperationsRepository.php | 22 +++---- app/Repositories/Bill/BillRepository.php | 7 ++- .../Budget/AvailableBudgetRepository.php | 8 +-- .../Budget/BudgetLimitRepository.php | 18 +++--- app/Repositories/Budget/BudgetRepository.php | 14 ++--- .../Budget/NoBudgetRepository.php | 4 +- .../Budget/OperationsRepository.php | 14 ++--- .../Category/CategoryRepository.php | 20 +++---- .../Category/NoCategoryRepository.php | 10 ++-- .../Category/OperationsRepository.php | 32 +++++----- .../Currency/CurrencyRepository.php | 14 +++-- .../ExchangeRate/ExchangeRateRepository.php | 2 +- .../Journal/JournalRepository.php | 14 ++--- .../LinkType/LinkTypeRepository.php | 10 ++-- .../PiggyBank/PiggyBankRepository.php | 13 +++-- .../Recurring/RecurringRepository.php | 25 ++++---- .../RuleGroup/RuleGroupRepository.php | 4 +- app/Repositories/Tag/OperationsRepository.php | 12 ++-- app/Repositories/Tag/TagRepository.php | 4 +- .../TransactionGroupRepository.php | 20 +++---- .../TransactionTypeRepository.php | 4 +- app/Repositories/User/UserRepository.php | 9 +-- .../UserGroup/UserGroupRepository.php | 2 +- .../UserGroups/Account/AccountRepository.php | 6 +- .../Budget/OperationsRepository.php | 6 +- .../Currency/CurrencyRepository.php | 14 +++-- .../ExchangeRate/ExchangeRateRepository.php | 2 +- app/Rules/IsValidBulkClause.php | 4 +- app/Rules/IsValidPositiveAmount.php | 4 +- app/Rules/UniqueAccountNumber.php | 6 +- app/Rules/UniqueIban.php | 2 +- .../FireflyIIIOrg/Update/UpdateRequest.php | 6 +- .../Destroy/AccountDestroyService.php | 4 +- .../Support/CreditRecalculateService.php | 8 +-- .../Internal/Support/JournalServiceTrait.php | 16 ++--- .../Support/RecurringTransactionTrait.php | 6 +- .../Internal/Update/AccountUpdateService.php | 2 +- .../Internal/Update/BillUpdateService.php | 9 +-- .../Internal/Update/GroupUpdateService.php | 4 +- .../Internal/Update/JournalUpdateService.php | 8 +-- .../Update/RecurrenceUpdateService.php | 2 +- .../Webhook/StandardWebhookSender.php | 4 +- app/Support/Amount.php | 22 +++---- .../Authentication/RemoteUserGuard.php | 6 +- app/Support/CacheProperties.php | 7 ++- app/Support/Calendar/Calculator.php | 2 +- .../Category/WholePeriodChartGenerator.php | 2 +- app/Support/Cronjobs/AutoBudgetCronjob.php | 2 +- app/Support/Cronjobs/BillWarningCronjob.php | 2 +- app/Support/Cronjobs/ExchangeRatesCronjob.php | 2 +- app/Support/Cronjobs/RecurringCronjob.php | 2 +- app/Support/Cronjobs/UpdateCheckCronjob.php | 7 ++- app/Support/FireflyConfig.php | 2 +- app/Support/Form/AccountForm.php | 2 +- app/Support/Form/FormSupport.php | 9 ++- .../Http/Api/AccountBalanceGrouped.php | 5 +- app/Support/Http/Controllers/CreateStuff.php | 6 +- .../Http/Controllers/DateCalculation.php | 2 +- .../Http/Controllers/GetConfigurationData.php | 2 +- .../Http/Controllers/RequestInformation.php | 21 +++---- .../Models/AccountBalanceCalculator.php | 4 +- app/Support/Models/BillDateCalculator.php | 2 +- app/Support/Navigation.php | 32 +++++----- app/Support/ParseDateString.php | 20 ++++--- app/Support/Preferences.php | 6 +- .../Summarizer/TransactionSummarizer.php | 2 +- app/Support/Request/ConvertsDataTypes.php | 10 ++-- app/Support/Search/AccountSearch.php | 6 +- app/Support/Search/OperatorQuerySearch.php | 18 +++--- .../Search/QueryParser/GdbotsQueryParser.php | 4 +- .../Search/QueryParser/QueryParser.php | 2 +- app/Support/Steam.php | 29 +++++----- app/Support/System/OAuthKeys.php | 11 ++-- app/Support/Twig/General.php | 8 ++- app/Support/Twig/TransactionGroupTwig.php | 16 ++--- .../Actions/SetDestinationAccount.php | 8 +-- .../Actions/SetSourceAccount.php | 6 +- .../Actions/UpdatePiggyBank.php | 4 +- .../Expressions/ActionExpression.php | 2 +- app/Transformers/AccountTransformer.php | 13 ++--- .../AvailableBudgetTransformer.php | 2 +- app/Transformers/BillTransformer.php | 8 +-- app/Transformers/BudgetLimitTransformer.php | 2 +- app/Transformers/BudgetTransformer.php | 2 +- app/Transformers/CategoryTransformer.php | 2 +- app/Transformers/RecurrenceTransformer.php | 4 +- .../TransactionGroupTransformer.php | 15 +++-- app/Transformers/V2/AccountTransformer.php | 5 +- app/Transformers/V2/BillTransformer.php | 2 +- app/Transformers/V2/PiggyBankTransformer.php | 4 +- .../V2/TransactionGroupTransformer.php | 6 +- .../WebhookMessageTransformer.php | 4 +- app/Validation/AccountValidator.php | 24 ++++---- .../Bulk/ValidatesBulkTransactionQuery.php | 4 +- app/Validation/FireflyValidator.php | 10 +++- app/Validation/RecurrenceValidation.php | 4 +- app/Validation/TransactionValidation.php | 10 +++- 123 files changed, 581 insertions(+), 500 deletions(-) diff --git a/.ci/rector.php b/.ci/rector.php index 5022e3dc6b..8f33d1615d 100644 --- a/.ci/rector.php +++ b/.ci/rector.php @@ -31,24 +31,13 @@ return RectorConfig::configure() ChangeOrIfContinueToMultiContinueRector::class, ]) ->withPaths([ -// __DIR__ . '/../app', - __DIR__ . '/../app/Api', - __DIR__ . '/../app/Casts', - __DIR__ . '/../app/Console', - __DIR__ . '/../app/Entities', - __DIR__ . '/../app/Enums', - __DIR__ . '/../app/Enums', - __DIR__ . '/../app/Events', - __DIR__ . '/../app/Exceptions', - __DIR__ . '/../app/Factory', - __DIR__ . '/../app/Generator', - __DIR__ . '/../app/Http', -// __DIR__ . '/../bootstrap', -// __DIR__ . '/../config', -// __DIR__ . '/../public', -// __DIR__ . '/../resources', -// __DIR__ . '/../routes', -// __DIR__ . '/../tests', + __DIR__ . '/../app', + __DIR__ . '/../bootstrap', + __DIR__ . '/../config', + __DIR__ . '/../public', + __DIR__ . '/../resources', + __DIR__ . '/../routes', + __DIR__ . '/../tests', ]) // uncomment to reach your current PHP version ->withPhpSets() diff --git a/app/Handlers/Events/Model/BudgetLimitHandler.php b/app/Handlers/Events/Model/BudgetLimitHandler.php index b36bbad397..ac93f75938 100644 --- a/app/Handlers/Events/Model/BudgetLimitHandler.php +++ b/app/Handlers/Events/Model/BudgetLimitHandler.php @@ -204,7 +204,7 @@ class BudgetLimitHandler if (!$limitPeriod->equals($abPeriod) && !$abPeriod->contains($limitPeriod) && $abPeriod->overlapsWith($limitPeriod)) { Log::debug('This budget limit is something else entirely!'); $overlap = $abPeriod->overlap($limitPeriod); - if (null !== $overlap) { + if ($overlap instanceof Period) { $length = $overlap->length(); $daily = bcmul($this->getDailyAmount($budgetLimit), (string) $length); $newAmount = bcadd($newAmount, $daily); diff --git a/app/Handlers/Events/Model/PiggyBankEventHandler.php b/app/Handlers/Events/Model/PiggyBankEventHandler.php index 21764cf508..ecad3759df 100644 --- a/app/Handlers/Events/Model/PiggyBankEventHandler.php +++ b/app/Handlers/Events/Model/PiggyBankEventHandler.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Handlers\Events\Model; +use FireflyIII\Models\TransactionGroup; use FireflyIII\Events\Model\PiggyBank\ChangedAmount; use FireflyIII\Models\PiggyBankEvent; @@ -36,7 +37,7 @@ class PiggyBankEventHandler { // find journal if group is present. $journal = $event->transactionJournal; - if (null !== $event->transactionGroup) { + if ($event->transactionGroup instanceof TransactionGroup) { $journal = $event->transactionGroup->transactionJournals()->first(); } $date = $journal->date ?? today(config('app.timezone')); diff --git a/app/Handlers/Events/PreferencesEventHandler.php b/app/Handlers/Events/PreferencesEventHandler.php index 57033f8fd4..91bbb9a9bd 100644 --- a/app/Handlers/Events/PreferencesEventHandler.php +++ b/app/Handlers/Events/PreferencesEventHandler.php @@ -108,13 +108,12 @@ class PreferencesEventHandler /** @var Budget $budget */ foreach ($set as $budget) { foreach ($budget->autoBudgets as $autoBudget) { - if (null !== $autoBudget->native_amount) { - if (null !== $autoBudget->native_amount) { - Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id)); - $autoBudget->native_amount = null; - $autoBudget->saveQuietly(); - } + if (null === $autoBudget->native_amount) { + continue; } + Log::debug(sprintf('Resetting native_amount for budget #%d and auto budget #%d.', $budget->id, $autoBudget->id)); + $autoBudget->native_amount = null; + $autoBudget->saveQuietly(); } foreach ($budget->budgetlimits as $limit) { if (null !== $limit->native_amount) { diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 3cc02a08bb..ebe0cca9f6 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -484,7 +484,7 @@ class UserEventHandler } // clean up old entries (6 months) $carbon = Carbon::createFromFormat('Y-m-d H:i:s', $preference[$index]['time']); - if (null !== $carbon && $carbon->diffInMonths(today(), true) > 6) { + if ($carbon instanceof Carbon && $carbon->diffInMonths(today(), true) > 6) { app('log')->debug(sprintf('Entry for %s is very old, remove it.', $row['ip'])); unset($preference[$index]); } diff --git a/app/Handlers/Events/VersionCheckEventHandler.php b/app/Handlers/Events/VersionCheckEventHandler.php index 75e313a313..b8005b70ee 100644 --- a/app/Handlers/Events/VersionCheckEventHandler.php +++ b/app/Handlers/Events/VersionCheckEventHandler.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Handlers\Events; +use Carbon\Carbon; use FireflyIII\Events\RequestedVersionCheckStatus; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Update\UpdateTrait; @@ -68,12 +69,12 @@ class VersionCheckEventHandler } /** @var Configuration $lastCheckTime */ - $lastCheckTime = app('fireflyconfig')->get('last_update_check', time()); - $now = time(); + $lastCheckTime = app('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) { - Log::debug(sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data))); + Log::debug(sprintf('Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s'))); return; } @@ -82,7 +83,7 @@ class VersionCheckEventHandler $release = $this->getLatestRelease(); session()->flash($release['level'], $release['message']); - app('fireflyconfig')->set('last_update_check', time()); + app('fireflyconfig')->set('last_update_check', Carbon::now()->getTimestamp()); } /** @@ -100,12 +101,12 @@ class VersionCheckEventHandler } /** @var Configuration $lastCheckTime */ - $lastCheckTime = app('fireflyconfig')->get('last_update_warning', time()); - $now = time(); + $lastCheckTime = app('fireflyconfig')->get('last_update_warning', Carbon::now()->getTimestamp()); + $now = Carbon::now()->getTimestamp(); $diff = $now - $lastCheckTime->data; Log::debug(sprintf('Last warning time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); if ($diff < 604800 * 4) { - Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data))); + Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s'))); return; } @@ -113,6 +114,6 @@ class VersionCheckEventHandler Log::debug('Have warned about a new version in four weeks!'); session()->flash('info', (string) trans('firefly.disabled_but_check')); - app('fireflyconfig')->set('last_update_warning', time()); + app('fireflyconfig')->set('last_update_warning', Carbon::now()->getTimestamp()); } } diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index 5922b84a68..28194b7e03 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -37,6 +37,12 @@ use Illuminate\Support\Facades\Storage; use Illuminate\Support\MessageBag; use Symfony\Component\HttpFoundation\File\UploadedFile; +use function Safe\tmpfile; +use function Safe\fwrite; +use function Safe\finfo_open; +use function Safe\fclose; +use function Safe\md5_file; + use const DIRECTORY_SEPARATOR; /** @@ -120,7 +126,7 @@ class AttachmentHelper implements AttachmentHelperInterface public function saveAttachmentFromApi(Attachment $attachment, string $content): bool { Log::debug(sprintf('Now in %s', __METHOD__)); - $resource = \Safe\tmpfile(); + $resource = tmpfile(); if (false === $resource) { Log::error('Cannot create temp-file for file upload.'); @@ -135,17 +141,17 @@ class AttachmentHelper implements AttachmentHelperInterface $path = stream_get_meta_data($resource)['uri']; Log::debug(sprintf('Path is %s', $path)); - $result = \Safe\fwrite($resource, $content); + $result = fwrite($resource, $content); if (false === $result) { Log::error('Could not write temp file.'); return false; } Log::debug(sprintf('Wrote %d bytes to temp file.', $result)); - $finfo = \Safe\finfo_open(FILEINFO_MIME_TYPE); + $finfo = finfo_open(FILEINFO_MIME_TYPE); if (false === $finfo) { Log::error('Could not open finfo.'); - \Safe\fclose($resource); + fclose($resource); return false; } @@ -153,7 +159,7 @@ class AttachmentHelper implements AttachmentHelperInterface $allowedMime = config('firefly.allowedMimes'); if (!in_array($mime, $allowedMime, true)) { Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime)); - \Safe\fclose($resource); + fclose($resource); return false; } @@ -165,7 +171,7 @@ class AttachmentHelper implements AttachmentHelperInterface $this->uploadDisk->put($file, $content); // update attachment. - $attachment->md5 = (string) \Safe\md5_file($path); + $attachment->md5 = (string) md5_file($path); $attachment->mime = $mime; $attachment->size = strlen($content); $attachment->uploaded = true; @@ -227,7 +233,7 @@ class AttachmentHelper implements AttachmentHelperInterface $attachment = new Attachment(); // create Attachment object. $attachment->user()->associate($user); $attachment->attachable()->associate($model); - $attachment->md5 = (string) \Safe\md5_file($file->getRealPath()); + $attachment->md5 = (string) md5_file($file->getRealPath()); $attachment->filename = $file->getClientOriginalName(); $attachment->mime = $file->getMimeType(); $attachment->size = $file->getSize(); @@ -282,7 +288,7 @@ class AttachmentHelper implements AttachmentHelperInterface } if (true === $result && $this->hasFile($file, $model)) { - $result = false; + return false; } return $result; @@ -335,7 +341,7 @@ class AttachmentHelper implements AttachmentHelperInterface */ protected function hasFile(UploadedFile $file, Model $model): bool { - $md5 = \Safe\md5_file($file->getRealPath()); + $md5 = md5_file($file->getRealPath()); $name = $file->getClientOriginalName(); $class = $model::class; $count = 0; diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php index 37d99ee720..5e6dd7e85c 100644 --- a/app/Helpers/Collector/Extensions/MetaCollection.php +++ b/app/Helpers/Collector/Extensions/MetaCollection.php @@ -36,6 +36,8 @@ use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; + /** * Trait MetaCollection */ @@ -167,7 +169,7 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_id'); - $this->query->where('journal_meta.data', '!=', sprintf('%s', \Safe\json_encode($externalId))); + $this->query->where('journal_meta.data', '!=', sprintf('%s', json_encode($externalId))); $this->query->whereNull('journal_meta.deleted_at'); return $this; @@ -190,14 +192,14 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_url'); - $this->query->where('journal_meta.data', '!=', \Safe\json_encode($url)); + $this->query->where('journal_meta.data', '!=', json_encode($url)); return $this; } public function excludeInternalReference(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -211,14 +213,14 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'recurrence_id'); - $this->query->where('journal_meta.data', '!=', sprintf('%s', \Safe\json_encode($recurringId))); + $this->query->where('journal_meta.data', '!=', sprintf('%s', json_encode($recurringId))); return $this; } public function externalIdContains(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -230,7 +232,7 @@ trait MetaCollection public function externalIdDoesNotContain(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -242,7 +244,7 @@ trait MetaCollection public function externalIdDoesNotEnd(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -254,7 +256,7 @@ trait MetaCollection public function externalIdDoesNotStart(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -266,7 +268,7 @@ trait MetaCollection public function externalIdEnds(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -278,7 +280,7 @@ trait MetaCollection public function externalIdStarts(string $externalId): GroupCollectorInterface { - $externalId = (string) \Safe\json_encode($externalId); + $externalId = (string) json_encode($externalId); $externalId = str_replace('\\', '\\\\', trim($externalId, '"')); $this->joinMetaDataTables(); @@ -291,7 +293,7 @@ trait MetaCollection public function externalUrlContains(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', trim($url, '"')); $this->query->where('journal_meta.name', '=', 'external_url'); $this->query->whereLike('journal_meta.data', sprintf('%%%s%%', $url)); @@ -302,7 +304,7 @@ trait MetaCollection public function externalUrlDoesNotContain(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', trim($url, '"')); $this->query->where('journal_meta.name', '=', 'external_url'); $this->query->whereNotLike('journal_meta.data', sprintf('%%%s%%', $url)); @@ -313,7 +315,7 @@ trait MetaCollection public function externalUrlDoesNotEnd(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', ltrim($url, '"')); $this->query->where('journal_meta.name', '=', 'external_url'); $this->query->whereNotLike('journal_meta.data', sprintf('%%%s', $url)); @@ -324,7 +326,7 @@ trait MetaCollection public function externalUrlDoesNotStart(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', rtrim($url, '"')); // var_dump($url); @@ -337,7 +339,7 @@ trait MetaCollection public function externalUrlEnds(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', ltrim($url, '"')); $this->query->where('journal_meta.name', '=', 'external_url'); $this->query->whereLike('journal_meta.data', sprintf('%%%s', $url)); @@ -348,7 +350,7 @@ trait MetaCollection public function externalUrlStarts(string $url): GroupCollectorInterface { $this->joinMetaDataTables(); - $url = (string) \Safe\json_encode($url); + $url = (string) json_encode($url); $url = str_replace('\\', '\\\\', rtrim($url, '"')); // var_dump($url); @@ -399,7 +401,7 @@ trait MetaCollection public function internalReferenceContains(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); // var_dump($internalReference); // exit; @@ -414,7 +416,7 @@ trait MetaCollection public function internalReferenceDoesNotContain(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -427,7 +429,7 @@ trait MetaCollection public function internalReferenceDoesNotEnd(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -440,7 +442,7 @@ trait MetaCollection public function internalReferenceDoesNotStart(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -453,7 +455,7 @@ trait MetaCollection public function internalReferenceEnds(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -466,7 +468,7 @@ trait MetaCollection public function internalReferenceStarts(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); @@ -704,7 +706,7 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_id'); - $this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($externalId))); + $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($externalId))); $this->query->whereNull('journal_meta.deleted_at'); return $this; @@ -714,7 +716,7 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_url'); - $this->query->where('journal_meta.data', '=', \Safe\json_encode($url)); + $this->query->where('journal_meta.data', '=', json_encode($url)); $this->query->whereNull('journal_meta.deleted_at'); return $this; @@ -722,12 +724,12 @@ trait MetaCollection public function setInternalReference(string $internalReference): GroupCollectorInterface { - $internalReference = (string) \Safe\json_encode($internalReference); + $internalReference = (string) json_encode($internalReference); $internalReference = str_replace('\\', '\\\\', trim($internalReference, '"')); $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'internal_reference'); - $this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($internalReference))); + $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($internalReference))); $this->query->whereNull('journal_meta.deleted_at'); return $this; @@ -737,7 +739,7 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'recurrence_id'); - $this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($recurringId))); + $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($recurringId))); $this->query->whereNull('journal_meta.deleted_at'); return $this; @@ -747,7 +749,7 @@ trait MetaCollection { $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'sepa_ct_id'); - $this->query->where('journal_meta.data', '=', sprintf('%s', \Safe\json_encode($sepaCT))); + $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($sepaCT))); $this->query->whereNull('journal_meta.deleted_at'); return $this; diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php index bb19eb13ae..b20a860e88 100644 --- a/app/Helpers/Collector/Extensions/TimeCollection.php +++ b/app/Helpers/Collector/Extensions/TimeCollection.php @@ -73,7 +73,11 @@ trait TimeCollection $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]->lt($start) || $transaction[$field]->gt($end); + if ($transaction[$field]->lt($start)) { + return true; + } + + return $transaction[$field]->gt($end); } } @@ -589,17 +593,17 @@ trait TimeCollection */ public function setRange(?Carbon $start, ?Carbon $end): GroupCollectorInterface { - if (null !== $start && null !== $end && $end < $start) { + if ($start instanceof Carbon && $end instanceof Carbon && $end < $start) { [$start, $end] = [$end, $start]; } // always got to end of day / start of day for ranges. $startStr = $start?->format('Y-m-d 00:00:00'); $endStr = $end?->format('Y-m-d 23:59:59'); - if (null !== $start) { + if ($start instanceof Carbon) { $this->query->where('transaction_journals.date', '>=', $startStr); } - if (null !== $end) { + if ($end instanceof Carbon) { $this->query->where('transaction_journals.date', '<=', $endStr); } diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 036b3de9cc..5daa03922e 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -48,6 +48,8 @@ use Illuminate\Support\Facades\Log; use Closure; use Override; +use function Safe\json_decode; + /** * Class GroupCollector */ @@ -595,7 +597,7 @@ class GroupCollector implements GroupCollectorInterface 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']) { - $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) \Safe\json_decode($result['meta_data']), 0, 10)); + $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) json_decode((string) $result['meta_data']), 0, 10)); } } @@ -1046,7 +1048,7 @@ class GroupCollector implements GroupCollectorInterface */ public function setUser(User $user): GroupCollectorInterface { - if (null === $this->user) { + if (!$this->user instanceof User) { $this->user = $user; $this->startQuery(); } @@ -1106,7 +1108,7 @@ class GroupCollector implements GroupCollectorInterface */ public function setUserGroup(UserGroup $userGroup): GroupCollectorInterface { - if (null === $this->userGroup) { + if (!$this->userGroup instanceof UserGroup) { $this->userGroup = $userGroup; $this->startQueryForGroup(); } diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php index 9f0984da10..aa21319780 100644 --- a/app/Helpers/Report/PopupReport.php +++ b/app/Helpers/Report/PopupReport.php @@ -149,10 +149,10 @@ class PopupReport implements PopupReportInterface ->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation() ; - if (null !== $category) { + if ($category instanceof Category) { $collector->setCategory($category); } - if (null === $category) { + if (!$category instanceof Category) { $collector->withoutCategory(); } diff --git a/app/Helpers/Webhook/Sha3SignatureGenerator.php b/app/Helpers/Webhook/Sha3SignatureGenerator.php index 51306071de..6d42a4ac56 100644 --- a/app/Helpers/Webhook/Sha3SignatureGenerator.php +++ b/app/Helpers/Webhook/Sha3SignatureGenerator.php @@ -24,10 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Helpers\Webhook; +use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\WebhookMessage; use JsonException; +use function Safe\json_encode; + /** * Class Sha3SignatureGenerator */ @@ -47,7 +50,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface $json = ''; try { - $json = \Safe\json_encode($message->message, JSON_THROW_ON_ERROR); + $json = json_encode($message->message, JSON_THROW_ON_ERROR); } catch (JsonException $e) { app('log')->error('Could not generate hash.'); app('log')->error(sprintf('JSON value: %s', $json)); @@ -63,7 +66,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface // The character . // The character . // The actual JSON payload (i.e., the request body) - $timestamp = time(); + $timestamp = Carbon::now()->getTimestamp(); $payload = sprintf('%s.%s', $timestamp, $json); $signature = hash_hmac('sha3-256', $payload, (string) $message->webhook->secret, false); diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php index da3d576cb7..396c21222c 100644 --- a/app/Jobs/CreateAutoBudgetLimits.php +++ b/app/Jobs/CreateAutoBudgetLimits.php @@ -55,7 +55,7 @@ class CreateAutoBudgetLimits implements ShouldQueue */ public function __construct(?Carbon $date) { - if (null !== $date) { + if ($date instanceof Carbon) { $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; @@ -127,7 +127,7 @@ class CreateAutoBudgetLimits implements ShouldQueue // find budget limit: $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end); - if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int) $autoBudget->auto_budget_type) { + if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int) $autoBudget->auto_budget_type) { // that's easy: create one. // do nothing else. $this->createBudgetLimit($autoBudget, $start, $end); @@ -136,14 +136,14 @@ class CreateAutoBudgetLimits implements ShouldQueue return; } - if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int) $autoBudget->auto_budget_type) { + if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int) $autoBudget->auto_budget_type) { // budget limit exists already, $this->createRollover($autoBudget); app('log')->debug(sprintf('Done with auto budget #%d', $autoBudget->id)); return; } - if (null === $budgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int) $autoBudget->auto_budget_type) { + if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int) $autoBudget->auto_budget_type) { // budget limit exists already, $this->createAdjustedLimit($autoBudget); app('log')->debug(sprintf('Done with auto budget #%d', $autoBudget->id)); @@ -256,7 +256,7 @@ class CreateAutoBudgetLimits implements ShouldQueue // has budget limit in previous period? $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); - if (null === $budgetLimit) { + if (!$budgetLimit instanceof BudgetLimit) { app('log')->debug('No budget limit exists in previous period, so create one.'); // if not, create it and we're done. $this->createBudgetLimit($autoBudget, $start, $end); @@ -316,7 +316,7 @@ class CreateAutoBudgetLimits implements ShouldQueue // has budget limit in previous period? $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); - if (null === $budgetLimit) { + if (!$budgetLimit instanceof BudgetLimit) { app('log')->debug('No budget limit exists in previous period, so create one.'); // if not, create standard amount, and we're done. $this->createBudgetLimit($autoBudget, $start, $end); diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 20a14d3895..a70e768868 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -74,7 +74,7 @@ class CreateRecurringTransactions implements ShouldQueue $newDate->startOfDay(); $this->date = $newDate; - if (null !== $date) { + if ($date instanceof Carbon) { $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; @@ -257,7 +257,7 @@ class CreateRecurringTransactions implements ShouldQueue { $startDate = clone $recurrence->first_date; if (null !== $recurrence->latest_date && $recurrence->latest_date->gte($startDate)) { - $startDate = clone $recurrence->latest_date; + return clone $recurrence->latest_date; } return $startDate; @@ -321,7 +321,7 @@ class CreateRecurringTransactions implements ShouldQueue /** @var Carbon $date */ foreach ($occurrences as $date) { $result = $this->handleOccurrence($recurrence, $repetition, $date); - if (null !== $result) { + if ($result instanceof TransactionGroup) { $collection->push($result); } } diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.php index bc17d08316..0a873f925c 100644 --- a/app/Jobs/DownloadExchangeRates.php +++ b/app/Jobs/DownloadExchangeRates.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Jobs; +use FireflyIII\Models\CurrencyExchangeRate; use Carbon\Carbon; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; @@ -39,6 +40,8 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Collection; +use function Safe\json_decode; + /** * Class DownloadExchangeRates */ @@ -67,7 +70,7 @@ class DownloadExchangeRates implements ShouldQueue $userRepository = app(UserRepositoryInterface::class); $this->users = $userRepository->all(); - if (null !== $date) { + if ($date instanceof Carbon) { $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; @@ -113,14 +116,14 @@ class DownloadExchangeRates implements ShouldQueue return; } $body = (string) $res->getBody(); - $json = \Safe\json_decode($body, true); + $json = json_decode($body, true); if (false === $json || null === $json) { app('log')->warning(sprintf('Trying to grab "%s" resulted in bad JSON.', $url)); return; } $date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone')); - if (null === $date) { + if (!$date instanceof Carbon) { return; } $this->saveRates($currency, $date, $json['rates']); @@ -130,7 +133,7 @@ class DownloadExchangeRates implements ShouldQueue { foreach ($rates as $code => $rate) { $to = $this->getCurrency($code); - if (null === $to) { + if (!$to instanceof TransactionCurrency) { app('log')->debug(sprintf('Currency %s is not in use, do not save rate.', $code)); continue; @@ -150,7 +153,7 @@ class DownloadExchangeRates implements ShouldQueue } // find it in the database. $currency = $this->repository->findByCode($code); - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { app('log')->debug(sprintf('Did not find currency %s.', $code)); $this->active[$code] = null; @@ -173,7 +176,7 @@ class DownloadExchangeRates implements ShouldQueue foreach ($this->users as $user) { $this->repository->setUser($user); $existing = $this->repository->getExchangeRate($from, $to, $date); - if (null === $existing) { + if (!$existing instanceof CurrencyExchangeRate) { app('log')->debug(sprintf('Saved rate from %s to %s for user #%d.', $from->code, $to->code, $user->id)); $this->repository->setExchangeRate($from, $to, $date, $rate); } diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index bc18bfe682..d1e34a4164 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Jobs; +use Carbon\Carbon; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Message; use Illuminate\Queue\InteractsWithQueue; @@ -32,6 +33,11 @@ use Illuminate\Support\Facades\Mail; use Symfony\Component\Mailer\Exception\TransportException; use Exception; +use function Safe\json_encode; +use function Safe\file_put_contents; +use function Safe\json_decode; +use function Safe\file_get_contents; + /** * Class MailError. */ @@ -48,7 +54,7 @@ class MailError extends Job implements ShouldQueue $debug = $this->exception; unset($debug['stackTrace'], $debug['headers']); - app('log')->error(sprintf('Exception is: %s', \Safe\json_encode($debug))); + app('log')->error(sprintf('Exception is: %s', json_encode($debug))); } /** @@ -119,11 +125,11 @@ class MailError extends Job implements ShouldQueue if (!file_exists($file)) { Log::debug(sprintf('Wrote new file in "%s"', $file)); - \Safe\file_put_contents($file, \Safe\json_encode($limits, JSON_PRETTY_PRINT)); + file_put_contents($file, json_encode($limits, JSON_PRETTY_PRINT)); } if (file_exists($file)) { Log::debug(sprintf('Read file in "%s"', $file)); - $limits = \Safe\json_decode((string) \Safe\file_get_contents($file), true); + $limits = json_decode((string) file_get_contents($file), true); } // limit reached? foreach ($types as $type => $info) { @@ -131,15 +137,15 @@ class MailError extends Job implements ShouldQueue if (!array_key_exists($type, $limits)) { Log::debug(sprintf('Limit "%s" reset to zero, did not exist yet.', $type)); $limits[$type] = [ - 'time' => time(), + 'time' => Carbon::now()->getTimestamp(), 'sent' => 0, ]; } - if (time() - $limits[$type]['time'] > $info['reset']) { - Log::debug(sprintf('Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', time() - $limits[$type]['time'], $info['reset'])); + if (Carbon::now()->getTimestamp() - $limits[$type]['time'] > $info['reset']) { + Log::debug(sprintf('Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', Carbon::now()->getTimestamp() - $limits[$type]['time'], $info['reset'])); $limits[$type] = [ - 'time' => time(), + 'time' => Carbon::now()->getTimestamp(), 'sent' => 0, ]; } @@ -151,7 +157,7 @@ class MailError extends Job implements ShouldQueue } ++$limits[$type]['sent']; } - \Safe\file_put_contents($file, \Safe\json_encode($limits, JSON_PRETTY_PRINT)); + file_put_contents($file, json_encode($limits, JSON_PRETTY_PRINT)); Log::debug('No limits reached, return FALSE.'); return false; diff --git a/app/Jobs/WarnAboutBills.php b/app/Jobs/WarnAboutBills.php index e79e05ea58..bf8d8ae6d2 100644 --- a/app/Jobs/WarnAboutBills.php +++ b/app/Jobs/WarnAboutBills.php @@ -55,7 +55,7 @@ class WarnAboutBills implements ShouldQueue $newDate->startOfDay(); $this->date = $newDate; - if (null !== $date) { + if ($date instanceof Carbon) { $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; diff --git a/app/Mail/InvitationMail.php b/app/Mail/InvitationMail.php index a41e6dbc6d..d1dd789cbe 100644 --- a/app/Mail/InvitationMail.php +++ b/app/Mail/InvitationMail.php @@ -28,6 +28,8 @@ use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; +use function Safe\parse_url; + /** * Class InvitationMail */ @@ -43,7 +45,7 @@ class InvitationMail extends Mailable */ public function __construct(public string $invitee, public string $admin, public string $url) { - $this->host = (string) \Safe\parse_url($this->url, PHP_URL_HOST); + $this->host = (string) parse_url($this->url, PHP_URL_HOST); } /** diff --git a/app/Models/AccountMeta.php b/app/Models/AccountMeta.php index baefb2f9b7..c053cdafb4 100644 --- a/app/Models/AccountMeta.php +++ b/app/Models/AccountMeta.php @@ -27,6 +27,9 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use function Safe\json_decode; +use function Safe\json_encode; + class AccountMeta extends Model { use ReturnsIntegerIdTrait; @@ -47,11 +50,11 @@ class AccountMeta extends Model public function getDataAttribute(mixed $value): string { - return (string) \Safe\json_decode($value, true); + return (string) json_decode((string) $value, true); } public function setDataAttribute(mixed $value): void { - $this->attributes['data'] = \Safe\json_encode($value); + $this->attributes['data'] = json_encode($value); } } diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php index 93abb2cfc1..78c9e8f44e 100644 --- a/app/Models/Configuration.php +++ b/app/Models/Configuration.php @@ -27,6 +27,9 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; +use function Safe\json_decode; +use function Safe\json_encode; + class Configuration extends Model { use ReturnsIntegerIdTrait; @@ -50,7 +53,7 @@ class Configuration extends Model */ public function getDataAttribute($value) { - return \Safe\json_decode($value); + return json_decode((string) $value); } /** @@ -58,6 +61,6 @@ class Configuration extends Model */ public function setDataAttribute($value): void { - $this->attributes['data'] = \Safe\json_encode($value); + $this->attributes['data'] = json_encode($value); } } diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 00e2aae961..51bfd13e34 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -29,6 +29,9 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use function Safe\json_decode; +use function Safe\json_encode; + class TransactionJournalMeta extends Model { use ReturnsIntegerIdTrait; @@ -52,7 +55,7 @@ class TransactionJournalMeta extends Model */ public function getDataAttribute($value) { - return \Safe\json_decode($value, false); + return json_decode((string) $value, false); } /** @@ -60,7 +63,7 @@ class TransactionJournalMeta extends Model */ public function setDataAttribute($value): void { - $data = \Safe\json_encode($value); + $data = json_encode($value); $this->attributes['data'] = $data; $this->attributes['hash'] = hash('sha256', (string) $data); } diff --git a/app/Notifications/ReturnsAvailableChannels.php b/app/Notifications/ReturnsAvailableChannels.php index 77cebfc2ab..e3b2737b30 100644 --- a/app/Notifications/ReturnsAvailableChannels.php +++ b/app/Notifications/ReturnsAvailableChannels.php @@ -39,7 +39,7 @@ class ReturnsAvailableChannels if ('owner' === $type) { return self::returnOwnerChannels(); } - if ('user' === $type && null !== $user) { + if ('user' === $type && $user instanceof User) { return self::returnUserChannels($user); } diff --git a/app/Notifications/ReturnsSettings.php b/app/Notifications/ReturnsSettings.php index 942e459df4..1d3d763fb3 100644 --- a/app/Notifications/ReturnsSettings.php +++ b/app/Notifications/ReturnsSettings.php @@ -52,7 +52,7 @@ class ReturnsSettings 'ntfy_pass' => '', ]; - if ('user' === $type && null !== $user) { + 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; diff --git a/app/Notifications/User/BillReminder.php b/app/Notifications/User/BillReminder.php index f30a158ead..aebdf1333b 100644 --- a/app/Notifications/User/BillReminder.php +++ b/app/Notifications/User/BillReminder.php @@ -66,12 +66,11 @@ class BillReminder extends Notification private function getSubject(): string { - $message = (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); if (0 === $this->diff) { - $message = (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); + return (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); } - return $message; + return (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); } public function toNtfy(User $notifiable): Message diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index fd0b48b003..263342b753 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -31,6 +31,8 @@ use Illuminate\Support\ServiceProvider; use Laravel\Passport\Passport; use Override; +use function Safe\preg_match; + /** * Class AppServiceProvider */ @@ -48,7 +50,7 @@ class AppServiceProvider extends ServiceProvider 'Cache-Control' => 'no-store', ]; $uuid = (string) request()->header('X-Trace-Id'); - if ('' !== trim($uuid) && (1 === \Safe\preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) { + if ('' !== trim($uuid) && (1 === preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) { $headers['X-Trace-Id'] = $uuid; } diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 149c5eb263..47cae859bc 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -47,6 +47,8 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Storage; use Override; +use function Safe\json_encode; + /** * Class AccountRepository. */ @@ -109,7 +111,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac ->where('accounts.active', true) ->where( static function (EloquentBuilder $q1) use ($number): void { - $json = \Safe\json_encode($number); + $json = json_encode($number); $q1->where('account_meta.name', '=', 'account_number'); $q1->where('account_meta.data', '=', $json); } diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php index c6a7604861..e402922365 100644 --- a/app/Repositories/Account/OperationsRepository.php +++ b/app/Repositories/Account/OperationsRepository.php @@ -150,51 +150,51 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn // depends on transaction type: if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - if (null !== $accounts) { + if ($accounts instanceof Collection) { $collector->setSourceAccounts($accounts); } - if (null !== $opposing) { + if ($opposing instanceof Collection) { $collector->setDestinationAccounts($opposing); } } if (TransactionTypeEnum::DEPOSIT->value === $type) { - if (null !== $accounts) { + if ($accounts instanceof Collection) { $collector->setDestinationAccounts($accounts); } - if (null !== $opposing) { + if ($opposing instanceof Collection) { $collector->setSourceAccounts($opposing); } } // supports only accounts, not opposing. - if (TransactionTypeEnum::TRANSFER->value === $type && null !== $accounts) { + if (TransactionTypeEnum::TRANSFER->value === $type && $accounts instanceof Collection) { $collector->setAccounts($accounts); } - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $collector->setCurrency($currency); } $journals = $collector->getExtractedJournals(); // same but for foreign currencies: - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([$type])->withAccountInformation() ->setForeignCurrency($currency) ; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - if (null !== $accounts) { + if ($accounts instanceof Collection) { $collector->setSourceAccounts($accounts); } - if (null !== $opposing) { + if ($opposing instanceof Collection) { $collector->setDestinationAccounts($opposing); } } if (TransactionTypeEnum::DEPOSIT->value === $type) { - if (null !== $accounts) { + if ($accounts instanceof Collection) { $collector->setDestinationAccounts($accounts); } - if (null !== $opposing) { + if ($opposing instanceof Collection) { $collector->setSourceAccounts($opposing); } } diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index c08acbad8e..ffa70a0274 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Bill; +use FireflyIII\Models\ObjectGroup; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\BillFactory; @@ -119,7 +120,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface { if (null !== $billId) { $searchResult = $this->find($billId); - if (null !== $searchResult) { + if ($searchResult instanceof Bill) { app('log')->debug(sprintf('Found bill based on #%d, will return it.', $billId)); return $searchResult; @@ -127,7 +128,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface } if (null !== $billName) { $searchResult = $this->findByName($billName); - if (null !== $searchResult) { + if ($searchResult instanceof Bill) { app('log')->debug(sprintf('Found bill based on "%s", will return it.', $billName)); return $searchResult; @@ -503,7 +504,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function setObjectGroup(Bill $bill, string $objectGroupTitle): Bill { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); - if (null !== $objectGroup) { + if ($objectGroup instanceof ObjectGroup) { $bill->objectGroups()->sync([$objectGroup->id]); } diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index 41f145c5e9..f04a17d968 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -65,7 +65,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U public function get(?Carbon $start = null, ?Carbon $end = null): Collection { $query = $this->user->availableBudgets()->with(['transactionCurrency']); - if (null !== $start && null !== $end) { + 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')); @@ -123,7 +123,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U ->where('end_date', $end->format('Y-m-d'))->first() ; if (null !== $availableBudget) { - $amount = $availableBudget->amount; + return $availableBudget->amount; } return $amount; @@ -172,10 +172,10 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U { $query = $this->user->availableBudgets(); - if (null !== $start) { + if ($start instanceof Carbon) { $query->where('start_date', '>=', $start->format('Y-m-d')); } - if (null !== $end) { + if ($end instanceof Carbon) { $query->where('end_date', '<=', $end->format('Y-m-d')); } diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index e25af43169..87a18dde34 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -88,7 +88,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->where('budgets.active', true) ->where('budgets.user_id', $this->user->id) ; - if (null !== $budgets && $budgets->count() > 0) { + if ($budgets instanceof Collection && $budgets->count() > 0) { $query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray()); } @@ -135,7 +135,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection { // both are NULL: - if (null === $start && null === $end) { + if (!$start instanceof Carbon && !$end instanceof Carbon) { return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->with(['budget']) ->where('budgets.user_id', $this->user->id) @@ -144,17 +144,17 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ; } // one of the two is NULL. - if (null === $start xor null === $end) { + 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) ; - if (null !== $end) { + if ($end instanceof Carbon) { // end date must be before $end. $query->where('end_date', '<=', $end->format('Y-m-d 00:00:00')); } - if (null !== $start) { + if ($start instanceof Carbon) { // start date must be after $start. $query->where('start_date', '>=', $start->format('Y-m-d 00:00:00')); } @@ -201,17 +201,17 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection { - if (null === $end && null === $start) { + if (!$end instanceof Carbon && !$start instanceof Carbon) { return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']); } - if (null === $end xor null === $start) { + if (!$end instanceof Carbon xor !$start instanceof Carbon) { $query = $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC'); // one of the two is null - if (null !== $end) { + if ($end instanceof Carbon) { // end date must be before $end. $query->where('end_date', '<=', $end->format('Y-m-d 00:00:00')); } - if (null !== $start) { + if ($start instanceof Carbon) { // start date must be after $start. $query->where('start_date', '>=', $start->format('Y-m-d 00:00:00')); } diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 09ffa8a636..6c7cf80784 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -303,16 +303,16 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // first things first: delete when no longer required: $autoBudgetType = array_key_exists('auto_budget_type', $data) ? $data['auto_budget_type'] : null; - if (0 === $autoBudgetType && null !== $autoBudget) { + if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) { // delete! $autoBudget->delete(); return $budget; } - if (0 === $autoBudgetType && null === $autoBudget) { + if (0 === $autoBudgetType && !$autoBudget instanceof AutoBudget) { return $budget; } - if (null === $autoBudgetType && null === $autoBudget) { + if (null === $autoBudgetType && !$autoBudget instanceof AutoBudget) { return $budget; } $this->updateAutoBudget($budget, $data); @@ -393,7 +393,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // grab default currency: $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); - if (null === $autoBudget) { + 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']; @@ -488,14 +488,14 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface app('log')->debug('Now in findBudget()'); app('log')->debug(sprintf('Searching for budget with ID #%d...', $budgetId)); $result = $this->find((int) $budgetId); - if (null === $result && null !== $budgetName && '' !== $budgetName) { + if (!$result instanceof Budget && null !== $budgetName && '' !== $budgetName) { app('log')->debug(sprintf('Searching for budget with name %s...', $budgetName)); $result = $this->findByName($budgetName); } - if (null !== $result) { + if ($result instanceof Budget) { app('log')->debug(sprintf('Found budget #%d: %s', $result->id, $result->name)); } - app('log')->debug(sprintf('Found result is null? %s', var_export(null === $result, true))); + app('log')->debug(sprintf('Found result is null? %s', var_export(!$result instanceof Budget, true))); return $result; } diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php index a82f593217..3cf6e2d846 100644 --- a/app/Repositories/Budget/NoBudgetRepository.php +++ b/app/Repositories/Budget/NoBudgetRepository.php @@ -85,10 +85,10 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $collector->setCurrency($currency); } $collector->withoutBudget(); diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index 45bd5d505f..fe37be9050 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -126,13 +126,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null !== $budgets && $budgets->count() > 0) { + if ($budgets instanceof Collection && $budgets->count() > 0) { $collector->setBudgets($budgets); } - if (null === $budgets || 0 === $budgets->count()) { + if (!$budgets instanceof Collection || 0 === $budgets->count()) { $collector->setBudgets($this->getBudgets()); } $collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation(); @@ -229,13 +229,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ; - if (null !== $accounts) { + if ($accounts instanceof Collection) { $collector->setAccounts($accounts); } - if (null === $budgets) { + if (!$budgets instanceof Collection) { $budgets = $this->getBudgets(); } - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { Log::debug(sprintf('Limit to normal currency %s', $currency->code)); $collector->setNormalCurrency($currency); } @@ -245,7 +245,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $journals = $collector->getExtractedJournals(); // same but for transactions in the foreign currency: - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { Log::debug('STOP looking for transactions in the foreign currency.'); } $summarizer = new TransactionSummarizer($this->user); diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index b56ed2828e..487a467c20 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -111,18 +111,18 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf app('log')->debug('Now in findCategory()'); app('log')->debug(sprintf('Searching for category with ID #%d...', $categoryId)); $result = $this->find((int) $categoryId); - if (null === $result) { + if (!$result instanceof Category) { app('log')->debug(sprintf('Searching for category with name %s...', $categoryName)); $result = $this->findByName((string) $categoryName); - if (null === $result && '' !== (string) $categoryName) { + if (!$result instanceof Category && '' !== (string) $categoryName) { // create it! $result = $this->store(['name' => $categoryName]); } } - if (null !== $result) { + if ($result instanceof Category) { app('log')->debug(sprintf('Found category #%d: %s', $result->id, $result->name)); } - app('log')->debug(sprintf('Found category result is null? %s', var_export(null === $result, true))); + app('log')->debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true))); return $result; } @@ -191,13 +191,13 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $firstJournalDate = $this->getFirstJournalDate($category); $firstTransactionDate = $this->getFirstTransactionDate($category); - if (null === $firstTransactionDate && null === $firstJournalDate) { + if (!$firstTransactionDate instanceof Carbon && !$firstJournalDate instanceof Carbon) { return null; } - if (null === $firstTransactionDate) { + if (!$firstTransactionDate instanceof Carbon) { return $firstJournalDate; } - if (null === $firstJournalDate) { + if (!$firstJournalDate instanceof Carbon) { return $firstTransactionDate; } @@ -279,13 +279,13 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $lastJournalDate = $this->getLastJournalDate($category, $accounts); $lastTransactionDate = $this->getLastTransactionDate($category, $accounts); - if (null === $lastTransactionDate && null === $lastJournalDate) { + if (!$lastTransactionDate instanceof Carbon && !$lastJournalDate instanceof Carbon) { return null; } - if (null === $lastTransactionDate) { + if (!$lastTransactionDate instanceof Carbon) { return $lastJournalDate; } - if (null === $lastJournalDate) { + if (!$lastJournalDate instanceof Carbon) { return $lastTransactionDate; } diff --git a/app/Repositories/Category/NoCategoryRepository.php b/app/Repositories/Category/NoCategoryRepository.php index 8c687125f6..dbaf464eb8 100644 --- a/app/Repositories/Category/NoCategoryRepository.php +++ b/app/Repositories/Category/NoCategoryRepository.php @@ -49,7 +49,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory(); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } $journals = $collector->getExtractedJournals(); @@ -95,7 +95,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->withoutCategory(); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } $journals = $collector->getExtractedJournals(); @@ -140,7 +140,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory(); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } $journals = $collector->getExtractedJournals(); @@ -158,7 +158,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->withoutCategory(); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } $journals = $collector->getExtractedJournals(); @@ -186,7 +186,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value])->withoutCategory(); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } $journals = $collector->getExtractedJournals(); diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php index ff98d9bdab..051769c563 100644 --- a/app/Repositories/Category/OperationsRepository.php +++ b/app/Repositories/Category/OperationsRepository.php @@ -53,14 +53,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); $collector->excludeDestinationAccounts($accounts); // to exclude withdrawals to liabilities. } - if (null !== $categories && $categories->count() > 0) { + if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); @@ -131,14 +131,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); $collector->excludeSourceAccounts($accounts); // to prevent income from liabilities. } - if (null !== $categories && $categories->count() > 0) { + if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation(); @@ -197,10 +197,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]) ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts) ; - if (null !== $categories && $categories->count() > 0) { + if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); @@ -260,10 +260,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]) ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts) ; - if (null !== $categories && $categories->count() > 0) { + if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); @@ -325,10 +325,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $categories = $this->getCategories(); } $collector->setCategories($categories); @@ -350,10 +350,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ->setTypes([TransactionTypeEnum::DEPOSIT->value]) ; - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $categories = $this->getCategories(); } $collector->setCategories($categories); @@ -419,10 +419,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ->setTypes([TransactionTypeEnum::TRANSFER->value]) ; - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null === $categories || 0 === $categories->count()) { + if (!$categories instanceof Collection || 0 === $categories->count()) { $categories = $this->getCategories(); } $collector->setCategories($categories); diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index 2034209c0b..2716d2e21e 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -44,6 +44,8 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Override; +use function Safe\json_encode; + /** * Class CurrencyRepository. */ @@ -82,7 +84,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in accounts: - $meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\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)); @@ -90,7 +92,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // second search using integer check. - $meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\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)); @@ -118,7 +120,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf // is being used in accounts (as integer) $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') - ->where('account_meta.name', 'currency_id')->where('account_meta.data', \Safe\json_encode($currency->id))->count() + ->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode($currency->id))->count() ; if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -237,7 +239,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf { $result = $this->findCurrencyNull($currencyId, $currencyCode); - if (null === $result) { + if (!$result instanceof TransactionCurrency) { Log::debug('Grabbing default currency for this user...'); /** @var null|TransactionCurrency $result */ @@ -260,7 +262,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf { Log::debug(sprintf('Now in findCurrencyNull(%s, "%s")', var_export($currencyId, true), $currencyCode)); $result = $this->find((int) $currencyId); - if (null !== $result) { + if ($result instanceof TransactionCurrency) { Log::debug(sprintf('Found currency by ID: %s', $result->code)); return $result; @@ -269,7 +271,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf Log::debug(sprintf('Searching for currency with code "%s"...', $currencyCode)); $result = $this->findByCode((string) $currencyCode); } - if (null !== $result && false === $result->enabled) { + if ($result instanceof TransactionCurrency && false === $result->enabled) { Log::debug(sprintf('Also enabled currency %s', $result->code)); $this->enable($result); } diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/ExchangeRate/ExchangeRateRepository.php index 6a56c17369..f7936e0979 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepository.php @@ -105,7 +105,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate { $object->rate = $rate; - if (null !== $date) { + if ($date instanceof Carbon) { $object->date = $date; } $object->save(); diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index 7ef358d137..aee44f902b 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -77,13 +77,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac public function firstNull(): ?TransactionJournal { /** @var null|TransactionJournal $entry */ - $entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); - $result = null; + $entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); if (null !== $entry) { - $result = $entry; + return $entry; } - return $result; + return null; } public function getDestinationAccount(TransactionJournal $journal): Account @@ -120,13 +119,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac public function getLast(): ?TransactionJournal { /** @var null|TransactionJournal $entry */ - $entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']); - $result = null; + $entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']); if (null !== $entry) { - $result = $entry; + return $entry; } - return $result; + return null; } public function getLinkNoteText(TransactionJournalLink $link): string diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index f4e59624a7..9b2924b191 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -47,7 +47,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool { - if (null !== $moveTo) { + if ($moveTo instanceof LinkType) { TransactionJournalLink::where('link_type_id', $linkType->id)->update(['link_type_id' => $moveTo->id]); } $linkType->delete(); @@ -125,7 +125,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf ->whereNull('dest_journals.deleted_at') ; - if (null !== $linkType) { + if ($linkType instanceof LinkType) { $query->where('journal_links.link_type_id', $linkType->id); } @@ -177,17 +177,17 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf { $linkType = $this->find((int) ($information['link_type_id'] ?? 0)); - if (null === $linkType) { + if (!$linkType instanceof LinkType) { $linkType = $this->findByName($information['link_type_name']); } - if (null === $linkType) { + if (!$linkType instanceof LinkType) { return null; } // might exist already: $existing = $this->findSpecificLink($linkType, $inward, $outward); - if (null !== $existing) { + if ($existing instanceof TransactionJournalLink) { return $existing; } diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index 497b8a6ca3..dbead1a4af 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\PiggyBank; +use FireflyIII\User; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\PiggyBankFactory; @@ -69,7 +70,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte if (null !== $piggyBankId) { $searchResult = $this->find($piggyBankId); - if (null !== $searchResult) { + if ($searchResult instanceof PiggyBank) { app('log')->debug(sprintf('Found piggy based on #%d, will return it.', $piggyBankId)); return $searchResult; @@ -77,7 +78,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } if (null !== $piggyBankName) { $searchResult = $this->findByName($piggyBankName); - if (null !== $searchResult) { + if ($searchResult instanceof PiggyBank) { app('log')->debug(sprintf('Found piggy based on "%s", will return it.', $piggyBankName)); return $searchResult; @@ -133,7 +134,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte { $sum = '0'; foreach ($piggyBank->accounts as $current) { - if (null !== $account && $account->id !== $current->id) { + if ($account instanceof Account && $account->id !== $current->id) { continue; } $amount = (string) $current->pivot->native_current_amount; @@ -267,7 +268,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte { $sum = '0'; foreach ($piggyBank->accounts as $current) { - if (null !== $account && $account->id !== $current->id) { + if ($account instanceof Account && $account->id !== $current->id) { continue; } $amount = (string) $current->pivot->current_amount; @@ -311,10 +312,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ; - if (null === $this->user) { + if (!$this->user instanceof User) { $query->where('accounts.user_group_id', $this->userGroup->id); } - if (null !== $this->user) { + if ($this->user instanceof User) { $query->where('accounts.user_id', $this->user->id); } diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 689e1ace72..e12a543e38 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -50,6 +50,9 @@ use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; +use function Safe\json_decode; + /** * Class RecurringRepository */ @@ -68,16 +71,16 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte $set = TransactionJournalMeta::where(static function (Builder $q1) use ($recurrence): void { $q1->where('name', 'recurrence_id'); - $q1->where('data', \Safe\json_encode((string) $recurrence->id)); + $q1->where('data', json_encode((string) $recurrence->id)); })->get(['journal_meta.transaction_journal_id']); // there are X journals made for this recurrence. Any of them meant for today? foreach ($set as $journalMeta) { $count = TransactionJournalMeta::where(static function (Builder $q2) use ($date): void { $string = (string) $date; - app('log')->debug(sprintf('Search for date: %s', \Safe\json_encode($string))); + app('log')->debug(sprintf('Search for date: %s', json_encode($string))); $q2->where('name', 'recurrence_date'); - $q2->where('data', \Safe\json_encode($string)); + $q2->where('data', json_encode($string)); }) ->where('transaction_journal_id', $journalMeta->transaction_journal_id) ->count() @@ -212,10 +215,10 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('journal_meta.name', 'recurrence_id') ->where('journal_meta.data', '"'.$recurrence->id.'"') ; - if (null !== $start) { + if ($start instanceof Carbon) { $query->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00')); } - if (null !== $end) { + if ($end instanceof Carbon) { $query->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00')); } $count = $query->count('transaction_journals.id'); @@ -232,7 +235,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return TransactionJournalMeta::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id') ->where('transaction_journals.user_id', $this->user->id) ->where('journal_meta.name', '=', 'recurrence_id') - ->where('journal_meta.data', '=', \Safe\json_encode((string) $recurrence->id)) + ->where('journal_meta.data', '=', json_encode((string) $recurrence->id)) ->get(['journal_meta.transaction_journal_id'])->pluck('transaction_journal_id')->toArray() ; } @@ -272,7 +275,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** @var RecurrenceMeta $meta */ foreach ($transaction->recurrenceTransactionMeta as $meta) { if ('tags' === $meta->name && '' !== $meta->value) { - $tags = \Safe\json_decode($meta->value, true, 512, JSON_THROW_ON_ERROR); + $tags = json_decode((string) $meta->value, true, 512, JSON_THROW_ON_ERROR); } } @@ -285,7 +288,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->whereNull('transaction_journals.deleted_at') ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') - ->where('data', \Safe\json_encode((string) $recurrence->id)) + ->where('data', json_encode((string) $recurrence->id)) ->get()->pluck('transaction_journal_id')->toArray() ; $search = []; @@ -311,7 +314,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->whereNull('transaction_journals.deleted_at') ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') - ->where('data', \Safe\json_encode((string) $recurrence->id)) + ->where('data', json_encode((string) $recurrence->id)) ->get()->pluck('transaction_journal_id')->toArray() ; $search = []; @@ -406,7 +409,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte private function filterMaxDate(?Carbon $max, array $occurrences): array { $filtered = []; - if (null === $max) { + if (!$max instanceof Carbon) { foreach ($occurrences as $date) { if ($date->gt(today())) { $filtered[] = $date; @@ -476,7 +479,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte if ('yearly' === $repetition->repetition_type) { $today = today(config('app.timezone'))->endOfYear(); $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); - if (null === $repDate) { + if (!$repDate instanceof Carbon) { $repDate = clone $today; } $diffInYears = (int) $today->diffInYears($repDate, true); diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index 4a57735e2d..3e1694baee 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -79,7 +79,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte { /** @var Rule $rule */ foreach ($ruleGroup->rules as $rule) { - if (null === $moveTo) { + if (!$moveTo instanceof RuleGroup) { $rule->delete(); continue; @@ -92,7 +92,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte $ruleGroup->delete(); $this->resetOrder(); - if (null !== $moveTo) { + if ($moveTo instanceof RuleGroup) { $this->resetRuleOrder($moveTo); } diff --git a/app/Repositories/Tag/OperationsRepository.php b/app/Repositories/Tag/OperationsRepository.php index 9fe781fd00..94ba8a0db5 100644 --- a/app/Repositories/Tag/OperationsRepository.php +++ b/app/Repositories/Tag/OperationsRepository.php @@ -50,14 +50,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); $tagIds = []; - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null !== $tags && $tags->count() > 0) { + if ($tags instanceof Collection && $tags->count() > 0) { $collector->setTags($tags); $tagIds = $tags->pluck('id')->toArray(); } - if (null === $tags || 0 === $tags->count()) { + if (!$tags instanceof Collection || 0 === $tags->count()) { $collector->setTags($this->getTags()); $tagIds = $this->getTags()->pluck('id')->toArray(); } @@ -133,14 +133,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); $tagIds = []; - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null !== $tags && $tags->count() > 0) { + if ($tags instanceof Collection && $tags->count() > 0) { $collector->setTags($tags); $tagIds = $tags->pluck('id')->toArray(); } - if (null === $tags || 0 === $tags->count()) { + if (!$tags instanceof Collection || 0 === $tags->count()) { $collector->setTags($this->getTags()); $tagIds = $this->getTags()->pluck('id')->toArray(); } diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 937c6492da..ad3ada6789 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -231,7 +231,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $collector->setRange($start, $end); } @@ -354,7 +354,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { $location = $this->getLocation($tag); - if (null === $location) { + if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($tag); } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 8f9b793aa9..8ca4cfcd8c 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -50,6 +50,8 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Exception; +use function Safe\json_decode; + /** * Class TransactionGroupRepository */ @@ -245,15 +247,14 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, $currency = $transaction->transactionCurrency; $type = $journal->transactionType->type; $amount = app('steam')->positive($transaction->amount); - $return = ''; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); + return app('amount')->formatAnything($currency, app('steam')->negative($amount)); } if (TransactionTypeEnum::WITHDRAWAL->value !== $type) { - $return = app('amount')->formatAnything($currency, $amount); + return app('amount')->formatAnything($currency, $amount); } - return $return; + return ''; } private function getFormattedForeignAmount(TransactionJournal $journal): string @@ -269,15 +270,14 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, $currency = $transaction->foreignCurrency; $type = $journal->transactionType->type; $amount = app('steam')->positive($transaction->foreign_amount); - $return = ''; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { - $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); + return app('amount')->formatAnything($currency, app('steam')->negative($amount)); } if (TransactionTypeEnum::WITHDRAWAL->value !== $type) { - $return = app('amount')->formatAnything($currency, $amount); + return app('amount')->formatAnything($currency, $amount); } - return $return; + return ''; } public function getLocation(int $journalId): ?Location @@ -305,7 +305,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, $return = []; foreach ($query as $row) { - $return[$row->name] = new Carbon(\Safe\json_decode($row->data, true, 512, JSON_THROW_ON_ERROR)); + $return[$row->name] = new Carbon(json_decode((string) $row->data, true, 512, JSON_THROW_ON_ERROR)); } return new NullArrayObject($return); @@ -325,7 +325,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, $return = []; foreach ($query as $row) { - $return[$row->name] = \Safe\json_decode($row->data); + $return[$row->name] = json_decode((string) $row->data); } return new NullArrayObject($return); diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php index 0576e9018c..55c0e2abe5 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepository.php +++ b/app/Repositories/TransactionType/TransactionTypeRepository.php @@ -36,14 +36,14 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType { app('log')->debug('Now looking for a transaction type.'); - if (null !== $type) { + if ($type instanceof TransactionType) { app('log')->debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type)); return $type; } $typeString ??= TransactionTypeEnum::WITHDRAWAL->value; $search = $this->findByType($typeString); - if (null === $search) { + if (!$search instanceof TransactionType) { $search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value); } app('log')->debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type)); diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index 5c018c6e04..e7d89c4a26 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\User; +use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\GroupMembership; @@ -56,7 +57,7 @@ class UserRepository implements UserRepositoryInterface // save old email as pref app('preferences')->setForUser($user, 'previous_email_latest', $oldEmail); - app('preferences')->setForUser($user, 'previous_email_'.date('Y-m-d-H-i-s'), $oldEmail); + app('preferences')->setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); // set undo and confirm token: app('preferences')->setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16))); @@ -230,7 +231,7 @@ class UserRepository implements UserRepositoryInterface public function hasRole(null|Authenticatable|User $user, string $role): bool { - if (null === $user) { + if (!$user instanceof Authenticatable) { return false; } if ($user instanceof User) { @@ -391,7 +392,7 @@ class UserRepository implements UserRepositoryInterface // save old email as pref app('preferences')->setForUser($user, 'admin_previous_email_latest', $oldEmail); - app('preferences')->setForUser($user, 'admin_previous_email_'.date('Y-m-d-H-i-s'), $oldEmail); + app('preferences')->setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); $user->email = $newEmail; $user->save(); @@ -405,7 +406,7 @@ class UserRepository implements UserRepositoryInterface public function removeRole(User $user, string $role): void { $roleObj = $this->getRole($role); - if (null === $roleObj) { + if (!$roleObj instanceof Role) { return; } $user->roles()->detach($roleObj->id); diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php index 15f49774ee..f30033dea3 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -134,7 +134,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $existingGroup = null; while ($exists && $loop < 10) { $existingGroup = $this->findByName($groupName); - if (null === $existingGroup) { + if (!$existingGroup instanceof UserGroup) { $exists = false; /** @var null|UserGroup $existingGroup */ diff --git a/app/Repositories/UserGroups/Account/AccountRepository.php b/app/Repositories/UserGroups/Account/AccountRepository.php index 15d8b4d52a..418f16ef8b 100644 --- a/app/Repositories/UserGroups/Account/AccountRepository.php +++ b/app/Repositories/UserGroups/Account/AccountRepository.php @@ -40,6 +40,8 @@ use Illuminate\Support\Facades\DB; use Override; use stdClass; +use function Safe\json_encode; + /** * Class AccountRepository * @@ -68,7 +70,7 @@ class AccountRepository implements AccountRepositoryInterface ->where('accounts.active', true) ->where( static function (EloquentBuilder $q1) use ($number): void { - $json = \Safe\json_encode($number); + $json = json_encode($number); $q1->where('account_meta.name', '=', 'account_number'); $q1->where('account_meta.data', '=', $json); } @@ -167,7 +169,7 @@ class AccountRepository implements AccountRepositoryInterface { $account = $this->user->accounts()->find($accountId); if (null === $account) { - $account = $this->userGroup->accounts()->find($accountId); + return $this->userGroup->accounts()->find($accountId); } /** @var null|Account */ diff --git a/app/Repositories/UserGroups/Budget/OperationsRepository.php b/app/Repositories/UserGroups/Budget/OperationsRepository.php index c5775be29e..78944b9d51 100644 --- a/app/Repositories/UserGroups/Budget/OperationsRepository.php +++ b/app/Repositories/UserGroups/Budget/OperationsRepository.php @@ -49,13 +49,13 @@ class OperationsRepository implements OperationsRepositoryInterface /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setUserGroup($this->userGroup)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - if (null !== $accounts && $accounts->count() > 0) { + if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - if (null !== $budgets && $budgets->count() > 0) { + if ($budgets instanceof Collection && $budgets->count() > 0) { $collector->setBudgets($budgets); } - if (null === $budgets || (0 === $budgets->count())) { + if (!$budgets instanceof Collection || (0 === $budgets->count())) { $collector->setBudgets($this->getBudgets()); } $collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation(); diff --git a/app/Repositories/UserGroups/Currency/CurrencyRepository.php b/app/Repositories/UserGroups/Currency/CurrencyRepository.php index 092ef4b50c..eddd408446 100644 --- a/app/Repositories/UserGroups/Currency/CurrencyRepository.php +++ b/app/Repositories/UserGroups/Currency/CurrencyRepository.php @@ -41,6 +41,8 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; + /** * Class CurrencyRepository * @@ -81,7 +83,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface } // is being used in accounts: - $meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\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)); @@ -89,7 +91,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface } // second search using integer check. - $meta = AccountMeta::where('name', 'currency_id')->where('data', \Safe\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)); @@ -117,7 +119,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface // is being used in accounts (as integer) $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') - ->where('account_meta.name', 'currency_id')->where('account_meta.data', \Safe\json_encode($currency->id))->count() + ->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode($currency->id))->count() ; if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -239,7 +241,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface { $result = $this->findCurrencyNull($currencyId, $currencyCode); - if (null === $result) { + if (!$result instanceof TransactionCurrency) { Log::debug('Grabbing default currency for this user...'); /** @var null|TransactionCurrency $result */ @@ -262,11 +264,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface { Log::debug(sprintf('Now in findCurrencyNull("%s", "%s")', $currencyId, $currencyCode)); $result = $this->find((int) $currencyId); - if (null === $result) { + if (!$result instanceof TransactionCurrency) { Log::debug(sprintf('Searching for currency with code "%s"...', $currencyCode)); $result = $this->findByCode((string) $currencyCode); } - if (null !== $result && false === $result->enabled) { + if ($result instanceof TransactionCurrency && false === $result->enabled) { Log::debug(sprintf('Also enabled currency %s', $result->code)); $this->enable($result); } diff --git a/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php index 56e0fcb1df..3dc1d6a797 100644 --- a/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php @@ -109,7 +109,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate { $object->rate = $rate; - if (null !== $date) { + if ($date instanceof Carbon) { $object->date = $date; } $object->save(); diff --git a/app/Rules/IsValidBulkClause.php b/app/Rules/IsValidBulkClause.php index 10ce75cf86..8be8759eed 100644 --- a/app/Rules/IsValidBulkClause.php +++ b/app/Rules/IsValidBulkClause.php @@ -29,6 +29,8 @@ use Illuminate\Support\Facades\Validator; use Closure; use JsonException; +use function Safe\json_decode; + /** * Class IsValidBulkClause */ @@ -65,7 +67,7 @@ class IsValidBulkClause implements ValidationRule private function basicValidation(string $value): bool { try { - $array = \Safe\json_decode($value, true, 8, JSON_THROW_ON_ERROR); + $array = json_decode($value, true, 8, JSON_THROW_ON_ERROR); } catch (JsonException) { $this->error = (string) trans('validation.json'); diff --git a/app/Rules/IsValidPositiveAmount.php b/app/Rules/IsValidPositiveAmount.php index c232bb02ef..2c6eeb63cd 100644 --- a/app/Rules/IsValidPositiveAmount.php +++ b/app/Rules/IsValidPositiveAmount.php @@ -30,6 +30,8 @@ use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; use Closure; +use function Safe\json_encode; + class IsValidPositiveAmount implements ValidationRule { use ValidatesAmountsTrait; @@ -41,7 +43,7 @@ class IsValidPositiveAmount implements ValidationRule { if (is_array($value)) { $fail('validation.numeric')->translate(); - $message = sprintf('IsValidPositiveAmount: "%s" is not a number.', \Safe\json_encode($value)); + $message = sprintf('IsValidPositiveAmount: "%s" is not a number.', json_encode($value)); Log::debug($message); Log::channel('audit')->info($message); diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index 554bb2bbd0..9cfae9d359 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -30,6 +30,8 @@ use FireflyIII\Models\AccountMeta; use Illuminate\Contracts\Validation\ValidationRule; use Closure; +use function Safe\json_encode; + /** * Class UniqueAccountNumber */ @@ -134,10 +136,10 @@ 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', \Safe\json_encode($accountNumber)) + ->where('account_meta.data', json_encode($accountNumber)) ; - if (null !== $this->account) { + 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 aaff70fb49..9246326c15 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -160,7 +160,7 @@ class UniqueIban implements ValidationRule ->whereIn('account_types.type', $typesArray) ; - if (null !== $this->account) { + if ($this->account instanceof Account) { $query->where('accounts.id', '!=', $this->account->id); } diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index f526efcb1e..9516071ddb 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -31,6 +31,8 @@ use GuzzleHttp\Exception\GuzzleException; use Illuminate\Support\Facades\Log; use JsonException; +use function Safe\json_decode; + /** * Class UpdateRequest */ @@ -100,7 +102,7 @@ class UpdateRequest implements UpdateRequestInterface $body = (string) $res->getBody(); try { - $json = \Safe\json_decode($body, true, 512, JSON_THROW_ON_ERROR); + $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { Log::error('Body is not valid JSON'); Log::error($body); @@ -118,7 +120,7 @@ class UpdateRequest implements UpdateRequestInterface // parse response a bit. No message yet. $response = $json['firefly_iii'][$channel]; $date = Carbon::createFromFormat('Y-m-d', $response['date']); - if (null === $date) { + if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $return['version'] = $response['version']; diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index ecfaddb147..e2e4cb994b 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -44,12 +44,12 @@ class AccountDestroyService // find and delete opening balance journal + opposing account $this->destroyOpeningBalance($account); - if (null !== $moveTo) { + if ($moveTo instanceof Account) { $this->moveTransactions($account, $moveTo); $this->updateRecurrences($account, $moveTo); } // delete recurring transactions with this account: - if (null === $moveTo) { + if (!$moveTo instanceof Account) { $this->destroyRecurrences($account); } diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php index 7c105ac472..da77efb15a 100644 --- a/app/Services/Internal/Support/CreditRecalculateService.php +++ b/app/Services/Internal/Support/CreditRecalculateService.php @@ -60,10 +60,10 @@ class CreditRecalculateService if (true !== config('firefly.feature_flags.handle_debts')) { return; } - if (null !== $this->group && null === $this->account) { + if ($this->group instanceof TransactionGroup && !$this->account instanceof Account) { $this->processGroup(); } - if (null !== $this->account && null === $this->group) { + if ($this->account instanceof Account && !$this->group instanceof TransactionGroup) { // work based on account. $this->processAccount(); } @@ -163,7 +163,7 @@ class CreditRecalculateService $this->repository->setUser($account->user); $direction = (string) $this->repository->getMetaValue($account, 'liability_direction'); $openingBalance = $this->repository->getOpeningBalance($account); - if (null !== $openingBalance) { + if ($openingBalance instanceof TransactionJournal) { // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id)); // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account: if ('debit' === $direction) { @@ -358,7 +358,7 @@ class CreditRecalculateService { $usedAmount = $transaction->amount; // Log::debug(sprintf('Amount of transaction is %s', app('steam')->bcround($usedAmount, 2))); - if (null !== $foreignCurrency && $foreignCurrency->id === $accountCurrency->id) { + if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $accountCurrency->id) { $usedAmount = $transaction->foreign_amount; // Log::debug(sprintf('Overruled by foreign amount. Amount of transaction is now %s', app('steam')->bcround($usedAmount, 2))); } diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index 507f65e95e..d0de5db9df 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -39,6 +39,8 @@ use FireflyIII\Rules\UniqueIban; use FireflyIII\Support\NullArrayObject; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; + /** * Trait JournalServiceTrait */ @@ -140,7 +142,7 @@ trait JournalServiceTrait private function findAccountByIban(?Account $account, array $data, array $types): ?Account { - if (null !== $account) { + if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); return $account; @@ -167,7 +169,7 @@ trait JournalServiceTrait private function findAccountByNumber(?Account $account, array $data, array $types): ?Account { - if (null !== $account) { + if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); return $account; @@ -196,7 +198,7 @@ trait JournalServiceTrait private function findAccountByName(?Account $account, array $data, array $types): ?Account { - if (null !== $account) { + if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); return $account; @@ -247,7 +249,7 @@ trait JournalServiceTrait { Log::debug('Now in createAccount()', $data); // return new account. - if (null !== $account) { + if ($account instanceof Account) { Log::debug( sprintf( 'Was given %s account #%d ("%s") so will simply return that.', @@ -257,10 +259,10 @@ trait JournalServiceTrait ) ); } - if (null === $account) { + if (!$account instanceof Account) { // final attempt, create it. if (AccountTypeEnum::ASSET->value === $preferredType) { - throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s', \Safe\json_encode($data))); + throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s', json_encode($data))); } // fix name of account if only IBAN is given: if ('' === (string) $data['name'] && '' !== (string) $data['iban']) { @@ -320,7 +322,7 @@ trait JournalServiceTrait private function getCashAccount(?Account $account, array $data, array $types): ?Account { // return cash account. - if (null === $account && '' === (string) $data['name'] + if (!$account instanceof Account && '' === (string) $data['name'] && in_array(AccountTypeEnum::CASH->value, $types, true)) { $account = $this->accountRepository->getCashAccount(); } diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index 95b5520599..84771766cf 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -43,6 +43,8 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Validation\AccountValidator; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; + /** * Trait RecurringTransactionTrait */ @@ -307,9 +309,9 @@ trait RecurringTransactionTrait /** @var null|RecurrenceMeta $entry */ $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); if (null === $entry) { - $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => \Safe\json_encode($tags)]); + $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]); } - $entry->value = \Safe\json_encode($tags); + $entry->value = json_encode($tags); $entry->save(); } if (0 === count($tags)) { diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index eddea89eec..5e1f230b4d 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -238,7 +238,7 @@ class AccountUpdateService // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { $location = $this->accountRepository->getLocation($account); - if (null === $location) { + if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($account); } diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index d56bb2cc8c..8726cd7ebc 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; +use FireflyIII\Models\ObjectGroup; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Models\Bill; @@ -100,7 +101,7 @@ class BillUpdateService $objectGroupTitle = $data['object_group_title'] ?? ''; if ('' !== $objectGroupTitle) { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); - if (null !== $objectGroup) { + if ($objectGroup instanceof ObjectGroup) { $bill->objectGroups()->sync([$objectGroup->id]); $bill->save(); } @@ -116,7 +117,7 @@ class BillUpdateService $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); - if (null !== $objectGroup) { + if ($objectGroup instanceof ObjectGroup) { $bill->objectGroups()->sync([$objectGroup->id]); $bill->save(); } @@ -232,14 +233,14 @@ class BillUpdateService /** @var Rule $rule */ foreach ($rules as $rule) { $trigger = $this->getRuleTrigger($rule, $key); - if (null !== $trigger && $trigger->trigger_value === $oldValue) { + if ($trigger instanceof RuleTrigger && $trigger->trigger_value === $oldValue) { app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); $trigger->trigger_value = $newValue; $trigger->save(); continue; } - if (null !== $trigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true) + if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true) && 0 === bccomp($trigger->trigger_value, $oldValue)) { app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); $trigger->trigger_value = $newValue; diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index 45bcf06d82..384f304938 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -187,10 +187,10 @@ class GroupUpdateService Log::debug('Call createTransactionJournal'); $newJournal = $this->createTransactionJournal($transactionGroup, $transaction); Log::debug('Done calling createTransactionJournal'); - if (null !== $newJournal) { + if ($newJournal instanceof TransactionJournal) { $updated[] = $newJournal->id; } - if (null === $newJournal) { + if (!$newJournal instanceof TransactionJournal) { Log::error('createTransactionJournal returned NULL, indicating something went wrong.'); } } diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index 671e0bcb4f..025c048965 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -226,7 +226,7 @@ class JournalUpdateService private function getOriginalSourceAccount(): Account { - if (null === $this->sourceAccount) { + if (!$this->sourceAccount instanceof Account) { $source = $this->getSourceTransaction(); $this->sourceAccount = $source->account; } @@ -236,7 +236,7 @@ class JournalUpdateService private function getSourceTransaction(): Transaction { - if (null === $this->sourceTransaction) { + if (!$this->sourceTransaction instanceof Transaction) { /** @var null|Transaction $result */ $result = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first(); $this->sourceTransaction = $result; @@ -304,7 +304,7 @@ class JournalUpdateService private function getOriginalDestinationAccount(): Account { - if (null === $this->destinationAccount) { + if (!$this->destinationAccount instanceof Account) { $destination = $this->getDestinationTransaction(); $this->destinationAccount = $destination->account; } @@ -317,7 +317,7 @@ class JournalUpdateService */ private function getDestinationTransaction(): Transaction { - if (null === $this->destinationTransaction) { + if (!$this->destinationTransaction instanceof Transaction) { /** @var null|Transaction $result */ $result = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); $this->destinationTransaction = $result; diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index 0503647bb0..7cad86a146 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -145,7 +145,7 @@ class RecurrenceUpdateService app('log')->debug('Loop and find'); foreach ($repetitions as $current) { $match = $this->matchRepetition($recurrence, $current); - if (null === $match) { + if (!$match instanceof RecurrenceRepetition) { throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.'); } $fields = [ diff --git a/app/Services/Webhook/StandardWebhookSender.php b/app/Services/Webhook/StandardWebhookSender.php index 1e312ed408..0962d538aa 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -34,6 +34,8 @@ use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; use JsonException; +use function Safe\json_encode; + /** * Class StandardWebhookSender */ @@ -81,7 +83,7 @@ class StandardWebhookSender implements WebhookSenderInterface app('log')->debug(sprintf('Trying to send webhook message #%d', $this->message->id)); try { - $json = \Safe\json_encode($this->message->message, JSON_THROW_ON_ERROR); + $json = json_encode($this->message->message, JSON_THROW_ON_ERROR); } catch (JsonException $e) { app('log')->error('Did not send message because of a JSON error.'); app('log')->error($e->getMessage()); diff --git a/app/Support/Amount.php b/app/Support/Amount.php index 0b419769ff..e58c313aac 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -115,7 +115,7 @@ class Amount public function convertToNative(?User $user = null): bool { - if (null === $user) { + if (!$user instanceof User) { return true === Preferences::get('convert_to_native', false)->data && true === config('cer.enabled'); // Log::debug(sprintf('convertToNative [a]: %s', var_export($result, true))); } @@ -286,7 +286,7 @@ class Amount public static function getAmountJsConfig(bool $sepBySpace, int $signPosn, string $sign, bool $csPrecedes): string { // negative first: - $space = ' '; + $space = ' '; // require space between symbol and amount? if (false === $sepBySpace) { @@ -295,11 +295,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 @@ -340,14 +340,10 @@ class Amount $posC = $sign; } - // default is amount before currency - $format = $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE; - if ($csPrecedes) { - // alternative is currency before amount - $format = $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE; + return $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE; } - return $format; + return $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE; } } diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index f3e3c68d34..ab21cdf260 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -56,7 +56,7 @@ class RemoteUserGuard implements Guard public function authenticate(): void { Log::debug(sprintf('Now at %s', __METHOD__)); - if (null !== $this->user) { + if ($this->user instanceof User) { Log::debug(sprintf('%s is found: #%d, "%s".', $this->user::class, $this->user->id, $this->user->email)); return; @@ -112,14 +112,14 @@ class RemoteUserGuard implements Guard { Log::debug(sprintf('Now at %s', __METHOD__)); - return null !== $this->user(); + return $this->user() instanceof User; } public function user(): ?User { Log::debug(sprintf('Now at %s', __METHOD__)); $user = $this->user; - if (null === $user) { + if (!$user instanceof User) { Log::debug('User is NULL'); return null; diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index a025795044..b81f040467 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -23,10 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Support; +use Carbon\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Cache; use JsonException; +use function Safe\json_encode; + /** * Class CacheProperties. */ @@ -80,10 +83,10 @@ class CacheProperties $content = ''; foreach ($this->properties as $property) { try { - $content = sprintf('%s%s', $content, \Safe\json_encode($property, JSON_THROW_ON_ERROR)); + $content = sprintf('%s%s', $content, json_encode($property, JSON_THROW_ON_ERROR)); } catch (JsonException) { // @ignoreException - $content = sprintf('%s%s', $content, hash('sha256', (string) time())); + $content = sprintf('%s%s', $content, hash('sha256', (string) Carbon::now()->getTimestamp())); } } $this->hash = substr(hash('sha256', $content), 0, 16); diff --git a/app/Support/Calendar/Calculator.php b/app/Support/Calendar/Calculator.php index f9fa6ffe67..8d200fba17 100644 --- a/app/Support/Calendar/Calculator.php +++ b/app/Support/Calendar/Calculator.php @@ -65,7 +65,7 @@ class Calculator private static function loadIntervalMap(): SplObjectStorage { - if (null !== self::$intervalMap) { + if (self::$intervalMap instanceof SplObjectStorage) { return self::$intervalMap; } self::$intervalMap = new SplObjectStorage(); diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php index 239015bf20..8183f4283c 100644 --- a/app/Support/Chart/Category/WholePeriodChartGenerator.php +++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php @@ -124,7 +124,7 @@ class WholePeriodChartGenerator $step = '1M'; } if ($months > 100) { - $step = '1Y'; + return '1Y'; } return $step; diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php index a2889ddc06..3d88f51fd2 100644 --- a/app/Support/Cronjobs/AutoBudgetCronjob.php +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -38,7 +38,7 @@ class AutoBudgetCronjob extends AbstractCronjob /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_ab_job', 0); $lastTime = (int) $config->data; - $diff = time() - $lastTime; + $diff = Carbon::now()->getTimestamp() - $lastTime; $diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { app('log')->info('Auto budget cron-job has never fired before.'); diff --git a/app/Support/Cronjobs/BillWarningCronjob.php b/app/Support/Cronjobs/BillWarningCronjob.php index 0e711195d8..f3861fb787 100644 --- a/app/Support/Cronjobs/BillWarningCronjob.php +++ b/app/Support/Cronjobs/BillWarningCronjob.php @@ -44,7 +44,7 @@ class BillWarningCronjob extends AbstractCronjob /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_bw_job', 0); $lastTime = (int) $config->data; - $diff = time() - $lastTime; + $diff = Carbon::now()->getTimestamp() - $lastTime; $diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { diff --git a/app/Support/Cronjobs/ExchangeRatesCronjob.php b/app/Support/Cronjobs/ExchangeRatesCronjob.php index 556e8e7618..b54c76a242 100644 --- a/app/Support/Cronjobs/ExchangeRatesCronjob.php +++ b/app/Support/Cronjobs/ExchangeRatesCronjob.php @@ -39,7 +39,7 @@ class ExchangeRatesCronjob extends AbstractCronjob /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_cer_job', 0); $lastTime = (int) $config->data; - $diff = time() - $lastTime; + $diff = Carbon::now()->getTimestamp() - $lastTime; $diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { Log::info('Exchange rates cron-job has never fired before.'); diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index 2379b937c2..995f31e777 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -44,7 +44,7 @@ class RecurringCronjob extends AbstractCronjob /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_rt_job', 0); $lastTime = (int) $config->data; - $diff = time() - $lastTime; + $diff = Carbon::now()->getTimestamp() - $lastTime; $diffForHumans = today(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { diff --git a/app/Support/Cronjobs/UpdateCheckCronjob.php b/app/Support/Cronjobs/UpdateCheckCronjob.php index dd1f603797..15e3eb5221 100644 --- a/app/Support/Cronjobs/UpdateCheckCronjob.php +++ b/app/Support/Cronjobs/UpdateCheckCronjob.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; +use Carbon\Carbon; use FireflyIII\Helpers\Update\UpdateTrait; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; @@ -55,8 +56,8 @@ class UpdateCheckCronjob extends AbstractCronjob // TODO this is duplicate. /** @var Configuration $lastCheckTime */ - $lastCheckTime = FireflyConfig::get('last_update_check', time()); - $now = time(); + $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) { @@ -64,7 +65,7 @@ class UpdateCheckCronjob extends AbstractCronjob $this->jobFired = false; $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data)); + $this->message = sprintf('Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s')); return; } diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index eab22d84d8..832a020951 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -54,7 +54,7 @@ class FireflyConfig public function getEncrypted(string $name, mixed $default = null): ?Configuration { $result = $this->get($name, $default); - if (null === $result) { + if (!$result instanceof Configuration) { return null; } if ('' === $result->data) { diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index 7dfc257bfa..19a043c76d 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -59,7 +59,7 @@ class AccountForm private function getAccountsGrouped(array $types, ?AccountRepositoryInterface $repository = null): array { - if (null === $repository) { + if (!$repository instanceof AccountRepositoryInterface) { $repository = $this->getAccountRepository(); } $accountList = $repository->getActiveAccountsByType($types); diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index 13f5eede8e..8240bc45a1 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -85,14 +85,13 @@ trait FormSupport { // Get errors from session: /** @var null|MessageBag $errors */ - $errors = session('errors'); - $classes = 'form-group'; + $errors = session('errors'); if (null !== $errors && $errors->has($name)) { - $classes = 'form-group has-error has-feedback'; + return 'form-group has-error has-feedback'; } - return $classes; + return 'form-group'; } /** @@ -112,7 +111,7 @@ trait FormSupport } if ($value instanceof Carbon) { - $value = $value->format('Y-m-d'); + return $value->format('Y-m-d'); } return $value; diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.php index 6246157049..8cc5ee85f9 100644 --- a/app/Support/Http/Api/AccountBalanceGrouped.php +++ b/app/Support/Http/Api/AccountBalanceGrouped.php @@ -215,7 +215,6 @@ class AccountBalanceGrouped private function getDataKey(array $journal): string { - $key = 'spent'; // deposit = incoming // transfer or reconcile or opening balance, and these accounts are the destination. if ( @@ -230,10 +229,10 @@ class AccountBalanceGrouped && in_array($journal['destination_account_id'], $this->accountIds, true) ) ) { - $key = 'earned'; + return 'earned'; } - return $key; + return 'spent'; } private function getRate(TransactionCurrency $currency, Carbon $date): string diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index 6fb55a9d22..6ce33985d3 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -33,6 +33,8 @@ use Illuminate\Support\Facades\Log; use Laravel\Passport\Passport; use phpseclib3\Crypt\RSA; +use function Safe\file_put_contents; + /** * Trait CreateStuff */ @@ -106,8 +108,8 @@ trait CreateStuff Log::alert('NO OAuth keys were found. They have been created.'); - \Safe\file_put_contents($publicKey, (string) $key->getPublicKey()); - \Safe\file_put_contents($privateKey, $key->toString('PKCS1')); + file_put_contents($publicKey, (string) $key->getPublicKey()); + file_put_contents($privateKey, $key->toString('PKCS1')); } /** diff --git a/app/Support/Http/Controllers/DateCalculation.php b/app/Support/Http/Controllers/DateCalculation.php index 32a4c58841..5027a4c69f 100644 --- a/app/Support/Http/Controllers/DateCalculation.php +++ b/app/Support/Http/Controllers/DateCalculation.php @@ -77,7 +77,7 @@ trait DateCalculation $step = '1M'; } if ($months > 100) { - $step = '1Y'; + return '1Y'; } return $step; diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index ca96315934..672a84cfb6 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -207,7 +207,7 @@ trait GetConfigurationData { $config = app('fireflyconfig')->get('last_rt_job', 0); $lastTime = (int) $config?->data; - $now = time(); + $now = Carbon::now()->getTimestamp(); app('log')->debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now)); if (0 === $lastTime) { request()->session()->flash('info', trans('firefly.recurring_never_cron')); diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index 84f87d580b..dd6badda30 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -36,6 +36,8 @@ use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Route as RouteFacade; use Hash; +use function Safe\parse_url; + /** * Trait RequestInformation */ @@ -47,7 +49,7 @@ trait RequestInformation final protected function getDomain(): string // get request info { $url = url()->to('/'); - $parts = \Safe\parse_url($url); + $parts = parse_url($url); return $parts['host'] ?? ''; } @@ -95,7 +97,7 @@ trait RequestInformation $shownDemo = app('preferences')->get($key, false)->data; } if (!is_bool($shownDemo)) { - $shownDemo = true; + return true; } return $shownDemo; @@ -123,20 +125,19 @@ trait RequestInformation final protected function notInSessionRange(Carbon $date): bool // Validate a preference { /** @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()); - $result = false; + $end = session('end', today(config('app.timezone'))->endOfMonth()); if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) { - $result = true; + return true; } // start and end in the past? use $end if ($start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date)) { - $result = true; + return true; } - return $result; + return false; } /** @@ -147,14 +148,14 @@ trait RequestInformation $attributes['location'] ??= ''; $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); $date = Carbon::createFromFormat('Ymd', $attributes['startDate']); - if (null === $date) { + if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $date->startOfMonth(); $attributes['startDate'] = $date; $date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']); - if (null === $date2) { + if (!$date2 instanceof Carbon) { $date2 = today(config('app.timezone')); } $date2->endOfDay(); diff --git a/app/Support/Models/AccountBalanceCalculator.php b/app/Support/Models/AccountBalanceCalculator.php index 21e9e8dc7f..f4ae008911 100644 --- a/app/Support/Models/AccountBalanceCalculator.php +++ b/app/Support/Models/AccountBalanceCalculator.php @@ -83,7 +83,7 @@ class AccountBalanceCalculator if ($accounts->count() > 0) { $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()); } - if (null !== $notBefore) { + if ($notBefore instanceof Carbon) { $notBefore->startOfDay(); $query->where('transaction_journals.date', '>=', $notBefore); } @@ -124,7 +124,7 @@ class AccountBalanceCalculator private function getLatestBalance(int $accountId, int $currencyId, ?Carbon $notBefore): string { - if (null === $notBefore) { + if (!$notBefore instanceof Carbon) { return '0'; } Log::debug(sprintf('getLatestBalance: notBefore date is "%s", calculating', $notBefore->format('Y-m-d'))); diff --git a/app/Support/Models/BillDateCalculator.php b/app/Support/Models/BillDateCalculator.php index e20993de38..71ffa170aa 100644 --- a/app/Support/Models/BillDateCalculator.php +++ b/app/Support/Models/BillDateCalculator.php @@ -83,7 +83,7 @@ class BillDateCalculator // AND date is after last paid date if ( $nextExpectedMatch->gte($earliest) // date is after "earliest possible date" - && (null === $lastPaid || $nextExpectedMatch->gt($lastPaid)) // date is after last paid date, if that date is not NULL + && (!$lastPaid instanceof Carbon || $nextExpectedMatch->gt($lastPaid)) // date is after last paid date, if that date is not NULL ) { Log::debug('Add date to set, because it is after earliest possible date and after last paid date.'); $set->push(clone $nextExpectedMatch); diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index ae604a0e6e..0b336ed8bc 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -421,7 +421,7 @@ class Navigation $currentEnd->{$function}(); // @phpstan-ignore-line } - if (null !== $maxDate && $currentEnd > $maxDate) { + if ($maxDate instanceof Carbon && $currentEnd > $maxDate) { return clone $maxDate; } @@ -502,7 +502,7 @@ class Navigation if ($diff >= 12.001) { // Log::debug(sprintf('Return Y because %s', $diff)); - $format = 'Y'; + return 'Y'; } return $format; @@ -565,16 +565,15 @@ class Navigation public function preferredCarbonLocalizedFormat(Carbon $start, Carbon $end): string { $locale = app('steam')->getLocale(); - $format = (string) trans('config.month_and_day_js', [], $locale); if ($start->diffInMonths($end, true) > 1) { - $format = (string) trans('config.month_js', [], $locale); + return (string) trans('config.month_js', [], $locale); } if ($start->diffInMonths($end, true) > 12) { - $format = (string) trans('config.year_js', [], $locale); + return (string) trans('config.year_js', [], $locale); } - return $format; + return (string) trans('config.month_and_day_js', [], $locale); } /** @@ -583,16 +582,15 @@ class Navigation */ public function preferredEndOfPeriod(Carbon $start, Carbon $end): string { - $format = 'endOfDay'; if ((int) $start->diffInMonths($end, true) > 1) { - $format = 'endOfMonth'; + return 'endOfMonth'; } if ((int) $start->diffInMonths($end, true) > 12) { - $format = 'endOfYear'; + return 'endOfYear'; } - return $format; + return 'endOfDay'; } /** @@ -601,16 +599,15 @@ class Navigation */ public function preferredRangeFormat(Carbon $start, Carbon $end): string { - $format = '1D'; if ((int) $start->diffInMonths($end, true) > 1) { - $format = '1M'; + return '1M'; } if ((int) $start->diffInMonths($end, true) > 12) { - $format = '1Y'; + return '1Y'; } - return $format; + return '1D'; } /** @@ -619,16 +616,15 @@ class Navigation */ public function preferredSqlFormat(Carbon $start, Carbon $end): string { - $format = '%Y-%m-%d'; if ((int) $start->diffInMonths($end, true) > 1) { - $format = '%Y-%m'; + return '%Y-%m'; } if ((int) $start->diffInMonths($end, true) > 12) { - $format = '%Y'; + return '%Y'; } - return $format; + return '%Y-%m-%d'; } /** diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index 4d61dc35d5..90a2ac6d88 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -30,6 +30,8 @@ use Carbon\Exceptions\InvalidFormatException; use FireflyIII\Exceptions\FireflyException; use Illuminate\Support\Facades\Log; +use function Safe\preg_match; + /** * Class ParseDateString */ @@ -85,7 +87,7 @@ class ParseDateString // if regex for YYYY-MM-DD: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { return $this->parseDefaultDate($date); } @@ -148,7 +150,7 @@ class ParseDateString Log::error(sprintf('parseDefaultDate("%s") ran into an error, but dont mind: %s', $date, $e->getMessage())); } if (false === $result) { - $result = today(config('app.timezone'))->startOfDay(); + return today(config('app.timezone'))->startOfDay(); } return $result; @@ -182,7 +184,7 @@ class ParseDateString // verify if correct $pattern = '/[+-]\d+[wqmdy]/'; - $result = \Safe\preg_match($pattern, $part); + $result = preg_match($pattern, $part); if (0 === $result || false === $result) { app('log')->error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part)); @@ -256,7 +258,7 @@ class ParseDateString protected function isDayRange(string $date): bool { $pattern = '/^xxxx-xx-(0[1-9]|[12]\d|3[01])$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a day range.', $date)); @@ -283,7 +285,7 @@ class ParseDateString { // if regex for xxxx-MM-xx: $pattern = '/^xxxx-(0[1-9]|1[012])-xx$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a month range.', $date)); @@ -311,7 +313,7 @@ class ParseDateString { // if regex for YYYY-xx-xx: $pattern = '/^(19|20)\d\d-xx-xx$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a year range.', $date)); @@ -339,7 +341,7 @@ class ParseDateString { // if regex for xxxx-MM-DD: $pattern = '/^xxxx-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a month/day range.', $date)); @@ -368,7 +370,7 @@ class ParseDateString { // if regex for YYYY-xx-DD: $pattern = '/^(19|20)\d\d-xx-(0[1-9]|[12]\d|3[01])$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a day/year range.', $date)); @@ -397,7 +399,7 @@ class ParseDateString { // if regex for YYYY-MM-xx: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-xx$/'; - $result = \Safe\preg_match($pattern, $date); + $result = preg_match($pattern, $date); if (false !== $result && 0 !== $result) { app('log')->debug(sprintf('"%s" is a month/year range.', $date)); diff --git a/app/Support/Preferences.php b/app/Support/Preferences.php index e6b084e388..c042fb4e04 100644 --- a/app/Support/Preferences.php +++ b/app/Support/Preferences.php @@ -110,7 +110,7 @@ class Preferences $groupId = null; $items = config('firefly.admin_specific_prefs') ?? []; if (in_array($preferenceName, $items, true)) { - $groupId = (int) $user->user_group_id; + return (int) $user->user_group_id; } return $groupId; @@ -215,7 +215,7 @@ class Preferences public function getEncrypted(string $name, mixed $default = null): ?Preference { $result = $this->get($name, $default); - if (null === $result) { + if (!$result instanceof Preference) { return null; } if ('' === $result->data) { @@ -286,7 +286,7 @@ class Preferences $lastActivity = microtime(); $preference = $this->get('lastActivity', microtime()); - if (null !== $preference && null !== $preference->data) { + if ($preference instanceof Preference && null !== $preference->data) { $lastActivity = $preference->data; } if (is_array($lastActivity)) { diff --git a/app/Support/Report/Summarizer/TransactionSummarizer.php b/app/Support/Report/Summarizer/TransactionSummarizer.php index 606fefae11..54d13dd2cd 100644 --- a/app/Support/Report/Summarizer/TransactionSummarizer.php +++ b/app/Support/Report/Summarizer/TransactionSummarizer.php @@ -37,7 +37,7 @@ class TransactionSummarizer public function __construct(?User $user = null) { - if (null !== $user) { + if ($user instanceof User) { $this->setUser($user); } } diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index 0e65fe7343..e1bdab159e 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -32,6 +32,8 @@ use FireflyIII\Support\Facades\Steam; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use function Safe\preg_replace; + /** * Trait ConvertsDataTypes */ @@ -125,7 +127,7 @@ trait ConvertsDataTypes $string = str_replace($this->characters, "\x20", $string); // clear zalgo text (TODO also in API v2) - $string = \Safe\preg_replace('/(\pM{2})\pM+/u', '\1', $string); + $string = preg_replace('/(\pM{2})\pM+/u', '\1', $string); return trim((string) $string); } @@ -263,7 +265,7 @@ trait ConvertsDataTypes return null; } - if (null === $carbon) { + if (!$carbon instanceof Carbon) { app('log')->error(sprintf('[2] "%s" is of an invalid format.', $value)); return null; @@ -316,7 +318,7 @@ trait ConvertsDataTypes } catch (InvalidFormatException) { // @ignoreException } - if (null === $carbon) { + if (!$carbon instanceof Carbon) { app('log')->debug(sprintf('Invalid date: %s', $string)); return null; @@ -380,7 +382,7 @@ trait ConvertsDataTypes // @ignoreException Log::debug(sprintf('Exception when parsing date "%s".', $this->get($field))); } - if (null === $result) { + if (!$result instanceof Carbon) { app('log')->debug(sprintf('Exception when parsing date "%s".', $this->get($field))); } diff --git a/app/Support/Search/AccountSearch.php b/app/Support/Search/AccountSearch.php index a40c407e3f..f374895c65 100644 --- a/app/Support/Search/AccountSearch.php +++ b/app/Support/Search/AccountSearch.php @@ -29,6 +29,8 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; +use function Safe\json_encode; + /** * Class AccountSearch */ @@ -81,7 +83,7 @@ class AccountSearch implements GenericSearchInterface // meta data: $searchQuery->orWhere( static function (Builder $q) use ($originalQuery): void { - $json = \Safe\json_encode($originalQuery, JSON_THROW_ON_ERROR); + $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); $q->where('account_meta.name', '=', 'account_number'); $q->whereLike('account_meta.data', $json); } @@ -108,7 +110,7 @@ class AccountSearch implements GenericSearchInterface // meta data: $searchQuery->Where( static function (Builder $q) use ($originalQuery): void { - $json = \Safe\json_encode($originalQuery, JSON_THROW_ON_ERROR); + $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); $q->where('account_meta.name', 'account_number'); $q->where('account_meta.data', $json); } diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index db289a99fc..095162de47 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -719,10 +719,10 @@ class OperatorQuerySearch implements SearchInterface // case 'currency_is': $currency = $this->findCurrency($value); - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $this->collector->setCurrency($currency); } - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->collector->findNothing(); } @@ -730,10 +730,10 @@ class OperatorQuerySearch implements SearchInterface case '-currency_is': $currency = $this->findCurrency($value); - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $this->collector->excludeCurrency($currency); } - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->collector->findNothing(); } @@ -741,10 +741,10 @@ class OperatorQuerySearch implements SearchInterface case 'foreign_currency_is': $currency = $this->findCurrency($value); - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $this->collector->setForeignCurrency($currency); } - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->collector->findNothing(); } @@ -752,10 +752,10 @@ class OperatorQuerySearch implements SearchInterface case '-foreign_currency_is': $currency = $this->findCurrency($value); - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { $this->collector->excludeForeignCurrency($currency); } - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->collector->findNothing(); } @@ -2109,7 +2109,7 @@ class OperatorQuerySearch implements SearchInterface } $result = $this->currencyRepository->findByCode($value); if (null === $result) { - $result = $this->currencyRepository->findByName($value); + return $this->currencyRepository->findByName($value); } return $result; diff --git a/app/Support/Search/QueryParser/GdbotsQueryParser.php b/app/Support/Search/QueryParser/GdbotsQueryParser.php index 7c610cf4b5..a402013e48 100644 --- a/app/Support/Search/QueryParser/GdbotsQueryParser.php +++ b/app/Support/Search/QueryParser/GdbotsQueryParser.php @@ -33,6 +33,8 @@ use Illuminate\Support\Facades\Log; use LogicException; use TypeError; +use function Safe\fwrite; + class GdbotsQueryParser implements QueryParserInterface { private readonly BaseQueryParser $parser; @@ -56,7 +58,7 @@ class GdbotsQueryParser implements QueryParserInterface return new NodeGroup($nodes); } catch (LogicException|TypeError $e) { - \Safe\fwrite(STDERR, "Setting up GdbotsQueryParserTest\n"); + fwrite(STDERR, "Setting up GdbotsQueryParserTest\n"); app('log')->error($e->getMessage()); app('log')->error(sprintf('Could not parse search: "%s".', $query)); diff --git a/app/Support/Search/QueryParser/QueryParser.php b/app/Support/Search/QueryParser/QueryParser.php index 05225f0fb7..c9072f970b 100644 --- a/app/Support/Search/QueryParser/QueryParser.php +++ b/app/Support/Search/QueryParser/QueryParser.php @@ -51,7 +51,7 @@ class QueryParser implements QueryParserInterface $nodes = []; $nodeResult = $this->buildNextNode($isSubquery); - while (null !== $nodeResult->node) { + while ($nodeResult->node instanceof Node) { $nodes[] = $nodeResult->node; if ($nodeResult->isSubqueryEnd) { break; diff --git a/app/Support/Steam.php b/app/Support/Steam.php index ff01d83474..033081a6ed 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -37,6 +37,9 @@ use Illuminate\Support\Str; use Exception; use ValueError; +use function Safe\preg_replace; +use function Safe\parse_url; + /** * Class Steam. */ @@ -97,25 +100,25 @@ class Steam unset($set[$defaultCurrency->code]); } // todo rethink this logic. - if (null !== $currency && $defaultCurrency->id !== $currency->id) { + if ($currency instanceof TransactionCurrency && $defaultCurrency->id !== $currency->id) { Log::debug(sprintf('Unset balance for account #%d', $account->id)); unset($set['balance']); } - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { Log::debug(sprintf('Unset balance for account #%d', $account->id)); unset($set['balance']); } } if (!$convertToNative) { - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { Log::debug(sprintf('Unset native_balance and make defaultCurrency balance the balance for account #%d', $account->id)); $set['balance'] = $set[$defaultCurrency->code] ?? '0'; unset($set[$defaultCurrency->code]); } - if (null !== $currency) { + if ($currency instanceof TransactionCurrency) { Log::debug(sprintf('Unset [%s] + [%s] balance for account #%d', $defaultCurrency->code, $currency->code, $account->id)); unset($set[$defaultCurrency->code], $set[$currency->code]); } @@ -186,8 +189,8 @@ class Steam ]; // clear zalgo text - $string = \Safe\preg_replace('/(\pM{2})\pM+/u', '\1', $string); - $string = \Safe\preg_replace('/\s+/', '', $string); + $string = preg_replace('/(\pM{2})\pM+/u', '\1', $string); + $string = preg_replace('/\s+/', '', $string); return str_replace($search, '', $string); } @@ -223,7 +226,7 @@ class Steam $startBalance = $this->finalAccountBalance($account, $request); $nativeCurrency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); $accountCurrency = $this->getAccountCurrency($account); - $hasCurrency = null !== $accountCurrency; + $hasCurrency = $accountCurrency instanceof TransactionCurrency; $currency = $accountCurrency ?? $nativeCurrency; Log::debug(sprintf('Currency is %s', $currency->code)); @@ -341,7 +344,7 @@ class Steam if (null === $convertToNative) { $convertToNative = Amount::convertToNative($account->user); } - if (null === $native) { + if (!$native instanceof TransactionCurrency) { $native = Amount::getNativeCurrencyByUserGroup($account->user->userGroup); } // account balance thing. @@ -516,7 +519,7 @@ class Steam // Check for Windows to replace the locale correctly. if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) { - $locale = str_replace('_', '-', $locale); + return str_replace('_', '-', $locale); } return $locale; @@ -568,8 +571,8 @@ class Steam { // Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); $returnUrl = $safeUrl; - $unknownHost = \Safe\parse_url($unknownUrl, PHP_URL_HOST); - $safeHost = \Safe\parse_url($safeUrl, PHP_URL_HOST); + $unknownHost = parse_url($unknownUrl, PHP_URL_HOST); + $safeHost = parse_url($safeUrl, PHP_URL_HOST); if (null !== $unknownHost && $unknownHost === $safeHost) { $returnUrl = $unknownUrl; @@ -578,7 +581,7 @@ class Steam // URL must not lead to weird pages $forbiddenWords = ['jscript', 'json', 'debug', 'serviceworker', 'offline', 'delete', '/login', '/attachments/view']; if (Str::contains($returnUrl, $forbiddenWords)) { - $returnUrl = $safeUrl; + return $safeUrl; } return $returnUrl; @@ -592,7 +595,7 @@ class Steam $amount = $this->floatalize($amount); if (1 === bccomp($amount, '0')) { - $amount = bcmul($amount, '-1'); + return bcmul($amount, '-1'); } return $amount; diff --git a/app/Support/System/OAuthKeys.php b/app/Support/System/OAuthKeys.php index 0ba89c644d..53e353481f 100644 --- a/app/Support/System/OAuthKeys.php +++ b/app/Support/System/OAuthKeys.php @@ -32,6 +32,9 @@ use Laravel\Passport\Console\KeysCommand; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; +use function Safe\file_get_contents; +use function Safe\file_put_contents; + /** * Class OAuthKeys */ @@ -97,8 +100,8 @@ class OAuthKeys { $private = storage_path('oauth-private.key'); $public = storage_path('oauth-public.key'); - app('fireflyconfig')->set(self::PRIVATE_KEY, Crypt::encrypt(\Safe\file_get_contents($private))); - app('fireflyconfig')->set(self::PUBLIC_KEY, Crypt::encrypt(\Safe\file_get_contents($public))); + app('fireflyconfig')->set(self::PRIVATE_KEY, Crypt::encrypt(file_get_contents($private))); + app('fireflyconfig')->set(self::PUBLIC_KEY, Crypt::encrypt(file_get_contents($public))); } /** @@ -124,8 +127,8 @@ class OAuthKeys } $private = storage_path('oauth-private.key'); $public = storage_path('oauth-public.key'); - \Safe\file_put_contents($private, $privateContent); - \Safe\file_put_contents($public, $publicContent); + file_put_contents($private, $privateContent); + file_put_contents($public, $publicContent); return true; } diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 4841e03245..61cbd5eba4 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -39,6 +39,8 @@ use Twig\TwigFilter; use Twig\TwigFunction; use Override; +use function Safe\parse_url; + /** * Class TwigSupport. */ @@ -64,7 +66,7 @@ class General extends AbstractExtension return new TwigFilter( 'balance', static function (?Account $account): string { - if (null === $account) { + if (!$account instanceof Account) { return '0'; } @@ -180,8 +182,8 @@ class General extends AbstractExtension return new TwigFilter( 'phphost', static function (string $string): string { - $proto = (string) \Safe\parse_url($string, PHP_URL_SCHEME); - $host = (string) \Safe\parse_url($string, PHP_URL_HOST); + $proto = (string) parse_url($string, PHP_URL_SCHEME); + $host = (string) parse_url($string, PHP_URL_HOST); return e(sprintf('%s://%s', $proto, $host)); } diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index f495721334..81cf8db231 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -35,6 +35,8 @@ use Twig\Extension\AbstractExtension; use Twig\TwigFunction; use Override; +use function Safe\json_decode; + /** * Class TransactionGroupTwig */ @@ -91,7 +93,7 @@ class TransactionGroupTwig extends AbstractExtension $result = app('amount')->formatFlat($array['currency_symbol'], (int) $array['currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { - $result = sprintf('%s', $result); + return sprintf('%s', $result); } return $result; @@ -111,7 +113,7 @@ class TransactionGroupTwig extends AbstractExtension // reconciliation and it comes from reconciliation? if (TransactionTypeEnum::RECONCILIATION->value === $transactionType && AccountTypeEnum::RECONCILIATION->value !== $sourceType) { - $amount = bcmul($amount, '-1'); + return bcmul($amount, '-1'); } return $amount; @@ -134,7 +136,7 @@ class TransactionGroupTwig extends AbstractExtension } $result = app('amount')->formatFlat($array['foreign_currency_symbol'], (int) $array['foreign_currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { - $result = sprintf('%s', $result); + return sprintf('%s', $result); } return $result; @@ -182,7 +184,7 @@ class TransactionGroupTwig extends AbstractExtension } $result = app('amount')->formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { - $result = sprintf('%s', $result); + return sprintf('%s', $result); } return $result; @@ -217,7 +219,7 @@ class TransactionGroupTwig extends AbstractExtension } $result = app('amount')->formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { - $result = sprintf('%s', $result); + return sprintf('%s', $result); } return $result; @@ -256,7 +258,7 @@ class TransactionGroupTwig extends AbstractExtension return today(config('app.timezone')); } - return new Carbon(\Safe\json_decode($entry->data, false)); + return new Carbon(json_decode((string) $entry->data, false)); } ); } @@ -277,7 +279,7 @@ class TransactionGroupTwig extends AbstractExtension return ''; } - return \Safe\json_decode($entry->data, true); + return json_decode((string) $entry->data, true); } ); } diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index 8140d1f9a8..b749889eb1 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -68,7 +68,7 @@ class SetDestinationAccount implements ActionInterface // if this is a transfer or a deposit, the new destination account must be an asset account or a default account, and it MUST exist: $newAccount = $this->findAssetAccount($type, $accountName); - if ((TransactionTypeEnum::DEPOSIT->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && null === $newAccount) { + if ((TransactionTypeEnum::DEPOSIT->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { app('log')->error( sprintf( 'Cant change destination account of journal #%d because no asset account with name "%s" exists.', @@ -97,7 +97,7 @@ class SetDestinationAccount implements ActionInterface return false; } - if (null !== $newAccount && $newAccount->id === $source->account_id) { + if ($newAccount instanceof Account && $newAccount->id === $source->account_id) { app('log')->error( sprintf( 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', @@ -116,7 +116,7 @@ class SetDestinationAccount implements ActionInterface if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $newAccount = $this->findWithdrawalDestinationAccount($accountName); } - if (null === $newAccount) { + if (!$newAccount instanceof Account) { app('log')->error( sprintf( 'No destination account found for name "%s".', @@ -159,7 +159,7 @@ class SetDestinationAccount implements ActionInterface { $allowed = config('firefly.expected_source_types.destination.Withdrawal'); $account = $this->repository->findByName($accountName, $allowed); - if (null === $account) { + if (!$account instanceof Account) { $data = [ 'name' => $accountName, 'account_type_name' => 'expense', diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index 340741cc81..3eddb9e7c7 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -67,7 +67,7 @@ class SetSourceAccount implements ActionInterface // if this is a transfer or a withdrawal, the new source account must be an asset account or a default account, and it MUST exist: $newAccount = $this->findAssetAccount($type, $accountName); - if ((TransactionTypeEnum::WITHDRAWAL->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && null === $newAccount) { + if ((TransactionTypeEnum::WITHDRAWAL->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { app('log')->error( sprintf('Cant change source account of journal #%d because no asset account with name "%s" exists.', $object->id, $accountName) ); @@ -92,7 +92,7 @@ class SetSourceAccount implements ActionInterface return false; } - if (null !== $newAccount && $newAccount->id === $destination->account_id) { + if ($newAccount instanceof Account && $newAccount->id === $destination->account_id) { app('log')->error( sprintf( 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', @@ -141,7 +141,7 @@ class SetSourceAccount implements ActionInterface { $allowed = config('firefly.expected_source_types.source.Deposit'); $account = $this->repository->findByName($accountName, $allowed); - if (null === $account) { + if (!$account instanceof Account) { // create new revenue account with this name: $data = [ 'name' => $accountName, diff --git a/app/TransactionRules/Actions/UpdatePiggyBank.php b/app/TransactionRules/Actions/UpdatePiggyBank.php index 6b7113b6b2..29937334dc 100644 --- a/app/TransactionRules/Actions/UpdatePiggyBank.php +++ b/app/TransactionRules/Actions/UpdatePiggyBank.php @@ -56,7 +56,7 @@ class UpdatePiggyBank implements ActionInterface $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); $piggyBank = $this->findPiggyBank($user, $actionValue); - if (null === $piggyBank) { + 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) ); @@ -150,7 +150,7 @@ class UpdatePiggyBank implements ActionInterface private function isConnected(PiggyBank $piggyBank, ?Account $link): bool { - if (null === $link) { + if (!$link instanceof Account) { return false; } foreach ($piggyBank->accounts as $account) { diff --git a/app/TransactionRules/Expressions/ActionExpression.php b/app/TransactionRules/Expressions/ActionExpression.php index a012c3c3b3..6e578c8444 100644 --- a/app/TransactionRules/Expressions/ActionExpression.php +++ b/app/TransactionRules/Expressions/ActionExpression.php @@ -135,7 +135,7 @@ class ActionExpression public function isValid(): bool { - return null === $this->validationError; + return !$this->validationError instanceof SyntaxError; } private function evaluateExpression(string $expr, array $journal): string diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 7a784ae774..a86adf3d92 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -125,7 +125,7 @@ class AccountTransformer extends AbstractTransformer 'currency_code' => $account->meta['currency']?->code, 'currency_symbol' => $account->meta['currency']?->symbol, 'currency_decimal_places' => $account->meta['currency']?->decimal_places, - 'native_currency_id' => null === $native ? null : (string) $native->id, + 'native_currency_id' => $native instanceof TransactionCurrency ? (string) $native->id : null, 'native_currency_code' => $native?->code, 'native_currency_symbol' => $native?->symbol, 'native_currency_decimal_places' => $native?->decimal_places, @@ -166,7 +166,7 @@ class AccountTransformer extends AbstractTransformer { $accountRole = $account->meta['account_role'] ?? null; if ('asset' !== $accountType || '' === (string) $accountRole) { - $accountRole = null; + return null; } return $accountRole; @@ -177,12 +177,11 @@ class AccountTransformer extends AbstractTransformer */ private function getDate(): Carbon { - $date = today(config('app.timezone')); if (null !== $this->parameters->get('date')) { - $date = $this->parameters->get('date'); + return $this->parameters->get('date'); } - return $date; + return today(config('app.timezone')); } private function getCCInfo(Account $account, ?string $accountRole, string $accountType): array @@ -197,7 +196,7 @@ class AccountTransformer extends AbstractTransformer // try classic date: if (10 === strlen($monthlyPaymentDate)) { $object = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone')); - if (null === $object) { + if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } $monthlyPaymentDate = $object->toAtomString(); @@ -223,7 +222,7 @@ class AccountTransformer extends AbstractTransformer } if (null !== $openingBalanceDate) { $object = Carbon::createFromFormat('Y-m-d H:i:s', $openingBalanceDate, config('app.timezone')); - if (null === $object) { + if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } $openingBalanceDate = $object->toAtomString(); diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index dacc389d07..fb34c8c9b1 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -74,7 +74,7 @@ class AvailableBudgetTransformer extends AbstractTransformer 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => null === $default ? null : (string) $default->id, + 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, 'native_currency_code' => $default?->code, 'native_currency_symbol' => $default?->symbol, 'native_currency_decimal_places' => $default?->decimal_places, diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index ec152568f8..fa1fcc8923 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -91,7 +91,7 @@ class BillTransformer extends AbstractTransformer $payDatesFormatted = []; foreach ($paidData as $object) { $date = Carbon::createFromFormat('!Y-m-d', $object['date'], config('app.timezone')); - if (null === $date) { + if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $object['date'] = $date->toAtomString(); @@ -100,7 +100,7 @@ class BillTransformer extends AbstractTransformer foreach ($payDates as $string) { $date = Carbon::createFromFormat('!Y-m-d', $string, config('app.timezone')); - if (null === $date) { + if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $payDatesFormatted[] = $date->toAtomString(); @@ -113,7 +113,7 @@ class BillTransformer extends AbstractTransformer if (null !== $firstPayDate) { $nemDate = Carbon::createFromFormat('!Y-m-d', $firstPayDate, config('app.timezone')); - if (null === $nemDate) { + if (!$nemDate instanceof Carbon) { $nemDate = today(config('app.timezone')); } $nem = $nemDate->toAtomString(); @@ -138,7 +138,7 @@ class BillTransformer extends AbstractTransformer $current = $payDatesFormatted[0] ?? null; if (null !== $current && !$nemDate->isToday()) { $temp2 = Carbon::createFromFormat('Y-m-d\TH:i:sP', $current); - if (null === $temp2) { + if (!$temp2 instanceof Carbon) { $temp2 = today(config('app.timezone')); } $nemDiff = trans('firefly.bill_expected_date', ['date' => $temp2->diffForHumans(today(config('app.timezone')), CarbonInterface::DIFF_RELATIVE_TO_NOW)]); diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index a1990febec..bc43a51f9e 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -111,7 +111,7 @@ class BudgetLimitTransformer extends AbstractTransformer 'currency_name' => $currencyName, 'currency_decimal_places' => $currencyDecimalPlaces, 'currency_symbol' => $currencySymbol, - 'native_currency_id' => null === $default ? null : (string) $default->id, + 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, 'native_currency_code' => $default?->code, 'native_currency_symbol' => $default?->symbol, 'native_currency_decimal_places' => $default?->decimal_places, diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index 12e5feac28..d028143c41 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -113,7 +113,7 @@ class BudgetTransformer extends AbstractTransformer 'currency_decimal_places' => $autoBudget?->transactionCurrency->decimal_places, 'currency_symbol' => $autoBudget?->transactionCurrency->symbol, - 'native_currency_id' => null === $default ? null : (string) $default->id, + 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, 'native_currency_code' => $default?->code, 'native_currency_symbol' => $default?->symbol, 'native_currency_decimal_places' => $default?->decimal_places, diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php index a5516e03c3..f7090cec3b 100644 --- a/app/Transformers/CategoryTransformer.php +++ b/app/Transformers/CategoryTransformer.php @@ -80,7 +80,7 @@ class CategoryTransformer extends AbstractTransformer 'updated_at' => $category->updated_at->toAtomString(), 'name' => $category->name, 'notes' => $notes, - 'native_currency_id' => null === $default ? null : (string) $default->id, + 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, 'native_currency_code' => $default?->code, 'native_currency_symbol' => $default?->symbol, 'native_currency_decimal_places' => $default?->decimal_places, diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index 5abe8b2615..dc07e04224 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -37,6 +37,8 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use function Safe\json_decode; + /** * Class RecurringTransactionTransformer */ @@ -264,7 +266,7 @@ class RecurrenceTransformer extends AbstractTransformer break; case 'tags': - $array['tags'] = \Safe\json_decode($transactionMeta->value); + $array['tags'] = json_decode((string) $transactionMeta->value); break; diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index 787c5e74a3..ef5f8213c8 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -306,7 +306,7 @@ class TransactionGroupTransformer extends AbstractTransformer $latitude = null; $zoomLevel = null; $location = $this->getLocation($journal); - if (null !== $location) { + if ($location instanceof Location) { $longitude = $location->longitude; $latitude = $location->latitude; $zoomLevel = $location->zoom_level; @@ -428,12 +428,11 @@ class TransactionGroupTransformer extends AbstractTransformer private function getForeignAmount(?string $foreignAmount): ?string { - $result = null; if (null !== $foreignAmount && '' !== $foreignAmount && 0 !== bccomp('0', $foreignAmount)) { - $result = app('steam')->positive($foreignAmount); + return app('steam')->positive($foreignAmount); } - return $result; + return null; } private function getDates(NullArrayObject $dates): array @@ -465,7 +464,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'symbol' => null, 'decimal_places' => null, ]; - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { return $array; } $array['id'] = $currency->id; @@ -482,7 +481,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'id' => null, 'name' => null, ]; - if (null === $budget) { + if (!$budget instanceof Budget) { return $array; } $array['id'] = $budget->id; @@ -497,7 +496,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'id' => null, 'name' => null, ]; - if (null === $category) { + if (!$category instanceof Category) { return $array; } $array['id'] = $category->id; @@ -512,7 +511,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'id' => null, 'name' => null, ]; - if (null === $bill) { + if (!$bill instanceof Bill) { return $array; } $array['id'] = (string) $bill->id; diff --git a/app/Transformers/V2/AccountTransformer.php b/app/Transformers/V2/AccountTransformer.php index 2f71df27d4..4b7e9f58bc 100644 --- a/app/Transformers/V2/AccountTransformer.php +++ b/app/Transformers/V2/AccountTransformer.php @@ -127,12 +127,11 @@ class AccountTransformer extends AbstractTransformer private function getDate(): Carbon { - $date = today(config('app.timezone')); if (null !== $this->parameters->get('date')) { - $date = $this->parameters->get('date'); + return $this->parameters->get('date'); } - return $date; + return today(config('app.timezone')); } private function getDefaultCurrency(): void diff --git a/app/Transformers/V2/BillTransformer.php b/app/Transformers/V2/BillTransformer.php index d5209d2243..79d18c671a 100644 --- a/app/Transformers/V2/BillTransformer.php +++ b/app/Transformers/V2/BillTransformer.php @@ -269,7 +269,7 @@ class BillTransformer extends AbstractTransformer } if ($nextMatch->isSameDay($lastPaidDate)) { // Add another period because it's the same day as the last paid date. - $nextMatch = app('navigation')->addPeriod($nextMatch, $bill->repeat_freq, $bill->skip); + return app('navigation')->addPeriod($nextMatch, $bill->repeat_freq, $bill->skip); } return $nextMatch; diff --git a/app/Transformers/V2/PiggyBankTransformer.php b/app/Transformers/V2/PiggyBankTransformer.php index 7f9befb640..26e927b0d4 100644 --- a/app/Transformers/V2/PiggyBankTransformer.php +++ b/app/Transformers/V2/PiggyBankTransformer.php @@ -248,12 +248,12 @@ class PiggyBankTransformer extends AbstractTransformer private function getSuggestedMonthlyAmount(string $currentAmount, string $targetAmount, ?Carbon $startDate, ?Carbon $targetDate): string { $savePerMonth = '0'; - if (null === $targetDate) { + if (!$targetDate instanceof Carbon) { return '0'; } if (bccomp($currentAmount, $targetAmount) < 1) { $now = today(config('app.timezone')); - $startDate = null !== $startDate && $startDate->gte($now) ? $startDate : $now; + $startDate = $startDate instanceof Carbon && $startDate->gte($now) ? $startDate : $now; $diffInMonths = (int) $startDate->diffInMonths($targetDate); $remainingAmount = bcsub($targetAmount, $currentAmount); diff --git a/app/Transformers/V2/TransactionGroupTransformer.php b/app/Transformers/V2/TransactionGroupTransformer.php index f6ec77c816..e9f3b12128 100644 --- a/app/Transformers/V2/TransactionGroupTransformer.php +++ b/app/Transformers/V2/TransactionGroupTransformer.php @@ -465,7 +465,7 @@ class TransactionGroupTransformer extends AbstractTransformer // app('log')->debug(sprintf('Now in date("%s")', $string)); if (10 === strlen($string)) { $res = Carbon::createFromFormat('Y-m-d', $string, config('app.timezone')); - if (null === $res) { + if (!$res instanceof Carbon) { return null; } @@ -476,7 +476,7 @@ class TransactionGroupTransformer extends AbstractTransformer } if (19 === strlen($string) && str_contains($string, 'T')) { $res = Carbon::createFromFormat('Y-m-d\TH:i:s', substr($string, 0, 19), config('app.timezone')); - if (null === $res) { + if (!$res instanceof Carbon) { return null; } @@ -485,7 +485,7 @@ class TransactionGroupTransformer extends AbstractTransformer // 2022-01-01 01:01:01 $res = Carbon::createFromFormat('Y-m-d H:i:s', substr($string, 0, 19), config('app.timezone')); - if (null === $res) { + if (!$res instanceof Carbon) { return null; } diff --git a/app/Transformers/WebhookMessageTransformer.php b/app/Transformers/WebhookMessageTransformer.php index 8d758ca9a9..0839a7c437 100644 --- a/app/Transformers/WebhookMessageTransformer.php +++ b/app/Transformers/WebhookMessageTransformer.php @@ -27,6 +27,8 @@ namespace FireflyIII\Transformers; use FireflyIII\Models\WebhookMessage; use JsonException; +use function Safe\json_encode; + /** * Class WebhookMessageTransformer */ @@ -40,7 +42,7 @@ class WebhookMessageTransformer extends AbstractTransformer $json = '{}'; try { - $json = \Safe\json_encode($message->message, JSON_THROW_ON_ERROR); + $json = json_encode($message->message, JSON_THROW_ON_ERROR); } catch (JsonException $e) { app('log')->error(sprintf('Could not encode webhook message #%d: %s', $message->id, $e->getMessage())); } diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index d6de97ed25..44c9ad9d7b 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -79,10 +79,10 @@ class AccountValidator public function setSource(?Account $account): void { - if (null === $account) { + if (!$account instanceof Account) { app('log')->debug('AccountValidator source is set to NULL'); } - if (null !== $account) { + if ($account instanceof Account) { app('log')->debug(sprintf('AccountValidator source is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType?->type)); } $this->source = $account; @@ -90,10 +90,10 @@ class AccountValidator public function setDestination(?Account $account): void { - if (null === $account) { + if (!$account instanceof Account) { app('log')->debug('AccountValidator destination is set to NULL'); } - if (null !== $account) { + if ($account instanceof Account) { app('log')->debug(sprintf('AccountValidator destination is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType->type)); } $this->destination = $account; @@ -118,7 +118,7 @@ class AccountValidator public function validateDestination(array $array): bool { app('log')->debug('Now in AccountValidator::validateDestination()', $array); - if (null === $this->source) { + if (!$this->source instanceof Account) { app('log')->error('Source is NULL, always FALSE.'); $this->destError = 'No source account validation has taken place yet. Please do this first or overrule the object.'; @@ -260,10 +260,10 @@ class AccountValidator // find by ID if (null !== $accountId && $accountId > 0) { $first = $this->accountRepository->find($accountId); - $accountType = null === $first ? 'invalid' : $first->accountType->type; + $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if ((null !== $first) && $check) { + if (($first instanceof Account) && $check) { app('log')->debug(sprintf('ID: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); return $first; @@ -273,10 +273,10 @@ class AccountValidator // find by iban if (null !== $accountIban && '' !== (string) $accountIban) { $first = $this->accountRepository->findByIbanNull($accountIban, $validTypes); - $accountType = null === $first ? 'invalid' : $first->accountType->type; + $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if ((null !== $first) && $check) { + if (($first instanceof Account) && $check) { app('log')->debug(sprintf('Iban: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); return $first; @@ -286,10 +286,10 @@ class AccountValidator // find by number if (null !== $accountNumber && '' !== (string) $accountNumber) { $first = $this->accountRepository->findByAccountNumber($accountNumber, $validTypes); - $accountType = null === $first ? 'invalid' : $first->accountType->type; + $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if ((null !== $first) && $check) { + if (($first instanceof Account) && $check) { app('log')->debug(sprintf('Number: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); return $first; @@ -299,7 +299,7 @@ class AccountValidator // find by name: if ('' !== (string) $accountName) { $first = $this->accountRepository->findByName($accountName, $validTypes); - if (null !== $first) { + if ($first instanceof Account) { app('log')->debug(sprintf('Name: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); return $first; diff --git a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php index c5651941d4..8f8cffba91 100644 --- a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php +++ b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php @@ -27,6 +27,8 @@ namespace FireflyIII\Validation\Api\Data\Bulk; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use Illuminate\Validation\Validator; +use function Safe\json_decode; + trait ValidatesBulkTransactionQuery { protected function validateTransactionQuery(Validator $validator): void @@ -34,7 +36,7 @@ trait ValidatesBulkTransactionQuery $data = $validator->getData(); // assumption is all validation has already taken place and the query key exists. $query = $data['query'] ?? '[]'; - $json = \Safe\json_decode($query, true, 8, JSON_THROW_ON_ERROR); + $json = json_decode($query, true, 8, JSON_THROW_ON_ERROR); if ( array_key_exists('where', $json) diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index f3ca6a4dbc..c24fcd54ea 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -48,6 +48,10 @@ use PragmaRX\Google2FALaravel\Facade; use Config; use ValueError; +use function Safe\preg_match; +use function Safe\iconv; +use function Safe\json_encode; + /** * Class FireflyValidator. * TODO all of these validations must become separate classes. @@ -113,7 +117,7 @@ class FireflyValidator extends Validator return false; } $regex = '/^[a-z]{6}[0-9a-z]{2}([0-9a-z]{3})?\z/i'; - $result = \Safe\preg_match($regex, $value); + $result = preg_match($regex, $value); if (false === $result || 0 === $result) { return false; } @@ -203,7 +207,7 @@ class FireflyValidator extends Validator $value = strtoupper($value); // replace characters outside of ASCI range. - $value = (string) \Safe\iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value); + $value = (string) iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value); $search = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; $replace = ['', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35']; @@ -637,7 +641,7 @@ class FireflyValidator extends Validator ->whereNull('accounts.deleted_at') ->where('accounts.user_id', auth()->user()->id) ->where('account_meta.name', 'account_number') - ->where('account_meta.data', \Safe\json_encode($value)) + ->where('account_meta.data', json_encode($value)) ; if ($accountId > 0) { diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index 547049b37d..52b829203e 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -166,13 +166,13 @@ trait RecurrenceValidation $reps = array_key_exists('nr_of_repetitions', $data) ? (int) $data['nr_of_repetitions'] : null; $repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null; - if (null === $reps && null === $repeatUntil) { + if (null === $reps && !$repeatUntil instanceof Carbon) { $validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until')); $validator->errors()->add('repeat_until', trans('validation.require_repeat_until')); return; } - if ($reps > 0 && null !== $repeatUntil) { + if ($reps > 0 && $repeatUntil instanceof Carbon) { $validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until')); $validator->errors()->add('repeat_until', trans('validation.require_repeat_until')); } diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index afae5b0e49..b03511f193 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -200,12 +200,12 @@ trait TransactionValidation return; } - if (null === $accountValidator->source) { + if (!$accountValidator->source instanceof Account) { Log::debug('No source, return'); return; } - if (null === $accountValidator->destination) { + if (!$accountValidator->destination instanceof Account) { Log::debug('No destination, return'); return; @@ -292,7 +292,11 @@ trait TransactionValidation private function isLiabilityOrAsset(Account $account): bool { - return $this->isLiability($account) || $this->isAsset($account); + if ($this->isLiability($account)) { + return true; + } + + return (bool) $this->isAsset($account); } private function isLiability(Account $account): bool