diff --git a/.ci/php-cs-fixer/.php-cs-fixer.php b/.ci/php-cs-fixer/.php-cs-fixer.php index 9ecec0fc77..51e31775a7 100644 --- a/.ci/php-cs-fixer/.php-cs-fixer.php +++ b/.ci/php-cs-fixer/.php-cs-fixer.php @@ -53,6 +53,9 @@ return $config->setRules( 'statement_indentation' => true, 'void_return' => true, + // about importing statements + 'global_namespace_import' => ['import_classes' => true, 'import_constants' => true, 'import_functions' => true], + // disabled rules 'native_function_invocation' => false, // annoying 'php_unit_data_provider_name' => false, // bloody annoying long test names diff --git a/.ci/rector.php b/.ci/rector.php index ca37bf1431..6e98485438 100644 --- a/.ci/rector.php +++ b/.ci/rector.php @@ -28,43 +28,40 @@ use Rector\EarlyReturn\Rector\If_\ChangeOrIfContinueToMultiContinueRector; return RectorConfig::configure() ->withSkip([ - ChangeOrIfContinueToMultiContinueRector::class, - ]) - ->withPaths([ -// __DIR__ . '/../app', -__DIR__ . '/../app/Api', -__DIR__ . '/../app/Http', -// __DIR__ . '/../bootstrap', -// __DIR__ . '/../config', -// __DIR__ . '/../public', -// __DIR__ . '/../resources', -// __DIR__ . '/../routes', -// __DIR__ . '/../tests', - ]) - // uncomment to reach your current PHP version - ->withPhpSets() - ->withPreparedSets( - codingStyle : false, // leave false - privatization: false, // leave false. - naming : false, // leave false - instanceOf : true, - earlyReturn : true, - strictBooleans : true, - carbon : true, - rectorPreset : true, - phpunitCodeQuality : true, - doctrineCodeQuality: true, - symfonyCodeQuality : true, - symfonyConfigs : true + ChangeOrIfContinueToMultiContinueRector::class, + ]) + ->withPaths([ + __DIR__ . '/../app', + __DIR__ . '/../bootstrap', + __DIR__ . '/../config', + __DIR__ . '/../public', + __DIR__ . '/../resources/lang/en_US', + __DIR__ . '/../routes', + __DIR__ . '/../tests', + ]) + // uncomment to reach your current PHP version + ->withPhpSets() + ->withPreparedSets( + codingStyle: false, // leave false + privatization: false, // leave false. + naming: false, // leave false + instanceOf: true, + earlyReturn: true, + strictBooleans: true, + carbon: true, + rectorPreset: true, + phpunitCodeQuality: true, + doctrineCodeQuality: true, + symfonyCodeQuality: true, + symfonyConfigs: true - ) - ->withComposerBased( - twig: true, - doctrine: true, - phpunit: true, - symfony: true) - ->withTypeCoverageLevel(0) - ->withDeadCodeLevel(0) - ->withCodeQualityLevel(0) - - ->withImportNames(removeUnusedImports: true);// import statements instead of full classes. + ) + ->withComposerBased( + twig: true, + doctrine: true, + phpunit: true, + symfony: true) + ->withTypeCoverageLevel(0) + ->withDeadCodeLevel(0) + ->withCodeQualityLevel(0) + ->withImportNames(removeUnusedImports: true);// import statements instead of full classes. diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e3260c0370..1c842783e7 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -5,7 +5,6 @@ on: push: branches: - main - - develop env: DB_CONNECTION: sqlite APP_KEY: TestTestTestTestTestTestTestTest diff --git a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php index 14c480577a..4a4ef9eb69 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\RuleGroup; +use Exception; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\RuleGroup\TestRequest; use FireflyIII\Api\V1\Requests\Models\RuleGroup\TriggerRequest; @@ -128,7 +129,7 @@ class TriggerController extends Controller * * Execute the given rule group on a set of existing transactions. * - * @throws \Exception + * @throws Exception */ public function triggerGroup(TriggerRequest $request, RuleGroup $group): JsonResponse { diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php index 2b36ee7775..1878812a27 100644 --- a/app/Api/V1/Controllers/Summary/BasicController.php +++ b/app/Api/V1/Controllers/Summary/BasicController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Summary; +use Exception; use Carbon\Carbon; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Data\DateRequest; @@ -91,7 +92,7 @@ class BasicController extends Controller * This endpoint is documented at: * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/summary/getBasicSummary * - * @throws \Exception + * @throws Exception */ public function basic(DateRequest $request): JsonResponse { @@ -467,7 +468,7 @@ class BasicController extends Controller } /** - * @throws \Exception + * @throws Exception */ private function getLeftToSpendInfo(Carbon $start, Carbon $end): array { diff --git a/app/Api/V1/Middleware/ApiDemoUser.php b/app/Api/V1/Middleware/ApiDemoUser.php index e031bfa039..cd85e94879 100644 --- a/app/Api/V1/Middleware/ApiDemoUser.php +++ b/app/Api/V1/Middleware/ApiDemoUser.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Middleware; +use Closure; use FireflyIII\User; use Illuminate\Http\Request; @@ -36,7 +37,7 @@ class ApiDemoUser * * @return mixed */ - public function handle(Request $request, \Closure $next) + public function handle(Request $request, Closure $next) { /** @var null|User $user */ $user = $request->user(); diff --git a/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php b/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php index b9319e0240..da2bfb3d7c 100644 --- a/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php +++ b/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Data\Bulk; +use JsonException; use FireflyIII\Enums\ClauseType; use FireflyIII\Rules\IsValidBulkClause; use FireflyIII\Support\Request\ChecksLogin; @@ -52,7 +53,7 @@ class TransactionRequest extends FormRequest $data = [ 'query' => json_decode($this->get('query'), true, 8, JSON_THROW_ON_ERROR), ]; - } catch (\JsonException $e) { + } catch (JsonException $e) { // dont really care. the validation should catch invalid json. app('log')->error($e->getMessage()); } diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.php index 40194a33f4..e773942ca3 100644 --- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Bill; +use ValueError; +use TypeError; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; @@ -109,7 +111,7 @@ class StoreRequest extends FormRequest try { $result = bccomp($min, $max); - } catch (\ValueError $e) { + } catch (ValueError $e) { Log::error($e->getMessage()); $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); $validator->errors()->add('amount_max', (string) trans('validation.generic_invalid')); @@ -124,7 +126,7 @@ class StoreRequest extends FormRequest try { $failed = $validator->fails(); - } catch (\TypeError $e) { + } catch (TypeError $e) { Log::error($e->getMessage()); $failed = false; } diff --git a/app/Api/V2/Controllers/Summary/BasicController.php b/app/Api/V2/Controllers/Summary/BasicController.php index e9402880d2..feb3798cef 100644 --- a/app/Api/V2/Controllers/Summary/BasicController.php +++ b/app/Api/V2/Controllers/Summary/BasicController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V2\Controllers\Summary; +use Exception; use Carbon\Carbon; use FireflyIII\Api\V2\Controllers\Controller; use FireflyIII\Api\V2\Request\Generic\DateRequest; @@ -92,7 +93,7 @@ class BasicController extends Controller * This endpoint is documented at: * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/summary/getBasicSummary * - * @throws \Exception + * @throws Exception * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ diff --git a/app/Api/V2/Request/Model/Transaction/UpdateRequest.php b/app/Api/V2/Request/Model/Transaction/UpdateRequest.php index c4d8140c79..3aeda0e3c3 100644 --- a/app/Api/V2/Request/Model/Transaction/UpdateRequest.php +++ b/app/Api/V2/Request/Model/Transaction/UpdateRequest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V2\Request\Model\Transaction; +use Override; use FireflyIII\Api\V1\Requests\Models\AvailableBudget\Request; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionGroup; @@ -64,7 +65,7 @@ class UpdateRequest extends Request * * @throws FireflyException */ - #[\Override] + #[Override] public function getAll(): array { app('log')->debug(sprintf('Now in %s', __METHOD__)); @@ -248,7 +249,7 @@ class UpdateRequest extends Request /** * The rules that the incoming request must be matched against. */ - #[\Override] + #[Override] public function rules(): array { app('log')->debug(sprintf('Now in %s', __METHOD__)); @@ -332,7 +333,7 @@ class UpdateRequest extends Request /** * Configure the validator instance. */ - #[\Override] + #[Override] public function withValidator(Validator $validator): void { app('log')->debug('Now in withValidator'); diff --git a/app/Api/V2/Response/Sum/AutoSum.php b/app/Api/V2/Response/Sum/AutoSum.php index c4ca249fbb..0f1d601f7c 100644 --- a/app/Api/V2/Response/Sum/AutoSum.php +++ b/app/Api/V2/Response/Sum/AutoSum.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V2\Response\Sum; +use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use Illuminate\Database\Eloquent\Model; @@ -39,7 +40,7 @@ class AutoSum /** * @throws FireflyException */ - public function autoSum(Collection $objects, \Closure $getCurrency, \Closure $getSum): array + public function autoSum(Collection $objects, Closure $getCurrency, Closure $getSum): array { $return = []; diff --git a/app/Console/Commands/Correction/CorrectsAmounts.php b/app/Console/Commands/Correction/CorrectsAmounts.php index fdc206cf80..5616908377 100644 --- a/app/Console/Commands/Correction/CorrectsAmounts.php +++ b/app/Console/Commands/Correction/CorrectsAmounts.php @@ -42,6 +42,7 @@ use FireflyIII\Support\Facades\Amount; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; +use ValueError; class CorrectsAmounts extends Command { @@ -234,7 +235,7 @@ class CorrectsAmounts extends Command { try { $check = bccomp((string) $item->trigger_value, '0'); - } catch (\ValueError) { + } catch (ValueError) { $this->friendlyError(sprintf('Rule #%d contained invalid %s-trigger "%s". The trigger has been removed, and the rule is disabled.', $item->rule_id, $item->trigger_type, $item->trigger_value)); $item->rule->active = false; $item->rule->save(); diff --git a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php index 11578b00c0..713f54d8c6 100644 --- a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php @@ -76,7 +76,7 @@ class CorrectsOpeningBalanceCurrencies extends Command { // get the asset account for this opening balance: $account = $this->getAccount($journal); - if (null === $account) { + if (!$account instanceof Account) { $message = sprintf('Transaction journal #%d has no valid account. Can\'t fix this line.', $journal->id); app('log')->warning($message); $this->friendlyError($message); diff --git a/app/Console/Commands/Correction/CorrectsUnevenAmount.php b/app/Console/Commands/Correction/CorrectsUnevenAmount.php index a864fcb115..70b36705f0 100644 --- a/app/Console/Commands/Correction/CorrectsUnevenAmount.php +++ b/app/Console/Commands/Correction/CorrectsUnevenAmount.php @@ -34,6 +34,8 @@ use FireflyIII\Support\Models\AccountBalanceCalculator; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; +use ValueError; +use stdClass; class CorrectsUnevenAmount extends Command { @@ -135,7 +137,7 @@ class CorrectsUnevenAmount extends Command ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($journals as $entry) { $sum = (string) $entry->the_sum; if (!is_numeric($sum) @@ -157,7 +159,7 @@ class CorrectsUnevenAmount extends Command try { $res = bccomp($sum, '0'); - } catch (\ValueError $e) { + } catch (ValueError $e) { $this->friendlyError(sprintf('Could not bccomp("%s", "0").', $sum)); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -385,7 +387,7 @@ class CorrectsUnevenAmount extends Command continue; } - if (0 === bccomp($source->amount, $source->foreign_amount) && 0 === bccomp($source->foreign_amount, $source->amount)) { + if (0 === bccomp((string) $source->amount, (string) $source->foreign_amount) && 0 === bccomp((string) $source->foreign_amount, (string) $source->amount)) { Log::debug('Already fixed, continue.'); continue; diff --git a/app/Console/Commands/Correction/CreatesAccessTokens.php b/app/Console/Commands/Correction/CreatesAccessTokens.php index 2dcfcb7ffd..f73e8d2258 100644 --- a/app/Console/Commands/Correction/CreatesAccessTokens.php +++ b/app/Console/Commands/Correction/CreatesAccessTokens.php @@ -28,6 +28,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Console\Command; +use Exception; class CreatesAccessTokens extends Command { @@ -40,7 +41,7 @@ class CreatesAccessTokens extends Command /** * Execute the console command. * - * @throws \Exception + * @throws Exception */ public function handle(): int { diff --git a/app/Console/Commands/Correction/RemovesEmptyGroups.php b/app/Console/Commands/Correction/RemovesEmptyGroups.php index 7f64fc048a..2fac48e95b 100644 --- a/app/Console/Commands/Correction/RemovesEmptyGroups.php +++ b/app/Console/Commands/Correction/RemovesEmptyGroups.php @@ -27,6 +27,7 @@ namespace FireflyIII\Console\Commands\Correction; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\TransactionGroup; use Illuminate\Console\Command; +use Exception; class RemovesEmptyGroups extends Command { @@ -38,7 +39,7 @@ class RemovesEmptyGroups extends Command /** * Execute the console command. * - * @throws \Exception + * @throws Exception */ public function handle(): int { diff --git a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php index 2952fd133a..f44ee5fb0d 100644 --- a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php +++ b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php @@ -28,6 +28,8 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use Illuminate\Console\Command; +use Exception; +use stdClass; /** * Deletes transactions where the journal has been deleted. @@ -43,7 +45,7 @@ class RemovesOrphanedTransactions extends Command /** * Execute the console command. * - * @throws \Exception + * @throws Exception */ public function handle(): int { @@ -85,7 +87,7 @@ class RemovesOrphanedTransactions extends Command } /** - * @throws \Exception + * @throws Exception */ private function deleteOrphanedTransactions(): void { @@ -102,7 +104,7 @@ class RemovesOrphanedTransactions extends Command ) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($set as $entry) { $transaction = Transaction::find((int) $entry->transaction_id); if (null !== $transaction) { diff --git a/app/Console/Commands/Export/ExportsData.php b/app/Console/Commands/Export/ExportsData.php index 9205749126..d1189a2b40 100644 --- a/app/Console/Commands/Export/ExportsData.php +++ b/app/Console/Commands/Export/ExportsData.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\Export; +use FireflyIII\Models\TransactionJournal; use Carbon\Carbon; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Console\Commands\VerifiesAccessToken; @@ -35,6 +36,10 @@ use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\Export\ExportDataGenerator; use Illuminate\Console\Command; use Illuminate\Support\Collection; +use Exception; +use InvalidArgumentException; + +use function Safe\file_put_contents; class ExportsData extends Command { @@ -139,7 +144,7 @@ class ExportsData extends Command /** * @throws FireflyException - * @throws \Exception + * @throws Exception */ private function parseOptions(): array { @@ -169,7 +174,7 @@ class ExportsData extends Command } /** - * @throws \Exception + * @throws Exception */ private function getDateParameter(string $field): Carbon { @@ -183,7 +188,7 @@ class ExportsData extends Command if (is_string($this->option($field))) { try { $date = Carbon::createFromFormat('!Y-m-d', $this->option($field)); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { app('log')->error($e->getMessage()); $this->friendlyError(sprintf('%s date "%s" must be formatted YYYY-MM-DD. Field will be ignored.', $field, $this->option('start'))); $error = true; @@ -201,7 +206,7 @@ class ExportsData extends Command if (true === $error && 'start' === $field) { $journal = $this->journalRepository->firstNull(); - $date = null === $journal ? today(config('app.timezone'))->subYear() : $journal->date; + $date = $journal instanceof TransactionJournal ? $journal->date : today(config('app.timezone'))->subYear(); $date->startOfDay(); return $date; @@ -273,7 +278,7 @@ class ExportsData extends Command */ private function exportData(array $options, array $data): void { - $date = date('Y_m_d'); + $date = Carbon::now()->format('Y_m_d'); foreach ($data as $key => $content) { $file = sprintf('%s%s_%s.csv', $options['directory'], $date, $key); if (false === $options['force'] && file_exists($file)) { @@ -283,7 +288,7 @@ class ExportsData extends Command $this->friendlyWarning(sprintf('File "%s" exists already but will be replaced.', $file)); } // continue to write to file. - \Safe\file_put_contents($file, $content); + file_put_contents($file, $content); $this->friendlyPositive(sprintf('Wrote %s-export to file "%s".', $key, $file)); } } diff --git a/app/Console/Commands/Integrity/ReportsEmptyObjects.php b/app/Console/Commands/Integrity/ReportsEmptyObjects.php index 06c9d99d0c..b2d26ba555 100644 --- a/app/Console/Commands/Integrity/ReportsEmptyObjects.php +++ b/app/Console/Commands/Integrity/ReportsEmptyObjects.php @@ -30,6 +30,7 @@ use FireflyIII\Models\Budget; use FireflyIII\Models\Category; use FireflyIII\Models\Tag; use Illuminate\Console\Command; +use stdClass; class ReportsEmptyObjects extends Command { @@ -66,7 +67,7 @@ class ReportsEmptyObjects extends Command ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($set as $entry) { $line = sprintf( 'User #%d (%s) has budget #%d ("%s") which has no transaction journals.', @@ -92,7 +93,7 @@ class ReportsEmptyObjects extends Command ->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($set as $entry) { $line = sprintf( 'User #%d (%s) has category #%d ("%s") which has no transaction journals.', @@ -115,7 +116,7 @@ class ReportsEmptyObjects extends Command ->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($set as $entry) { $line = sprintf( 'User #%d (%s) has tag #%d ("%s") which has no transaction journals.', @@ -142,7 +143,7 @@ class ReportsEmptyObjects extends Command ) ; - /** @var \stdClass $entry */ + /** @var stdClass $entry */ foreach ($set as $entry) { $line = 'User #%d (%s) has account #%d ("%s") which has no transactions.'; $line = sprintf($line, $entry->user_id, $entry->email, $entry->id, $entry->name); diff --git a/app/Console/Commands/System/CreatesDatabase.php b/app/Console/Commands/System/CreatesDatabase.php index 97d644445f..1e88f7209f 100644 --- a/app/Console/Commands/System/CreatesDatabase.php +++ b/app/Console/Commands/System/CreatesDatabase.php @@ -27,6 +27,7 @@ namespace FireflyIII\Console\Commands\System; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use Illuminate\Console\Command; use PDO; +use PDOException; class CreatesDatabase extends Command { @@ -53,15 +54,15 @@ class CreatesDatabase extends Command $this->friendlyLine(sprintf('DSN is %s', $dsn)); $options = [ - \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, - \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, - \PDO::ATTR_EMULATE_PREPARES => false, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, ]; // when it fails, display error try { - $pdo = new \PDO($dsn, (string) env('DB_USERNAME'), (string) env('DB_PASSWORD'), $options); - } catch (\PDOException $e) { + $pdo = new PDO($dsn, (string) env('DB_USERNAME'), (string) env('DB_PASSWORD'), $options); + } catch (PDOException $e) { $this->friendlyError(sprintf('Error when connecting to DB: %s', $e->getMessage())); return 1; diff --git a/app/Console/Commands/System/ForcesDecimalSize.php b/app/Console/Commands/System/ForcesDecimalSize.php index eaec52cdfb..4b54218f10 100644 --- a/app/Console/Commands/System/ForcesDecimalSize.php +++ b/app/Console/Commands/System/ForcesDecimalSize.php @@ -43,6 +43,9 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use function Safe\mb_regex_encoding; +use function Safe\json_encode; + /** * This command was inspired by https://github.com/elliot-gh. It will check all amount fields * and their values and correct them to the correct number of decimal places. This fixes issues where @@ -130,7 +133,7 @@ class ForcesDecimalSize extends Command // if sqlite, add function? if ('sqlite' === (string) config('database.default')) { DB::connection()->getPdo()->sqliteCreateFunction('REGEXP', static function ($pattern, $value) { - \Safe\mb_regex_encoding('UTF-8'); + mb_regex_encoding('UTF-8'); $pattern = trim($pattern, '"'); return (false !== mb_ereg($pattern, (string) $value)) ? 1 : 0; @@ -234,7 +237,7 @@ class ForcesDecimalSize extends Command /** @var Builder $query */ $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', \Safe\json_encode((string) $currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ; $query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { @@ -338,7 +341,7 @@ class ForcesDecimalSize extends Command ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', \Safe\json_encode((string) $currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $cast, $operator, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -394,7 +397,7 @@ class ForcesDecimalSize extends Command ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', \Safe\json_encode((string) $currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -448,7 +451,7 @@ class ForcesDecimalSize extends Command $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', \Safe\json_encode((string) $currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( diff --git a/app/Console/Commands/System/OutputsInstructions.php b/app/Console/Commands/System/OutputsInstructions.php index 0d3e64d854..0c691971bf 100644 --- a/app/Console/Commands/System/OutputsInstructions.php +++ b/app/Console/Commands/System/OutputsInstructions.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\System; +use Carbon\Carbon; use FireflyIII\Support\System\GeneratesInstallationId; use Illuminate\Console\Command; @@ -111,8 +112,8 @@ class OutputsInstructions extends Command */ private function showLogo(): void { - $today = date('m-d'); - $month = date('m'); + $today = Carbon::now()->format('m-d'); + $month = Carbon::now()->format('m'); // variation in colors and effects just because I can! // default is Ukraine flag: $colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default']; diff --git a/app/Console/Commands/System/ScansAttachments.php b/app/Console/Commands/System/ScansAttachments.php index 001f2ec80c..6597025bcd 100644 --- a/app/Console/Commands/System/ScansAttachments.php +++ b/app/Console/Commands/System/ScansAttachments.php @@ -31,6 +31,11 @@ use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Storage; +use function Safe\tempnam; +use function Safe\file_put_contents; +use function Safe\md5_file; +use function Safe\mime_content_type; + class ScansAttachments extends Command { use ShowsFriendlyMessages; @@ -63,15 +68,15 @@ class ScansAttachments extends Command app('log')->error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage())); $decryptedContent = $encryptedContent; } - $tempFileName = \Safe\tempnam(sys_get_temp_dir(), 'FireflyIII'); + $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); if (false === $tempFileName) { app('log')->error(sprintf('Could not create temporary file for attachment #%d', $attachment->id)); exit(1); } - \Safe\file_put_contents($tempFileName, $decryptedContent); - $attachment->md5 = (string) \Safe\md5_file($tempFileName); - $attachment->mime = (string) \Safe\mime_content_type($tempFileName); + file_put_contents($tempFileName, $decryptedContent); + $attachment->md5 = (string) md5_file($tempFileName); + $attachment->mime = (string) mime_content_type($tempFileName); $attachment->save(); $this->friendlyInfo(sprintf('Fixed attachment #%d', $attachment->id)); } diff --git a/app/Console/Commands/System/VerifySecurityAlerts.php b/app/Console/Commands/System/VerifySecurityAlerts.php index 0cad167ccb..920142d794 100644 --- a/app/Console/Commands/System/VerifySecurityAlerts.php +++ b/app/Console/Commands/System/VerifySecurityAlerts.php @@ -30,6 +30,8 @@ use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Storage; use League\Flysystem\FilesystemException; +use function Safe\json_decode; + class VerifySecurityAlerts extends Command { use ShowsFriendlyMessages; @@ -57,7 +59,7 @@ class VerifySecurityAlerts extends Command return 0; } $content = $disk->get('alerts.json'); - $json = \Safe\json_decode($content, true, 10); + $json = json_decode((string) $content, true, 10); /** @var array $array */ foreach ($json as $array) { diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index f62eab5439..b2a891b5d6 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -248,7 +248,7 @@ class ApplyRules extends Command foreach ($ruleList as $ruleId) { $rule = $this->ruleRepository->find((int) $ruleId); - if (null !== $rule && true === $rule->active) { + if ($rule instanceof Rule && true === $rule->active) { $this->ruleSelection[] = $rule->id; } } diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index c220ccf307..25b073801a 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -34,6 +34,7 @@ use FireflyIII\Support\Cronjobs\RecurringCronjob; use FireflyIII\Support\Cronjobs\UpdateCheckCronjob; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; +use InvalidArgumentException; class Cron extends Command { @@ -62,7 +63,7 @@ class Cron extends Command try { $date = new Carbon($this->option('date')); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { $this->friendlyError(sprintf('"%s" is not a valid date', $this->option('date'))); } $force = (bool) $this->option('force'); // @phpstan-ignore-line @@ -133,7 +134,7 @@ class Cron extends Command $exchangeRates = new ExchangeRatesCronjob(); $exchangeRates->setForce($force); // set date in cron job: - if (null !== $date) { + if ($date instanceof Carbon) { $exchangeRates->setDate($date); } @@ -176,7 +177,7 @@ class Cron extends Command $recurring->setForce($force); // set date in cron job: - if (null !== $date) { + if ($date instanceof Carbon) { $recurring->setDate($date); } @@ -197,7 +198,7 @@ class Cron extends Command $autoBudget = new AutoBudgetCronjob(); $autoBudget->setForce($force); // set date in cron job: - if (null !== $date) { + if ($date instanceof Carbon) { $autoBudget->setDate($date); } @@ -222,7 +223,7 @@ class Cron extends Command $autoBudget = new BillWarningCronjob(); $autoBudget->setForce($force); // set date in cron job: - if (null !== $date) { + if ($date instanceof Carbon) { $autoBudget->setDate($date); } diff --git a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php index aa2b108dea..af59ca61ce 100644 --- a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php +++ b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php @@ -120,7 +120,7 @@ class AddsTransactionIdentifiers extends Command /** @var Transaction $transaction */ foreach ($transactions as $transaction) { $opposing = $this->findOpposing($transaction, $exclude); - if (null !== $opposing) { + if ($opposing instanceof Transaction) { // give both a new identifier: $transaction->identifier = $identifier; $opposing->identifier = $identifier; diff --git a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php index 9bc4477888..87e99cd706 100644 --- a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php +++ b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php @@ -31,6 +31,10 @@ use Illuminate\Console\Command; use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; +use JsonException; +use stdClass; + +use function Safe\json_decode; class RemovesDatabaseDecryption extends Command { @@ -105,13 +109,13 @@ class RemovesDatabaseDecryption extends Command { $rows = DB::table($table)->get(['id', $field]); - /** @var \stdClass $row */ + /** @var stdClass $row */ foreach ($rows as $row) { $this->decryptRow($table, $field, $row); } } - private function decryptRow(string $table, string $field, \stdClass $row): void + private function decryptRow(string $table, string $field, stdClass $row): void { $original = $row->{$field}; if (null === $original) { @@ -167,8 +171,8 @@ class RemovesDatabaseDecryption extends Command { // try to json_decrypt the value. try { - $newValue = \Safe\json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value; - } catch (\JsonException $e) { + $newValue = json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value; + } catch (JsonException $e) { $message = sprintf('Could not JSON decode preference row #%d: %s. This does not have to be a problem.', $id, $e->getMessage()); $this->friendlyError($message); app('log')->warning($message); diff --git a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php index 0c8dea4901..94c5643feb 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\Upgrade; +use FireflyIII\Models\TransactionJournal; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -141,7 +142,7 @@ class UpgradesAccountCurrencies extends Command return; } // do not match and opening balance id is not null. - if ($accountCurrency !== $obCurrency && null !== $openingBalance) { + if ($accountCurrency !== $obCurrency && $openingBalance instanceof TransactionJournal) { // update opening balance: $openingBalance->transaction_currency_id = $accountCurrency; $openingBalance->save(); diff --git a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php index 1e2398c2be..b146f11e8b 100644 --- a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php +++ b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php @@ -123,7 +123,7 @@ class UpgradesBillsToRules extends Command $groupTitle = (string) trans('firefly.rulegroup_for_bills_title', [], $language); $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle); - if (null === $ruleGroup) { + if (!$ruleGroup instanceof RuleGroup) { $ruleGroup = $this->ruleGroupRepository->store( [ 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language), diff --git a/app/Console/Commands/Upgrade/UpgradesDatabase.php b/app/Console/Commands/Upgrade/UpgradesDatabase.php index b6e5764dd4..13d7db7832 100644 --- a/app/Console/Commands/Upgrade/UpgradesDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradesDatabase.php @@ -27,8 +27,10 @@ namespace FireflyIII\Console\Commands\Upgrade; use Illuminate\Support\Facades\Log; use Safe\Exceptions\InfoException; +use function Safe\set_time_limit; + try { - \Safe\set_time_limit(0); + set_time_limit(0); } catch (InfoException) { Log::warning('set_time_limit returned false. This could be an issue, unless you also run XDebug.'); } diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilities.php b/app/Console/Commands/Upgrade/UpgradesLiabilities.php index 0fc444304b..4a4074b1fb 100644 --- a/app/Console/Commands/Upgrade/UpgradesLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradesLiabilities.php @@ -122,7 +122,7 @@ class UpgradesLiabilities extends Command { $source = $this->getSourceTransaction($openingBalance); $destination = $this->getDestinationTransaction($openingBalance); - if (null === $source || null === $destination) { + if (!$source instanceof Transaction || !$destination instanceof Transaction) { return; } // source MUST be the liability. diff --git a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php index 39a715ced9..d40f566a4c 100644 --- a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php @@ -30,6 +30,8 @@ use FireflyIII\Models\RecurrenceMeta; use FireflyIII\Models\RecurrenceTransactionMeta; use Illuminate\Console\Command; +use function Safe\json_encode; + class UpgradesRecurrenceMetaData extends Command { use ShowsFriendlyMessages; @@ -100,7 +102,7 @@ class UpgradesRecurrenceMetaData extends Command if ('tags' === $meta->name) { $array = explode(',', $meta->value); - $value = \Safe\json_encode($array, JSON_THROW_ON_ERROR); + $value = json_encode($array, JSON_THROW_ON_ERROR); } RecurrenceTransactionMeta::create( diff --git a/app/Console/Commands/Upgrade/UpgradesToGroups.php b/app/Console/Commands/Upgrade/UpgradesToGroups.php index 137a9f8bea..453c31e0d3 100644 --- a/app/Console/Commands/Upgrade/UpgradesToGroups.php +++ b/app/Console/Commands/Upgrade/UpgradesToGroups.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\Upgrade; +use Carbon\Carbon; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Factory\TransactionGroupFactory; use FireflyIII\Models\Budget; @@ -36,6 +37,7 @@ use FireflyIII\Services\Internal\Destroy\JournalDestroyService; use Illuminate\Console\Command; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use Exception; class UpgradesToGroups extends Command { @@ -103,7 +105,7 @@ class UpgradesToGroups extends Command } /** - * @throws \Exception + * @throws Exception */ private function makeGroupsFromSplitJournals(): void { @@ -119,7 +121,7 @@ class UpgradesToGroups extends Command } /** - * @throws \Exception + * @throws Exception */ private function makeMultiGroup(TransactionJournal $journal): void { @@ -191,7 +193,7 @@ class UpgradesToGroups extends Command app('log')->debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id)); $opposingTr = $this->findOpposingTransaction($journal, $transaction); - if (null === $opposingTr) { + if (!$opposingTr instanceof Transaction) { $this->friendlyError( sprintf( 'Journal #%d has no opposing transaction for transaction #%d. Cannot upgrade this entry.', @@ -366,8 +368,8 @@ class UpgradesToGroups extends Command { $groupId = DB::table('transaction_groups')->insertGetId( [ - 'created_at' => date('Y-m-d H:i:s'), - 'updated_at' => date('Y-m-d H:i:s'), + 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), + 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), 'title' => null, 'user_id' => $array['user_id'], ] diff --git a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php index 90f6affb97..d92813d6cd 100644 --- a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php @@ -202,7 +202,7 @@ class UpgradesTransferCurrencies extends Command { $this->sourceTransaction = $this->getSourceTransaction($journal); $this->sourceAccount = $this->sourceTransaction?->account; - $this->sourceCurrency = null === $this->sourceAccount ? null : $this->getCurrency($this->sourceAccount); + $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null; } private function getSourceTransaction(TransactionJournal $transfer): ?Transaction @@ -221,7 +221,7 @@ class UpgradesTransferCurrencies extends Command return $this->accountCurrencies[$accountId]; } $currency = $this->accountRepos->getAccountCurrency($account); - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; return null; @@ -238,7 +238,7 @@ class UpgradesTransferCurrencies extends Command { $this->destinationTransaction = $this->getDestinationTransaction($journal); $this->destinationAccount = $this->destinationTransaction?->account; - $this->destinationCurrency = null === $this->destinationAccount ? null : $this->getCurrency($this->destinationAccount); + $this->destinationCurrency = $this->destinationAccount instanceof Account ? $this->getCurrency($this->destinationAccount) : null; } private function getDestinationTransaction(TransactionJournal $transfer): ?Transaction @@ -252,15 +252,15 @@ class UpgradesTransferCurrencies extends Command */ private function isEmptyTransactions(): bool { - return null === $this->sourceTransaction || null === $this->destinationTransaction - || null === $this->sourceAccount - || null === $this->destinationAccount; + return !$this->sourceTransaction instanceof Transaction || !$this->destinationTransaction instanceof Transaction + || !$this->sourceAccount instanceof Account + || !$this->destinationAccount instanceof Account; } private function isNoCurrencyPresent(): bool { // source account must have a currency preference. - if (null === $this->sourceCurrency) { + if (!$this->sourceCurrency instanceof TransactionCurrency) { $message = sprintf('Account #%d ("%s") must have currency preference but has none.', $this->sourceAccount->id, $this->sourceAccount->name); app('log')->error($message); $this->friendlyError($message); @@ -269,7 +269,7 @@ class UpgradesTransferCurrencies extends Command } // destination account must have a currency preference. - if (null === $this->destinationCurrency) { + if (!$this->destinationCurrency instanceof TransactionCurrency) { $message = sprintf( 'Account #%d ("%s") must have currency preference but has none.', $this->destinationAccount->id, @@ -290,7 +290,7 @@ class UpgradesTransferCurrencies extends Command */ private function fixSourceNoCurrency(): void { - if (null === $this->sourceTransaction->transaction_currency_id && null !== $this->sourceCurrency) { + if (null === $this->sourceTransaction->transaction_currency_id && $this->sourceCurrency instanceof TransactionCurrency) { $this->sourceTransaction ->transaction_currency_id = $this->sourceCurrency->id @@ -312,7 +312,7 @@ class UpgradesTransferCurrencies extends Command */ private function fixSourceUnmatchedCurrency(): void { - if (null !== $this->sourceCurrency + if ($this->sourceCurrency instanceof TransactionCurrency && null === $this->sourceTransaction->foreign_amount && (int) $this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id ) { @@ -336,7 +336,7 @@ class UpgradesTransferCurrencies extends Command */ private function fixDestNoCurrency(): void { - if (null === $this->destinationTransaction->transaction_currency_id && null !== $this->destinationCurrency) { + if (null === $this->destinationTransaction->transaction_currency_id && $this->destinationCurrency instanceof TransactionCurrency) { $this->destinationTransaction ->transaction_currency_id = $this->destinationCurrency->id @@ -358,7 +358,7 @@ class UpgradesTransferCurrencies extends Command */ private function fixDestinationUnmatchedCurrency(): void { - if (null !== $this->destinationCurrency + if ($this->destinationCurrency instanceof TransactionCurrency && null === $this->destinationTransaction->foreign_amount && (int) $this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id ) { diff --git a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php index 0283e00d7c..648b34ed5e 100644 --- a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php +++ b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php @@ -120,7 +120,7 @@ class UpgradesVariousCurrencyInformation extends Command $leadTransaction = $this->getLeadTransaction($journal); - if (null === $leadTransaction) { + if (!$leadTransaction instanceof Transaction) { $this->friendlyError(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id)); return; @@ -129,7 +129,7 @@ class UpgradesVariousCurrencyInformation extends Command $account = $leadTransaction->account; $currency = $this->getCurrency($account); $isMultiCurrency = $this->isMultiCurrency($account); - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->friendlyError( sprintf( 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected', @@ -227,7 +227,7 @@ class UpgradesVariousCurrencyInformation extends Command return $this->accountCurrencies[$accountId]; } $currency = $this->accountRepos->getAccountCurrency($account); - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; return null; diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index e29ec31305..bccbb2c3e5 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -26,6 +26,7 @@ namespace FireflyIII\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; +use Override; /** * File to make sure commands work. @@ -35,7 +36,7 @@ class Kernel extends ConsoleKernel /** * Register the commands for the application. */ - #[\Override] + #[Override] protected function commands(): void { $this->load(__DIR__.'/Commands'); @@ -46,7 +47,7 @@ class Kernel extends ConsoleKernel /** * Define the application's command schedule. */ - #[\Override] + #[Override] protected function schedule(Schedule $schedule): void { $schedule->call( diff --git a/app/Exceptions/BadHttpHeaderException.php b/app/Exceptions/BadHttpHeaderException.php index 19e1e5a7af..375466c218 100644 --- a/app/Exceptions/BadHttpHeaderException.php +++ b/app/Exceptions/BadHttpHeaderException.php @@ -24,7 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; -class BadHttpHeaderException extends \Exception +use Exception; + +class BadHttpHeaderException extends Exception { public int $statusCode = 406; } diff --git a/app/Exceptions/DuplicateTransactionException.php b/app/Exceptions/DuplicateTransactionException.php index b8d6ece025..f468652981 100644 --- a/app/Exceptions/DuplicateTransactionException.php +++ b/app/Exceptions/DuplicateTransactionException.php @@ -24,7 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; +use Exception; + /** * Class DuplicateTransactionException */ -class DuplicateTransactionException extends \Exception {} +class DuplicateTransactionException extends Exception {} diff --git a/app/Exceptions/FireflyException.php b/app/Exceptions/FireflyException.php index 18b3fb0a35..bca7de92bd 100644 --- a/app/Exceptions/FireflyException.php +++ b/app/Exceptions/FireflyException.php @@ -24,7 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; +use Exception; + /** * Class FireflyException. */ -class FireflyException extends \Exception {} +class FireflyException extends Exception {} diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php index 7faa9e03e2..7866d20047 100644 --- a/app/Exceptions/GracefulNotFoundHandler.php +++ b/app/Exceptions/GracefulNotFoundHandler.php @@ -34,6 +34,8 @@ use FireflyIII\User; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; +use Override; +use Throwable; /** * Class GracefulNotFoundHandler @@ -45,12 +47,12 @@ class GracefulNotFoundHandler extends ExceptionHandler * * @param Request $request * - * @throws \Throwable + * @throws Throwable * * @SuppressWarnings("PHPMD.CyclomaticComplexity") */ - #[\Override] - public function render($request, \Throwable $e): Response + #[Override] + public function render($request, Throwable $e): Response { $route = $request->route(); if (null === $route) { @@ -149,9 +151,9 @@ class GracefulNotFoundHandler extends ExceptionHandler } /** - * @throws \Throwable + * @throws Throwable */ - private function handleAccount(Request $request, \Throwable $exception): Response + private function handleAccount(Request $request, Throwable $exception): Response { app('log')->debug('404 page is probably a deleted account. Redirect to overview of account types.'); @@ -184,9 +186,9 @@ class GracefulNotFoundHandler extends ExceptionHandler /** * @return Response * - * @throws \Throwable + * @throws Throwable */ - private function handleGroup(Request $request, \Throwable $exception) + private function handleGroup(Request $request, Throwable $exception) { app('log')->debug('404 page is probably a deleted group. Redirect to overview of group types.'); @@ -224,9 +226,9 @@ class GracefulNotFoundHandler extends ExceptionHandler /** * @return Response * - * @throws \Throwable + * @throws Throwable */ - private function handleAttachment(Request $request, \Throwable $exception) + private function handleAttachment(Request $request, Throwable $exception) { app('log')->debug('404 page is probably a deleted attachment. Redirect to parent object.'); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 9368d57cc0..77f198dae1 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; +use Carbon\Carbon; use Brick\Math\Exception\NumberFormatException; use FireflyIII\Jobs\MailError; use Illuminate\Auth\Access\AuthorizationException; @@ -44,6 +45,12 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use ErrorException; +use Override; +use Throwable; + +use function Safe\json_encode; +use function Safe\parse_url; // temp /** @@ -52,7 +59,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class Handler extends ExceptionHandler { /** - * @var array> + * @var array> */ protected $dontReport = [ @@ -70,7 +77,7 @@ class Handler extends ExceptionHandler /** * Register the exception handling callbacks for the application. */ - #[\Override] + #[Override] public function register(): void {} /** @@ -79,13 +86,13 @@ class Handler extends ExceptionHandler * * @param Request $request * - * @throws \Throwable + * @throws Throwable * * @SuppressWarnings("PHPMD.NPathComplexity") * @SuppressWarnings("PHPMD.CyclomaticComplexity") */ - #[\Override] - public function render($request, \Throwable $e): Response + #[Override] + public function render($request, Throwable $e): Response { $expectsJson = $request->expectsJson(); @@ -188,7 +195,7 @@ class Handler extends ExceptionHandler return response()->view('errors.DatabaseException', ['exception' => $e, 'debug' => $isDebug], 500); } - if ($e instanceof FireflyException || $e instanceof \ErrorException || $e instanceof OAuthServerException) { + if ($e instanceof FireflyException || $e instanceof ErrorException || $e instanceof OAuthServerException) { app('log')->debug('Return Firefly III error view.'); $isDebug = config('app.debug'); @@ -203,10 +210,10 @@ class Handler extends ExceptionHandler /** * Report or log an exception. * - * @throws \Throwable + * @throws Throwable */ - #[\Override] - public function report(\Throwable $e): void + #[Override] + public function report(Throwable $e): void { $doMailError = (bool) config('firefly.send_error_message'); if ($this->shouldntReportLocal($e) || !$doMailError) { @@ -228,7 +235,7 @@ class Handler extends ExceptionHandler $data = [ 'class' => $e::class, 'errorMessage' => $e->getMessage(), - 'time' => date('r'), + 'time' => Carbon::now()->format('r'), 'stackTrace' => $e->getTraceAsString(), 'file' => $e->getFile(), 'line' => $e->getLine(), @@ -239,7 +246,7 @@ class Handler extends ExceptionHandler 'json' => request()->acceptsJson(), 'method' => request()->method(), 'headers' => $headers, - 'post' => 'POST' === request()->method() ? \Safe\json_encode(request()->all()) : '', + 'post' => 'POST' === request()->method() ? json_encode(request()->all()) : '', ]; // create job that will mail. @@ -250,7 +257,7 @@ class Handler extends ExceptionHandler parent::report($e); } - private function shouldntReportLocal(\Throwable $e): bool + private function shouldntReportLocal(Throwable $e): bool { return null !== Arr::first( $this->dontReport, @@ -263,7 +270,7 @@ class Handler extends ExceptionHandler * * @param Request $request */ - #[\Override] + #[Override] protected function invalid($request, LaravelValidationException $exception): \Illuminate\Http\Response|JsonResponse|RedirectResponse { // protect against open redirect when submitting invalid forms. @@ -286,8 +293,8 @@ class Handler extends ExceptionHandler } $safe = route('index'); $previous = $exception->redirectTo; - $previousHost = \Safe\parse_url($previous, PHP_URL_HOST); - $safeHost = \Safe\parse_url($safe, PHP_URL_HOST); + $previousHost = parse_url($previous, PHP_URL_HOST); + $safeHost = parse_url($safe, PHP_URL_HOST); return null !== $previousHost && $previousHost === $safeHost ? $previous : $safe; } diff --git a/app/Exceptions/IntervalException.php b/app/Exceptions/IntervalException.php index c411b2dd1c..45fe7cddfb 100644 --- a/app/Exceptions/IntervalException.php +++ b/app/Exceptions/IntervalException.php @@ -25,11 +25,13 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; use FireflyIII\Support\Calendar\Periodicity; +use Exception; +use Throwable; /** * Class IntervalException */ -final class IntervalException extends \Exception +final class IntervalException extends Exception { public array $availableIntervals; public Periodicity $periodicity; @@ -37,7 +39,7 @@ final class IntervalException extends \Exception /** @var mixed */ protected $message = 'The periodicity %s is unknown. Choose one of available periodicity: %s'; - public function __construct(string $message = '', int $code = 0, ?\Throwable $previous = null) + public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); $this->availableIntervals = []; @@ -48,7 +50,7 @@ final class IntervalException extends \Exception Periodicity $periodicity, array $intervals, int $code = 0, - ?\Throwable $previous = null + ?Throwable $previous = null ): self { $message = sprintf( 'The periodicity %s is unknown. Choose one of available periodicity: %s', diff --git a/app/Exceptions/NotImplementedException.php b/app/Exceptions/NotImplementedException.php index 37bc63c0bb..40d6a6e362 100644 --- a/app/Exceptions/NotImplementedException.php +++ b/app/Exceptions/NotImplementedException.php @@ -24,7 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; +use Exception; + /** * Class NotImplementedException. */ -class NotImplementedException extends \Exception {} +class NotImplementedException extends Exception {} diff --git a/app/Exceptions/ValidationException.php b/app/Exceptions/ValidationException.php index 1927df03ef..5a89abb0c2 100644 --- a/app/Exceptions/ValidationException.php +++ b/app/Exceptions/ValidationException.php @@ -24,7 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; +use Exception; + /** * Class ValidationExceptions. */ -class ValidationException extends \Exception {} +class ValidationException extends Exception {} diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index 2a359bc823..94e9f5a5d9 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -75,7 +75,7 @@ class AccountFactory app('log')->debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); $type = $this->accountRepository->getAccountTypeByType($accountType); - if (null === $type) { + if (!$type instanceof AccountType) { throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType)); } $return = $this->user->accounts->where('account_type_id', $type->id)->where('name', $accountName)->first(); @@ -111,7 +111,7 @@ class AccountFactory // account may exist already: $return = $this->find($data['name'], $type->type); - if (null !== $return) { + if ($return instanceof Account) { return $return; } diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index 12b8c9b686..7a6babf654 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Factory; +use FireflyIII\Models\ObjectGroup; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Bill; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; @@ -93,7 +94,7 @@ class BillFactory $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(); } @@ -102,7 +103,7 @@ class BillFactory $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(); } @@ -124,7 +125,7 @@ class BillFactory // then find by name: if (null === $bill && '' !== $billName) { - $bill = $this->findByName($billName); + return $this->findByName($billName); } return $bill; diff --git a/app/Factory/BudgetFactory.php b/app/Factory/BudgetFactory.php index b08b1f2e4e..bbb274fa5d 100644 --- a/app/Factory/BudgetFactory.php +++ b/app/Factory/BudgetFactory.php @@ -53,7 +53,7 @@ class BudgetFactory if ('' !== $budgetName) { $budget = $this->findByName($budgetName); - if (null !== $budget) { + if ($budget instanceof Budget) { return $budget; } } diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php index 9978e2c233..754dba7644 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -59,7 +59,7 @@ class CategoryFactory if ('' !== $categoryName) { $category = $this->findByName($categoryName); - if (null !== $category) { + if ($category instanceof Category) { return $category; } diff --git a/app/Factory/PiggyBankEventFactory.php b/app/Factory/PiggyBankEventFactory.php index 7cfed006a5..52643c55f7 100644 --- a/app/Factory/PiggyBankEventFactory.php +++ b/app/Factory/PiggyBankEventFactory.php @@ -37,7 +37,7 @@ class PiggyBankEventFactory public function create(TransactionJournal $journal, ?PiggyBank $piggyBank): void { app('log')->debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type)); - if (null === $piggyBank) { + if (!$piggyBank instanceof PiggyBank) { app('log')->debug('Piggy bank is null'); return; diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index a6707e8b40..519b56fbfd 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Factory; +use FireflyIII\Models\ObjectGroup; +use FireflyIII\Models\Account; use FireflyIII\Events\Model\PiggyBank\ChangedAmount; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\PiggyBank; @@ -35,6 +37,8 @@ use FireflyIII\User; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; +use function Safe\json_encode; + /** * Class PiggyBankFactory */ @@ -99,7 +103,7 @@ class PiggyBankFactory $objectGroupTitle = $data['object_group_title'] ?? ''; if ('' !== $objectGroupTitle) { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); - if (null !== $objectGroup) { + if ($objectGroup instanceof ObjectGroup) { $piggyBank->objectGroups()->sync([$objectGroup->id]); } } @@ -107,7 +111,7 @@ class PiggyBankFactory $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); - if (null !== $objectGroup) { + if ($objectGroup instanceof ObjectGroup) { $piggyBank->objectGroups()->sync([$objectGroup->id]); } } @@ -241,7 +245,7 @@ class PiggyBankFactory /** @var array $info */ foreach ($accounts as $info) { $account = $this->accountRepository->find((int) ($info['account_id'] ?? 0)); - if (null === $account) { + if (!$account instanceof Account) { Log::debug(sprintf('Account #%d not found, skipping.', (int) ($info['account_id'] ?? 0))); continue; @@ -284,7 +288,7 @@ class PiggyBankFactory Log::debug(sprintf('Will link account #%d with info: ', $account->id), $toBeLinked[$account->id]); } } - Log::debug(sprintf('Link information: %s', \Safe\json_encode($toBeLinked))); + Log::debug(sprintf('Link information: %s', json_encode($toBeLinked))); if (0 !== count($toBeLinked)) { $piggyBank->accounts()->sync($toBeLinked); } diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php index 892a6cfe37..b3a0e376e7 100644 --- a/app/Factory/TagFactory.php +++ b/app/Factory/TagFactory.php @@ -59,7 +59,7 @@ class TagFactory 'zoom_level' => null, ] ); - if (null === $newTag) { + if (!$newTag instanceof Tag) { app('log')->error(sprintf('TagFactory::findOrCreate("%s") but tag is unexpectedly NULL!', $tag)); return null; diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php index 1065b7bda3..9a1b590bf7 100644 --- a/app/Factory/TransactionFactory.php +++ b/app/Factory/TransactionFactory.php @@ -118,7 +118,7 @@ class TransactionFactory ); // do foreign currency thing: add foreign currency info to $one and $two if necessary. - if (null !== $this->foreignCurrency + if ($this->foreignCurrency instanceof TransactionCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id) { $result->foreign_currency_id = $this->foreignCurrency->id; diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index f89c86b3aa..bf1a755e9e 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Factory; +use FireflyIII\Models\Bill; +use FireflyIII\Models\PiggyBank; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; @@ -51,6 +53,10 @@ use FireflyIII\User; use FireflyIII\Validation\AccountValidator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Exception; +use JsonException; + +use function Safe\json_encode; /** * Class TransactionJournalFactory @@ -76,7 +82,7 @@ class TransactionJournalFactory /** * Constructor. * - * @throws \Exception + * @throws Exception */ public function __construct() { @@ -120,10 +126,10 @@ class TransactionJournalFactory foreach ($transactions as $index => $row) { Log::debug(sprintf('Now creating journal %d/%d', $index + 1, count($transactions))); $journal = $this->createJournal(new NullArrayObject($row)); - if (null !== $journal) { + if ($journal instanceof TransactionJournal) { $collection->push($journal); } - if (null === $journal) { + if (!$journal instanceof TransactionJournal) { Log::error('The createJournal() method returned NULL. This may indicate an error.'); } } @@ -173,7 +179,7 @@ class TransactionJournalFactory $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); - $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && null !== $bill ? $bill->id : null; + $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null; $description = (string) $row['description']; // Manipulate basic fields @@ -284,7 +290,7 @@ class TransactionJournalFactory // see the currency they expect to see. $amount = (string) $row['amount']; $foreignAmount = (string) $row['foreign_amount']; - if (null !== $foreignCurrency && $foreignCurrency->id !== $currency->id + if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id !== $currency->id && (TransactionTypeEnum::TRANSFER->value === $type->type || $this->isBetweenAssetAndLiability($sourceAccount, $destinationAccount)) ) { $transactionFactory->setCurrency($foreignCurrency); @@ -323,8 +329,8 @@ class TransactionJournalFactory unset($dataRow['import_hash_v2'], $dataRow['original_source']); try { - $json = \Safe\json_encode($dataRow, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + $json = json_encode($dataRow, JSON_THROW_ON_ERROR); + } catch (JsonException $e) { Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage())); $json = microtime(); } @@ -352,7 +358,7 @@ class TransactionJournalFactory ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id') ->whereNotNull('transaction_journals.id') ->where('transaction_journals.user_id', $this->user->id) - ->where('data', \Safe\json_encode($hash, JSON_THROW_ON_ERROR)) + ->where('data', json_encode($hash, JSON_THROW_ON_ERROR)) ->with(['transactionJournal', 'transactionJournal.transactionGroup']) ->first(['journal_meta.*']) ; @@ -425,12 +431,12 @@ class TransactionJournalFactory private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array { Log::debug(sprintf('Now in %s', __METHOD__)); - if (null !== $sourceAccount && null !== $destinationAccount) { + if ($sourceAccount instanceof Account && $destinationAccount instanceof Account) { Log::debug('Both accounts exist, simply return them.'); return [$sourceAccount, $destinationAccount]; } - if (null === $destinationAccount) { + if (!$destinationAccount instanceof Account) { Log::debug('Destination account is NULL, source account is not.'); $account = $this->accountRepository->getReconciliation($sourceAccount); Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type)); @@ -438,7 +444,7 @@ class TransactionJournalFactory return [$sourceAccount, $account]; } - if (null === $sourceAccount) { // @phpstan-ignore-line + if (!$sourceAccount instanceof Account) { // @phpstan-ignore-line Log::debug('Source account is NULL, destination account is not.'); $account = $this->accountRepository->getReconciliation($destinationAccount); Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type)); @@ -480,7 +486,7 @@ class TransactionJournalFactory /** @var null|TransactionCurrency $preference */ $preference = $this->accountRepository->getAccountCurrency($account); - if (null === $preference && null === $currency) { + if (null === $preference && !$currency instanceof TransactionCurrency) { // return user's default: return app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); } @@ -496,10 +502,10 @@ class TransactionJournalFactory private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency { Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code)); - if (null === $currency) { + if (!$currency instanceof TransactionCurrency) { return null; } - if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) { + if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $currency->id) { return null; } @@ -556,7 +562,7 @@ class TransactionJournalFactory $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']); - if (null !== $piggyBank) { + if ($piggyBank instanceof PiggyBank) { $this->piggyEventFactory->create($journal, $piggyBank); Log::debug('Create piggy event.'); diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index 49487a84b5..f711be2185 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -27,6 +27,7 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -56,7 +57,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('doubles', $this->expense) ->render() ; - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Account/MultiYearReportGenerator.php b/app/Generator/Report/Account/MultiYearReportGenerator.php index ff59598046..467b461113 100644 --- a/app/Generator/Report/Account/MultiYearReportGenerator.php +++ b/app/Generator/Report/Account/MultiYearReportGenerator.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Generator\Report\Account; +use Override; + /** * Class MultiYearReportGenerator. */ @@ -31,7 +33,7 @@ class MultiYearReportGenerator extends MonthReportGenerator /** * Returns the preferred period. */ - #[\Override] + #[Override] protected function preferredPeriod(): string { return 'year'; diff --git a/app/Generator/Report/Account/YearReportGenerator.php b/app/Generator/Report/Account/YearReportGenerator.php index 4b39570840..90a1b03cb6 100644 --- a/app/Generator/Report/Account/YearReportGenerator.php +++ b/app/Generator/Report/Account/YearReportGenerator.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Generator\Report\Account; +use Override; + /** * Class YearReportGenerator. */ @@ -31,7 +33,7 @@ class YearReportGenerator extends MonthReportGenerator /** * Returns the preferred period. */ - #[\Override] + #[Override] protected function preferredPeriod(): string { return 'month'; diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index 5d6767a6db..a8bbca3b18 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -34,6 +34,7 @@ use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\Facades\Steam; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -103,7 +104,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('start', $this->start)->with('end', $this->end)->with('accounts', $this->accounts) ->render() ; - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Budget/MonthReportGenerator.php b/app/Generator/Report/Budget/MonthReportGenerator.php index 2e86d36c15..7c19c19e54 100644 --- a/app/Generator/Report/Budget/MonthReportGenerator.php +++ b/app/Generator/Report/Budget/MonthReportGenerator.php @@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -70,7 +71,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('accounts', $this->accounts) ->render() ; - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Category/MonthReportGenerator.php b/app/Generator/Report/Category/MonthReportGenerator.php index f0acb5520a..61dd7f5cac 100644 --- a/app/Generator/Report/Category/MonthReportGenerator.php +++ b/app/Generator/Report/Category/MonthReportGenerator.php @@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -71,7 +72,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('accounts', $this->accounts) ->render() ; - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.category.month: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Standard/MonthReportGenerator.php b/app/Generator/Report/Standard/MonthReportGenerator.php index fe70dc3041..edbe7910b6 100644 --- a/app/Generator/Report/Standard/MonthReportGenerator.php +++ b/app/Generator/Report/Standard/MonthReportGenerator.php @@ -27,6 +27,7 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -54,7 +55,7 @@ class MonthReportGenerator implements ReportGeneratorInterface try { return view('reports.default.month', compact('accountIds', 'reportType'))->with('start', $this->start)->with('end', $this->end)->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.default.month: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render report view.'; diff --git a/app/Generator/Report/Standard/MultiYearReportGenerator.php b/app/Generator/Report/Standard/MultiYearReportGenerator.php index f40dcfe8eb..d5e42a4dcb 100644 --- a/app/Generator/Report/Standard/MultiYearReportGenerator.php +++ b/app/Generator/Report/Standard/MultiYearReportGenerator.php @@ -27,6 +27,7 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -58,7 +59,7 @@ class MultiYearReportGenerator implements ReportGeneratorInterface 'reports.default.multi-year', compact('accountIds', 'reportType') )->with('start', $this->start)->with('end', $this->end)->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.default.multi-year: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Standard/YearReportGenerator.php b/app/Generator/Report/Standard/YearReportGenerator.php index 74b3b57ea9..6ac88700c2 100644 --- a/app/Generator/Report/Standard/YearReportGenerator.php +++ b/app/Generator/Report/Standard/YearReportGenerator.php @@ -27,6 +27,7 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -58,7 +59,7 @@ class YearReportGenerator implements ReportGeneratorInterface 'reports.default.year', compact('accountIds', 'reportType') )->with('start', $this->start)->with('end', $this->end)->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render report view.'; diff --git a/app/Generator/Report/Tag/MonthReportGenerator.php b/app/Generator/Report/Tag/MonthReportGenerator.php index 12f94d62cf..82d1c0c247 100644 --- a/app/Generator/Report/Tag/MonthReportGenerator.php +++ b/app/Generator/Report/Tag/MonthReportGenerator.php @@ -28,6 +28,7 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class MonthReportGenerator. @@ -65,7 +66,7 @@ class MonthReportGenerator implements ReportGeneratorInterface 'reports.tag.month', compact('accountIds', 'reportType', 'tagIds') )->with('start', $this->start)->with('end', $this->end)->with('tags', $this->tags)->with('accounts', $this->accounts)->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Handlers/Events/APIEventHandler.php b/app/Handlers/Events/APIEventHandler.php index cad6117f7a..7d59a4b636 100644 --- a/app/Handlers/Events/APIEventHandler.php +++ b/app/Handlers/Events/APIEventHandler.php @@ -28,6 +28,7 @@ use FireflyIII\Notifications\User\NewAccessToken; use FireflyIII\Repositories\User\UserRepositoryInterface; use Illuminate\Support\Facades\Notification; use Laravel\Passport\Events\AccessTokenCreated; +use Exception; /** * Class APIEventHandler @@ -48,7 +49,7 @@ class APIEventHandler if (null !== $user) { try { Notification::send($user, new NewAccessToken()); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); diff --git a/app/Handlers/Events/AdminEventHandler.php b/app/Handlers/Events/AdminEventHandler.php index 3121a569c9..5fe258067c 100644 --- a/app/Handlers/Events/AdminEventHandler.php +++ b/app/Handlers/Events/AdminEventHandler.php @@ -37,6 +37,7 @@ use FireflyIII\Notifications\Test\OwnerTestNotificationPushover; use FireflyIII\Notifications\Test\OwnerTestNotificationSlack; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; +use Exception; /** * Class AdminEventHandler. @@ -52,7 +53,7 @@ class AdminEventHandler try { Notification::send(new OwnerNotifiable(), new UserInvitation($event->invitee)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -74,7 +75,7 @@ class AdminEventHandler try { $owner = new OwnerNotifiable(); Notification::send($owner, new UnknownUserLoginAttempt($event->address)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -104,7 +105,7 @@ class AdminEventHandler try { $owner = new OwnerNotifiable(); Notification::send($owner, new VersionCheckResult($event->message)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -158,7 +159,7 @@ class AdminEventHandler try { Notification::send($event->owner, new $class()); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); diff --git a/app/Handlers/Events/AutomationHandler.php b/app/Handlers/Events/AutomationHandler.php index 4d5b4e8006..11b11a7b65 100644 --- a/app/Handlers/Events/AutomationHandler.php +++ b/app/Handlers/Events/AutomationHandler.php @@ -31,6 +31,7 @@ use FireflyIII\Notifications\User\TransactionCreation; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Transformers\TransactionGroupTransformer; use Illuminate\Support\Facades\Notification; +use Exception; /** * Class AutomationHandler @@ -78,7 +79,7 @@ class AutomationHandler try { Notification::send($user, new TransactionCreation($groups)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); diff --git a/app/Handlers/Events/BillEventHandler.php b/app/Handlers/Events/BillEventHandler.php index b600fe2dbe..8ecb2fab82 100644 --- a/app/Handlers/Events/BillEventHandler.php +++ b/app/Handlers/Events/BillEventHandler.php @@ -27,6 +27,7 @@ namespace FireflyIII\Handlers\Events; use FireflyIII\Events\WarnUserAboutBill; use FireflyIII\Notifications\User\BillReminder; use Illuminate\Support\Facades\Notification; +use Exception; /** * Class BillEventHandler @@ -47,7 +48,7 @@ class BillEventHandler try { Notification::send($bill->user, new BillReminder($bill, $event->field, $event->diff)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); 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/Security/MFAHandler.php b/app/Handlers/Events/Security/MFAHandler.php index 9b24cc0495..a259a742e2 100644 --- a/app/Handlers/Events/Security/MFAHandler.php +++ b/app/Handlers/Events/Security/MFAHandler.php @@ -39,6 +39,7 @@ use FireflyIII\Notifications\Security\MFAManyFailedAttemptsNotification; use FireflyIII\Notifications\Security\MFAUsedBackupCodeNotification; use FireflyIII\Notifications\Security\NewBackupCodesNotification; use Illuminate\Support\Facades\Notification; +use Exception; class MFAHandler { @@ -51,7 +52,7 @@ class MFAHandler try { Notification::send($user, new MFABackupFewLeftNotification($user, $count)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -76,7 +77,7 @@ class MFAHandler try { Notification::send($user, new MFABackupNoLeftNotification($user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -101,7 +102,7 @@ class MFAHandler try { Notification::send($user, new DisabledMFANotification($user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -126,7 +127,7 @@ class MFAHandler try { Notification::send($user, new EnabledMFANotification($user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -152,7 +153,7 @@ class MFAHandler try { Notification::send($user, new MFAManyFailedAttemptsNotification($user, $count)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -177,7 +178,7 @@ class MFAHandler try { Notification::send($user, new NewBackupCodesNotification($user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -202,7 +203,7 @@ class MFAHandler try { Notification::send($user, new MFAUsedBackupCodeNotification($user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 70e2c8dab2..ebe0cca9f6 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -56,6 +56,7 @@ use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Notification; +use Exception; /** * Class UserEventHandler. @@ -203,7 +204,7 @@ class UserEventHandler if (false === $entry['notified']) { try { Notification::send($user, new UserLogin()); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -233,7 +234,7 @@ class UserEventHandler try { Notification::send($owner, new AdminRegistrationNotification($event->user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -267,7 +268,7 @@ class UserEventHandler try { Mail::to($newEmail)->send(new ConfirmEmailChangeMail($newEmail, $oldEmail, $url)); - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->error($e->getMessage()); app('log')->error($e->getTraceAsString()); @@ -292,7 +293,7 @@ class UserEventHandler try { Mail::to($oldEmail)->send(new UndoEmailChangeMail($newEmail, $oldEmail, $url)); - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->error($e->getMessage()); app('log')->error($e->getTraceAsString()); @@ -304,7 +305,7 @@ class UserEventHandler { try { Notification::send($event->user, new UserFailedLoginAttempt($event->user)); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -328,7 +329,7 @@ class UserEventHandler { try { Notification::send($event->user, new UserNewPassword(route('password.reset', [$event->token]))); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -356,7 +357,7 @@ class UserEventHandler try { Mail::to($invitee)->send(new InvitationMail($invitee, $admin, $url)); - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->error($e->getMessage()); app('log')->error($e->getTraceAsString()); @@ -374,7 +375,7 @@ class UserEventHandler if ($sendMail) { try { Notification::send($event->user, new UserRegistrationNotification()); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -429,7 +430,7 @@ class UserEventHandler try { Notification::send($event->user, new $class()); - } catch (\Exception $e) { + } catch (Exception $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); @@ -483,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 3d8583805e..28194b7e03 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -37,6 +37,14 @@ 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; + /** * Class AttachmentHelper. */ @@ -85,7 +93,7 @@ class AttachmentHelper implements AttachmentHelperInterface */ public function getAttachmentLocation(Attachment $attachment): string { - return sprintf('%sat-%d.data', \DIRECTORY_SEPARATOR, $attachment->id); + return sprintf('%sat-%d.data', DIRECTORY_SEPARATOR, $attachment->id); } /** @@ -118,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.'); @@ -133,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; } @@ -151,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; } @@ -163,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; @@ -225,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(); @@ -280,7 +288,7 @@ class AttachmentHelper implements AttachmentHelperInterface } if (true === $result && $this->hasFile($file, $model)) { - $result = false; + return false; } return $result; @@ -333,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/AccountCollection.php b/app/Helpers/Collector/Extensions/AccountCollection.php index a8d408a15e..2328b5dabc 100644 --- a/app/Helpers/Collector/Extensions/AccountCollection.php +++ b/app/Helpers/Collector/Extensions/AccountCollection.php @@ -30,13 +30,14 @@ use FireflyIII\Support\Facades\Steam; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Override; /** * Trait AccountCollection */ trait AccountCollection { - #[\Override] + #[Override] public function accountBalanceIs(string $direction, string $operator, string $value): GroupCollectorInterface { Log::warning(sprintf('GroupCollector will be SLOW: accountBalanceIs: "%s" "%s" "%s"', $direction, $operator, $value)); 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 4cff722226..5daa03922e 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -45,6 +45,10 @@ use Illuminate\Database\Query\JoinClause; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Closure; +use Override; + +use function Safe\json_decode; /** * Class GroupCollector @@ -582,7 +586,7 @@ class GroupCollector implements GroupCollectorInterface $result['date']->setTimezone(config('app.timezone')); $result['created_at']->setTimezone(config('app.timezone')); $result['updated_at']->setTimezone(config('app.timezone')); - } catch (\Exception $e) { // intentional generic exception + } catch (Exception $e) { // intentional generic exception app('log')->error($e->getMessage()); throw new FireflyException($e->getMessage(), 0, $e); @@ -593,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)); } } @@ -778,7 +782,7 @@ class GroupCollector implements GroupCollectorInterface app('log')->debug(sprintf('GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).', count($this->postFilters), count($currentCollection))); /** - * @var \Closure $function + * @var Closure $function */ foreach ($this->postFilters as $function) { app('log')->debug('Applying filter...'); @@ -812,7 +816,7 @@ class GroupCollector implements GroupCollectorInterface return $currentCollection; } - #[\Override] + #[Override] public function sortCollection(Collection $collection): Collection { /** @@ -1004,7 +1008,7 @@ class GroupCollector implements GroupCollectorInterface return $this; } - #[\Override] + #[Override] public function setSorting(array $instructions): GroupCollectorInterface { $this->sorting = $instructions; @@ -1044,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(); } @@ -1104,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 e1b77af37d..6d42a4ac56 100644 --- a/app/Helpers/Webhook/Sha3SignatureGenerator.php +++ b/app/Helpers/Webhook/Sha3SignatureGenerator.php @@ -24,8 +24,12 @@ 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 @@ -46,8 +50,8 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface $json = ''; try { - $json = \Safe\json_encode($message->message, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + $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)); app('log')->error($e->getMessage()); @@ -62,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/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index 761070bd46..71f7b7dc27 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -53,6 +53,9 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use function Safe\file_get_contents; use function Safe\ini_get; +use const PHP_INT_SIZE; +use const PHP_SAPI; + /** * Class DebugController */ @@ -111,7 +114,7 @@ class DebugController extends Controller try { Artisan::call('twig:clean'); - } catch (\Exception $e) { // intentional generic exception + } catch (Exception $e) { // intentional generic exception throw new FireflyException($e->getMessage(), 0, $e); } @@ -177,8 +180,8 @@ class DebugController extends Controller 'php_version' => PHP_VERSION, 'php_os' => PHP_OS, 'uname' => php_uname('m'), - 'interface' => \PHP_SAPI, - 'bits' => \PHP_INT_SIZE * 8, + 'interface' => PHP_SAPI, + 'bits' => PHP_INT_SIZE * 8, 'bcscale' => bcscale(), 'display_errors' => ini_get('display_errors'), 'error_reporting' => $this->errorReporting((int) ini_get('error_reporting')), @@ -203,7 +206,7 @@ class DebugController extends Controller $return['build'] = trim((string) file_get_contents('/var/www/counter-main.txt')); app('log')->debug(sprintf('build is now "%s"', $return['build'])); } - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->debug('Could not check build counter, but thats ok.'); app('log')->warning($e->getMessage()); } @@ -212,7 +215,7 @@ class DebugController extends Controller if (file_exists('/var/www/build-date-main.txt')) { $return['build_date'] = trim((string) file_get_contents('/var/www/build-date-main.txt')); } - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->debug('Could not check build date, but thats ok.'); app('log')->warning($e->getMessage()); } diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 4f300d8924..b829724308 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; +use Exception; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; use FireflyIII\Enums\AccountTypeEnum; @@ -57,7 +58,7 @@ class HomeController extends Controller /** * Change index date range. * - * @throws \Exception + * @throws Exception */ public function dateRange(Request $request): JsonResponse { diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index 08ed98cd53..f508c66763 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; +use Throwable; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\PiggyBank; @@ -89,7 +90,7 @@ class FrontpageController extends Controller if (0 !== count($info)) { try { $html = view('json.piggy-banks', compact('info', 'convertToNative', 'native'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render json.piggy-banks: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $html = 'Could not render view.'; diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index f2122dc310..db7642cfe8 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; +use Throwable; use Carbon\Carbon; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -130,7 +131,7 @@ class ReconcileController extends Controller try { $view = view('accounts.reconcile.overview', compact('account', 'start', 'diffCompare', 'difference', 'end', 'clearedAmount', 'startBalance', 'endBalance', 'amount', 'route', 'countCleared', 'reconSum', 'selectedIds'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('View error: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $view = sprintf('Could not render accounts.reconcile.overview: %s', $e->getMessage()); @@ -228,7 +229,7 @@ class ReconcileController extends Controller 'accounts.reconcile.transactions', compact('account', 'journals', 'currency', 'start', 'end', 'selectionStart', 'selectionEnd') )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $html = sprintf('Could not render accounts.reconcile.transactions: %s', $e->getMessage()); diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index c91fb1c1e3..a555015150 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; +use Throwable; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; @@ -50,7 +51,7 @@ class RuleController extends Controller try { $view = view('rules.partials.action', compact('actions', 'count'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render rules.partials.action: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $view = 'Could not render view.'; @@ -80,7 +81,7 @@ class RuleController extends Controller try { $view = view('rules.partials.trigger', compact('triggers', 'count'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render rules.partials.trigger: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $view = 'Could not render view.'; diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index 4f2526083c..3031037624 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; +use JsonException; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Events\Preferences\UserGroupChangedDefaultCurrency; @@ -155,7 +156,7 @@ class PreferencesController extends Controller try { $locales = json_decode((string) file_get_contents(resource_path(sprintf('locales/%s/locales.json', $language))), true, 512, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + } catch (JsonException $e) { app('log')->error($e->getMessage()); $locales = []; } diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index 031b09a785..e784c4fb7a 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; +use Exception; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use FireflyIII\Events\UserChangedEmail; @@ -362,7 +363,7 @@ class ProfileController extends Controller * * @return Redirector|RedirectResponse * - * @throws \Exception + * @throws Exception */ public function regenerate(Request $request) { diff --git a/app/Http/Controllers/Report/AccountController.php b/app/Http/Controllers/Report/AccountController.php index d99ec61237..dcd9464ce3 100644 --- a/app/Http/Controllers/Report/AccountController.php +++ b/app/Http/Controllers/Report/AccountController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -58,7 +59,7 @@ class AccountController extends Controller try { $result = view('reports.partials.accounts', compact('accountReport'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.accounts: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; diff --git a/app/Http/Controllers/Report/BalanceController.php b/app/Http/Controllers/Report/BalanceController.php index 914f12061c..41b3010a4a 100644 --- a/app/Http/Controllers/Report/BalanceController.php +++ b/app/Http/Controllers/Report/BalanceController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -140,7 +141,7 @@ class BalanceController extends Controller try { $result = view('reports.partials.balance', compact('report'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.balance: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; diff --git a/app/Http/Controllers/Report/BillController.php b/app/Http/Controllers/Report/BillController.php index afbb68362c..1fd70e3c48 100644 --- a/app/Http/Controllers/Report/BillController.php +++ b/app/Http/Controllers/Report/BillController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Report\ReportHelperInterface; @@ -58,7 +59,7 @@ class BillController extends Controller try { $result = view('reports.partials.bills', compact('report'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budgets: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index 67c316891d..f24dd2b551 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -176,7 +177,7 @@ class BudgetController extends Controller try { $result = view('reports.budget.partials.avg-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); app('log')->error($e->getTraceAsString()); @@ -326,7 +327,7 @@ class BudgetController extends Controller try { $result = view('reports.partials.budget-period', compact('report', 'periods'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; @@ -377,7 +378,7 @@ class BudgetController extends Controller try { $result = view('reports.budget.partials.top-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index 0168fdd75e..fc8d17421a 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -295,7 +296,7 @@ class CategoryController extends Controller try { $result = view('reports.category.partials.avg-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -345,7 +346,7 @@ class CategoryController extends Controller try { $result = view('reports.category.partials.avg-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -527,7 +528,7 @@ class CategoryController extends Controller try { $result = view('reports.partials.category-period', compact('report', 'periods'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); @@ -599,7 +600,7 @@ class CategoryController extends Controller try { $result = view('reports.partials.category-period', compact('report', 'periods'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); @@ -639,7 +640,7 @@ class CategoryController extends Controller try { $result = view('reports.partials.categories', compact('report'))->render(); $cache->store($result); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); @@ -687,7 +688,7 @@ class CategoryController extends Controller try { $result = view('reports.category.partials.top-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -735,7 +736,7 @@ class CategoryController extends Controller try { $result = view('reports.category.partials.top-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php index 79d9d5fc1e..32a1736844 100644 --- a/app/Http/Controllers/Report/DoubleController.php +++ b/app/Http/Controllers/Report/DoubleController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -102,7 +103,7 @@ class DoubleController extends Controller try { $result = view('reports.double.partials.avg-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -152,7 +153,7 @@ class DoubleController extends Controller try { $result = view('reports.double.partials.avg-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -429,7 +430,7 @@ class DoubleController extends Controller try { $result = view('reports.double.partials.top-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -477,7 +478,7 @@ class DoubleController extends Controller try { $result = view('reports.double.partials.top-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); diff --git a/app/Http/Controllers/Report/OperationsController.php b/app/Http/Controllers/Report/OperationsController.php index de27b13d04..d2aaeaa3dd 100644 --- a/app/Http/Controllers/Report/OperationsController.php +++ b/app/Http/Controllers/Report/OperationsController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -78,7 +79,7 @@ class OperationsController extends Controller try { $result = view('reports.partials.income-expenses', compact('report', 'type'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.income-expense: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; @@ -112,7 +113,7 @@ class OperationsController extends Controller try { $result = view('reports.partials.income-expenses', compact('report', 'type'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.income-expenses: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; @@ -167,7 +168,7 @@ class OperationsController extends Controller try { $result = view('reports.partials.operations', compact('sums'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render reports.partials.operations: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view.'; diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index 0b8f8cde7b..22bca3fd99 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -292,7 +293,7 @@ class TagController extends Controller try { $result = view('reports.tag.partials.avg-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -342,7 +343,7 @@ class TagController extends Controller try { $result = view('reports.tag.partials.avg-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -490,7 +491,7 @@ class TagController extends Controller try { $result = view('reports.tag.partials.top-expenses', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); @@ -538,7 +539,7 @@ class TagController extends Controller try { $result = view('reports.tag.partials.top-income', compact('result'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php index c6f50d48ec..848fa259a3 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; +use Throwable; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleFormRequest; @@ -177,7 +178,7 @@ class EditController extends Controller 'triggers' => $triggers, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { $message = sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage()); app('log')->debug($message); app('log')->error($e->getTraceAsString()); diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index d6dae9d5fa..24c7dc0860 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; +use Throwable; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -174,7 +175,7 @@ class SelectController extends Controller try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { app('log')->error(sprintf('Could not render view in testTriggers(): %s', $exception->getMessage())); app('log')->error($exception->getTraceAsString()); $view = sprintf('Could not render list.journals-tiny: %s', $exception->getMessage()); @@ -216,7 +217,7 @@ class SelectController extends Controller try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { $message = sprintf('Could not render view in testTriggersByRule(): %s', $exception->getMessage()); app('log')->error($message); app('log')->error($exception->getTraceAsString()); diff --git a/app/Http/Controllers/RuleGroup/ExecutionController.php b/app/Http/Controllers/RuleGroup/ExecutionController.php index 542d38d0a7..40419e9656 100644 --- a/app/Http/Controllers/RuleGroup/ExecutionController.php +++ b/app/Http/Controllers/RuleGroup/ExecutionController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\RuleGroup; +use Exception; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\SelectTransactionsRequest; @@ -64,7 +65,7 @@ class ExecutionController extends Controller /** * Execute the given rulegroup on a set of existing transactions. * - * @throws \Exception + * @throws Exception */ public function execute(SelectTransactionsRequest $request, RuleGroup $ruleGroup): RedirectResponse { diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index ceab9169c5..b30d1eefad 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; +use Throwable; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Support\Search\SearchInterface; @@ -118,7 +119,7 @@ class SearchController extends Controller try { $html = view('search.search', compact('groups', 'hasPages', 'searchTime'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render search.search: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $html = 'Could not render view.'; diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index 8f59b12f46..e2acfb680f 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -146,7 +146,7 @@ class InstallController extends Controller Artisan::call($command, $args); app('log')->debug(Artisan::output()); } - } catch (\Exception $e) { // intentional generic exception + } catch (Exception $e) { // intentional generic exception throw new FireflyException($e->getMessage(), 0, $e); } // clear cache as well. diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index 929d46ede7..d3b00a5738 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -82,7 +82,7 @@ class ConvertController extends Controller * * @return Factory|Redirector|RedirectResponse|View * - * @throws \Exception + * @throws Exception */ public function index(TransactionType $destinationType, TransactionGroup $group) { @@ -214,7 +214,7 @@ class ConvertController extends Controller } /** - * @throws \Exception + * @throws Exception */ private function getLiabilities(): array { @@ -238,7 +238,7 @@ class ConvertController extends Controller } /** - * @throws \Exception + * @throws Exception */ private function getAssetAccounts(): array { diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index aa44005821..bac580dc76 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; +use InvalidArgumentException; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; @@ -231,7 +232,7 @@ class MassController extends Controller try { $carbon = Carbon::parse($value[$journalId]); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { Log::warning(sprintf('Could not parse "%s" but dont mind', $value[$journalId])); Log::warning($e->getMessage()); diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index a4de77717e..7f11d50cba 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\User; use Illuminate\Auth\AuthenticationException; @@ -56,7 +57,7 @@ class Authenticate * @throws FireflyException * @throws AuthenticationException */ - public function handle($request, \Closure $next, ...$guards) + public function handle($request, Closure $next, ...$guards) { $this->authenticate($request, $guards); diff --git a/app/Http/Middleware/Binder.php b/app/Http/Middleware/Binder.php index 9f4413a06d..7b03830ba5 100644 --- a/app/Http/Middleware/Binder.php +++ b/app/Http/Middleware/Binder.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Support\Domain; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Http\Request; @@ -63,7 +64,7 @@ class Binder * * @return mixed */ - public function handle($request, \Closure $next) + public function handle($request, Closure $next) { foreach ($request->route()->parameters() as $key => $value) { if (array_key_exists($key, $this->binders)) { diff --git a/app/Http/Middleware/InstallationId.php b/app/Http/Middleware/InstallationId.php index 79ac8daedc..6c8aff7dab 100644 --- a/app/Http/Middleware/InstallationId.php +++ b/app/Http/Middleware/InstallationId.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Support\System\GeneratesInstallationId; use Illuminate\Http\Request; @@ -41,7 +42,7 @@ class InstallationId * * @return mixed */ - public function handle($request, \Closure $next) + public function handle($request, Closure $next) { $this->generateInstallationId(); diff --git a/app/Http/Middleware/Installer.php b/app/Http/Middleware/Installer.php index 1954f226bd..f7d38232ca 100644 --- a/app/Http/Middleware/Installer.php +++ b/app/Http/Middleware/Installer.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\System\OAuthKeys; use Illuminate\Database\QueryException; @@ -45,7 +46,7 @@ class Installer * * @throws FireflyException */ - public function handle($request, \Closure $next) + public function handle($request, Closure $next) { // Log::debug(sprintf('Installer middleware for URL %s', $request->url())); // ignore installer in test environment. diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index 49e013d5ed..30c9b65e68 100644 --- a/app/Http/Middleware/InterestingMessage.php +++ b/app/Http/Middleware/InterestingMessage.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Models\Account; use FireflyIII\Models\Bill; use FireflyIII\Models\GroupMembership; @@ -45,7 +46,7 @@ class InterestingMessage * * @return mixed */ - public function handle(Request $request, \Closure $next) + public function handle(Request $request, Closure $next) { if ($this->testing()) { return $next($request); diff --git a/app/Http/Middleware/IsAdmin.php b/app/Http/Middleware/IsAdmin.php index c992713911..2412e607b7 100644 --- a/app/Http/Middleware/IsAdmin.php +++ b/app/Http/Middleware/IsAdmin.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Http\Request; @@ -40,7 +41,7 @@ class IsAdmin * * @return mixed */ - public function handle(Request $request, \Closure $next, $guard = null) + public function handle(Request $request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($request->ajax()) { diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index c984e947a5..e792003b9a 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Http\Request; @@ -37,7 +38,7 @@ class IsDemoUser * * @return mixed */ - public function handle(Request $request, \Closure $next) + public function handle(Request $request, Closure $next) { /** @var null|User $user */ $user = $request->user(); diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index d0e151d331..4699a454c0 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use Illuminate\Support\Facades\App; use Carbon\Carbon; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; @@ -43,7 +44,7 @@ class Range * * @return mixed */ - public function handle(Request $request, \Closure $next) + public function handle(Request $request, Closure $next) { if (null !== $request->user()) { // set start, end and finish: diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 5bffbb7146..01cda1a816 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -39,7 +40,7 @@ class RedirectIfAuthenticated * * @return mixed */ - public function handle($request, \Closure $next, $guard = null) + public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { return response()->redirectTo(route('index')); diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 4ae071b11f..5f8b104992 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Closure; +use Exception; use Barryvdh\Debugbar\Facades\Debugbar; use Illuminate\Http\Request; use Illuminate\Support\Facades\Vite; @@ -38,9 +40,9 @@ class SecureHeaders * * @return mixed * - * @throws \Exception + * @throws Exception */ - public function handle(Request $request, \Closure $next) + public function handle(Request $request, Closure $next) { // generate and share nonce. $nonce = base64_encode(random_bytes(16)); diff --git a/app/Http/Middleware/StartFireflySession.php b/app/Http/Middleware/StartFireflySession.php index 03359f735a..922bc3ad8c 100644 --- a/app/Http/Middleware/StartFireflySession.php +++ b/app/Http/Middleware/StartFireflySession.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Override; use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Session\Middleware\StartSession; @@ -37,7 +38,7 @@ class StartFireflySession extends StartSession * * @param Session $session */ - #[\Override] + #[Override] protected function storeCurrentUrl(Request $request, $session): void { $url = $request->fullUrl(); diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php index 9dcd6a249a..4446201045 100644 --- a/app/Http/Middleware/TrustHosts.php +++ b/app/Http/Middleware/TrustHosts.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Override; use Illuminate\Http\Middleware\TrustHosts as Middleware; class TrustHosts extends Middleware @@ -33,7 +34,7 @@ class TrustHosts extends Middleware * * @return array */ - #[\Override] + #[Override] public function hosts(): array { return [ diff --git a/app/Http/Requests/ReportFormRequest.php b/app/Http/Requests/ReportFormRequest.php index bf7e4417bb..8c5de287d4 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -149,7 +149,7 @@ class ReportFormRequest extends FormRequest if (false !== $result && 0 !== $result) { try { $date = new Carbon($parts[1]); - } catch (\Exception $e) { // intentional generic exception + } catch (Exception $e) { // intentional generic exception $error = sprintf('"%s" is not a valid date range: %s', $range, $e->getMessage()); app('log')->error($error); app('log')->error($e->getTraceAsString()); @@ -187,7 +187,7 @@ class ReportFormRequest extends FormRequest if (false !== $result && 0 !== $result) { try { $date = new Carbon($parts[0]); - } catch (\Exception $e) { // intentional generic exception + } catch (Exception $e) { // intentional generic exception $error = sprintf('"%s" is not a valid date range: %s', $range, $e->getMessage()); app('log')->error($error); app('log')->error($e->getTraceAsString()); 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 229a55b28d..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; @@ -30,6 +31,12 @@ use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; 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. @@ -47,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))); } /** @@ -80,7 +87,7 @@ class MailError extends Job implements ShouldQueue } } ); - } catch (\Exception|TransportException $e) { + } catch (Exception|TransportException $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { app('log')->warning('[Bcc] Could not email or log the error. Please validate your email settings, use the .env.example file as a guide.'); @@ -118,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) { @@ -130,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, ]; } @@ -150,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/AccountType.php b/app/Models/AccountType.php index cffbf7a8bf..d4571fde77 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -32,46 +32,46 @@ class AccountType extends Model { use ReturnsIntegerIdTrait; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string ASSET = 'Asset account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string BENEFICIARY = 'Beneficiary account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string CASH = 'Cash account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string CREDITCARD = 'Credit card'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string DEBT = 'Debt'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string DEFAULT = 'Default account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string EXPENSE = 'Expense account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string IMPORT = 'Import account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string INITIAL_BALANCE = 'Initial balance account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string LIABILITY_CREDIT = 'Liability credit account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string LOAN = 'Loan'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string MORTGAGE = 'Mortgage'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string RECONCILIATION = 'Reconciliation account'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string REVENUE = 'Revenue account'; protected $casts diff --git a/app/Models/AutoBudget.php b/app/Models/AutoBudget.php index 85deb27d83..7f53584616 100644 --- a/app/Models/AutoBudget.php +++ b/app/Models/AutoBudget.php @@ -36,13 +36,13 @@ class AutoBudget extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int AUTO_BUDGET_ADJUSTED = 3; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int AUTO_BUDGET_RESET = 1; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int AUTO_BUDGET_ROLLOVER = 2; protected $casts = [ 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/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php index a5bcfc7f17..93ad02a196 100644 --- a/app/Models/RecurrenceRepetition.php +++ b/app/Models/RecurrenceRepetition.php @@ -36,16 +36,16 @@ class RecurrenceRepetition extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int WEEKEND_DO_NOTHING = 1; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int WEEKEND_SKIP_CREATION = 2; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int WEEKEND_TO_FRIDAY = 3; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const int WEEKEND_TO_MONDAY = 4; protected $casts 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/Models/TransactionType.php b/app/Models/TransactionType.php index 06fcde6c17..0b04ead8b5 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -36,25 +36,25 @@ class TransactionType extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string DEPOSIT = 'Deposit'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string INVALID = 'Invalid'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string LIABILITY_CREDIT = 'Liability credit'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string OPENING_BALANCE = 'Opening balance'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string RECONCILIATION = 'Reconciliation'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string TRANSFER = 'Transfer'; - #[\Deprecated] /** @deprecated */ + #[Deprecated] /** @deprecated */ public const string WITHDRAWAL = 'Withdrawal'; protected $casts 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/AccountServiceProvider.php b/app/Providers/AccountServiceProvider.php index 939815c8a8..311aae4bba 100644 --- a/app/Providers/AccountServiceProvider.php +++ b/app/Providers/AccountServiceProvider.php @@ -31,6 +31,7 @@ use FireflyIII\Repositories\Account\OperationsRepository; use FireflyIII\Repositories\Account\OperationsRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class AccountServiceProvider. @@ -45,7 +46,7 @@ class AccountServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->registerRepository(); diff --git a/app/Providers/AdminServiceProvider.php b/app/Providers/AdminServiceProvider.php index 1709ca658d..ac768ddb9d 100644 --- a/app/Providers/AdminServiceProvider.php +++ b/app/Providers/AdminServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\LinkType\LinkTypeRepository; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class AdminServiceProvider @@ -41,7 +42,7 @@ class AdminServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->linkType(); diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 169258cb36..263342b753 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -29,6 +29,9 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Laravel\Passport\Passport; +use Override; + +use function Safe\preg_match; /** * Class AppServiceProvider @@ -47,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; } @@ -87,7 +90,7 @@ class AppServiceProvider extends ServiceProvider /** * Register any application services. */ - #[\Override] + #[Override] public function register(): void { Passport::ignoreRoutes(); diff --git a/app/Providers/AttachmentServiceProvider.php b/app/Providers/AttachmentServiceProvider.php index c4cfb6d264..50a00766fe 100644 --- a/app/Providers/AttachmentServiceProvider.php +++ b/app/Providers/AttachmentServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\Attachment\AttachmentRepository; use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class AttachmentServiceProvider. @@ -41,7 +42,7 @@ class AttachmentServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/BillServiceProvider.php b/app/Providers/BillServiceProvider.php index e2a3a42e71..2035762a51 100644 --- a/app/Providers/BillServiceProvider.php +++ b/app/Providers/BillServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\Bill\BillRepository; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class BillServiceProvider. @@ -41,7 +42,7 @@ class BillServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/BudgetServiceProvider.php b/app/Providers/BudgetServiceProvider.php index 8da9ef97b8..25184a1aac 100644 --- a/app/Providers/BudgetServiceProvider.php +++ b/app/Providers/BudgetServiceProvider.php @@ -35,6 +35,7 @@ use FireflyIII\Repositories\Budget\OperationsRepository; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class BudgetServiceProvider. @@ -51,7 +52,7 @@ class BudgetServiceProvider extends ServiceProvider * * @SuppressWarnings("PHPMD.ExcessiveMethodLength") */ - #[\Override] + #[Override] public function register(): void { // reference to auth is not understood by phpstan. diff --git a/app/Providers/CategoryServiceProvider.php b/app/Providers/CategoryServiceProvider.php index 4c86c9800e..2ab8db6ff5 100644 --- a/app/Providers/CategoryServiceProvider.php +++ b/app/Providers/CategoryServiceProvider.php @@ -31,6 +31,7 @@ use FireflyIII\Repositories\Category\OperationsRepository; use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class CategoryServiceProvider. @@ -45,7 +46,7 @@ class CategoryServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { // phpstan does not understand reference to 'auth'. diff --git a/app/Providers/CurrencyServiceProvider.php b/app/Providers/CurrencyServiceProvider.php index 4f9c466cb8..6ffb3688f7 100644 --- a/app/Providers/CurrencyServiceProvider.php +++ b/app/Providers/CurrencyServiceProvider.php @@ -31,6 +31,7 @@ use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepository; use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class CurrencyServiceProvider. @@ -45,7 +46,7 @@ class CurrencyServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 7b3be85ddc..b016fe0e4d 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -101,6 +101,7 @@ use FireflyIII\Models\WebhookMessage; use Illuminate\Auth\Events\Login; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Laravel\Passport\Events\AccessTokenCreated; +use Override; /** * Class EventServiceProvider. @@ -260,7 +261,7 @@ class EventServiceProvider extends ServiceProvider /** * Register any events for your application. */ - #[\Override] + #[Override] public function boot(): void { $this->registerObservers(); diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index 2b9360f85a..83b4c1e585 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -76,6 +76,7 @@ use Illuminate\Foundation\Application; use Illuminate\Support\Facades\Validator; use Illuminate\Support\ServiceProvider; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; +use Override; /** * Class FireflyServiceProvider. @@ -99,7 +100,7 @@ class FireflyServiceProvider extends ServiceProvider * * @SuppressWarnings("PHPMD.ExcessiveMethodLength") */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/FireflySessionProvider.php b/app/Providers/FireflySessionProvider.php index 249325dd55..fee1b30ed6 100644 --- a/app/Providers/FireflySessionProvider.php +++ b/app/Providers/FireflySessionProvider.php @@ -26,6 +26,7 @@ namespace FireflyIII\Providers; use FireflyIII\Http\Middleware\StartFireflySession; use Illuminate\Session\SessionManager; use Illuminate\Support\ServiceProvider; +use Override; /** * Class FireflySessionProvider @@ -35,7 +36,7 @@ class FireflySessionProvider extends ServiceProvider /** * Register the service provider. */ - #[\Override] + #[Override] public function register(): void { $this->registerSessionManager(); diff --git a/app/Providers/JournalServiceProvider.php b/app/Providers/JournalServiceProvider.php index 8e758ca143..3c02bbaed4 100644 --- a/app/Providers/JournalServiceProvider.php +++ b/app/Providers/JournalServiceProvider.php @@ -35,6 +35,7 @@ use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepository; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class JournalServiceProvider. @@ -49,7 +50,7 @@ class JournalServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->registerRepository(); diff --git a/app/Providers/PiggyBankServiceProvider.php b/app/Providers/PiggyBankServiceProvider.php index 53e35d02fe..c89fe9c6d0 100644 --- a/app/Providers/PiggyBankServiceProvider.php +++ b/app/Providers/PiggyBankServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\PiggyBank\PiggyBankRepository; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class PiggyBankServiceProvider. @@ -41,7 +42,7 @@ class PiggyBankServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/RecurringServiceProvider.php b/app/Providers/RecurringServiceProvider.php index 9f77c8bdc9..b9aeed4c4f 100644 --- a/app/Providers/RecurringServiceProvider.php +++ b/app/Providers/RecurringServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\Recurring\RecurringRepository; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class RecurringServiceProvider. @@ -41,7 +42,7 @@ class RecurringServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 6e02c53603..caec293d3d 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -25,6 +25,7 @@ namespace FireflyIII\Providers; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Route; +use Override; /** * Class RouteServiceProvider @@ -37,7 +38,7 @@ class RouteServiceProvider extends ServiceProvider /** * Define the routes for the application. */ - #[\Override] + #[Override] public function boot(): void { $this->routes(function (): void { diff --git a/app/Providers/RuleGroupServiceProvider.php b/app/Providers/RuleGroupServiceProvider.php index ff1f0c777d..df76177faf 100644 --- a/app/Providers/RuleGroupServiceProvider.php +++ b/app/Providers/RuleGroupServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\RuleGroup\RuleGroupRepository; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class RuleGroupServiceProvider. @@ -41,7 +42,7 @@ class RuleGroupServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/RuleServiceProvider.php b/app/Providers/RuleServiceProvider.php index e6ef01b7fd..6c3df05f49 100644 --- a/app/Providers/RuleServiceProvider.php +++ b/app/Providers/RuleServiceProvider.php @@ -27,6 +27,7 @@ use FireflyIII\Repositories\Rule\RuleRepository; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class RuleServiceProvider. @@ -41,7 +42,7 @@ class RuleServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/SearchServiceProvider.php b/app/Providers/SearchServiceProvider.php index 10df8973e2..93b96a4b97 100644 --- a/app/Providers/SearchServiceProvider.php +++ b/app/Providers/SearchServiceProvider.php @@ -30,6 +30,7 @@ use FireflyIII\Support\Search\QueryParser\QueryParserInterface; use FireflyIII\Support\Search\SearchInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class SearchServiceProvider. @@ -44,7 +45,7 @@ class SearchServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Providers/SessionServiceProvider.php b/app/Providers/SessionServiceProvider.php index 9c5f4e86f2..2fdf356bd3 100644 --- a/app/Providers/SessionServiceProvider.php +++ b/app/Providers/SessionServiceProvider.php @@ -25,6 +25,7 @@ namespace FireflyIII\Providers; use FireflyIII\Http\Middleware\StartFireflySession; use Illuminate\Session\SessionServiceProvider as BaseSessionServiceProvider; +use Override; /** * Class SessionServiceProvider. @@ -34,7 +35,7 @@ class SessionServiceProvider extends BaseSessionServiceProvider /** * Register the service provider. */ - #[\Override] + #[Override] public function register(): void { $this->registerSessionManager(); diff --git a/app/Providers/TagServiceProvider.php b/app/Providers/TagServiceProvider.php index 271e4160d2..0b11619c22 100644 --- a/app/Providers/TagServiceProvider.php +++ b/app/Providers/TagServiceProvider.php @@ -29,6 +29,7 @@ use FireflyIII\Repositories\Tag\TagRepository; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; +use Override; /** * Class TagServiceProvider. @@ -43,7 +44,7 @@ class TagServiceProvider extends ServiceProvider /** * Register the application services. */ - #[\Override] + #[Override] public function register(): void { $this->app->bind( diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index c498f6a5b1..47cae859bc 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -45,6 +45,9 @@ use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Storage; +use Override; + +use function Safe\json_encode; /** * Class AccountRepository. @@ -108,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); } @@ -162,7 +165,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $account; } - #[\Override] + #[Override] public function getAccountBalances(Account $account): Collection { return $account->accountBalances; @@ -533,7 +536,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return null; } - #[\Override] + #[Override] public function periodCollection(Account $account, Carbon $start, Carbon $end): array { return $account->transactions() 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/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index 961127f085..0e41c59cf4 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -35,6 +35,8 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Storage; use League\Flysystem\UnableToDeleteFile; +use Exception; +use LogicException; /** * Class AttachmentRepository. @@ -44,7 +46,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn use UserGroupTrait; /** - * @throws \Exception + * @throws Exception */ public function destroy(Attachment $attachment): bool { @@ -158,7 +160,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn if (null !== $dbNote) { try { $dbNote->delete(); - } catch (\LogicException $e) { + } catch (LogicException $e) { app('log')->error($e->getMessage()); } } 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 456e8197f6..87a18dde34 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -36,6 +36,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Override; /** * Class BudgetLimitRepository @@ -87,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()); } @@ -134,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) @@ -143,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')); } @@ -200,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')); } @@ -254,7 +255,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ; } - #[\Override] + #[Override] public function getNoteText(BudgetLimit $budgetLimit): string { return (string) $budgetLimit->notes()->first()?->text; @@ -323,7 +324,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ; } - #[\Override] + #[Override] public function setNoteText(BudgetLimit $budgetLimit, string $text): void { $dbNote = $budgetLimit->notes()->first(); 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 19d1447857..487a467c20 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -39,6 +39,7 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; +use Exception; /** * Class CategoryRepository. @@ -110,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; } @@ -190,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; } @@ -271,20 +272,20 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf } /** - * @throws \Exception + * @throws Exception */ public function lastUseDate(Category $category, Collection $accounts): ?Carbon { $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; } @@ -314,7 +315,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf } /** - * @throws \Exception + * @throws Exception */ private function getLastTransactionDate(Category $category, Collection $accounts): ?Carbon { @@ -347,7 +348,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf } /** - * @throws \Exception + * @throws Exception */ public function update(Category $category, array $data): Category { 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 9676766b6c..2716d2e21e 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -42,6 +42,9 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Override; + +use function Safe\json_encode; /** * Class CurrencyRepository. @@ -81,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)); @@ -89,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)); @@ -117,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)); @@ -236,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 */ @@ -259,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; @@ -268,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); } @@ -277,7 +280,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf return $result; } - #[\Override] + #[Override] public function find(int $currencyId): ?TransactionCurrency { return TransactionCurrency::find($currencyId); diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/ExchangeRate/ExchangeRateRepository.php index cce27ba123..f7936e0979 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepository.php @@ -31,24 +31,25 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; +use Override; class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGroupInterface { use UserGroupTrait; - #[\Override] + #[Override] public function deleteRate(CurrencyExchangeRate $rate): void { $this->userGroup->currencyExchangeRates()->where('id', $rate->id)->delete(); } - #[\Override] + #[Override] public function getAll(): Collection { return $this->userGroup->currencyExchangeRates()->orderBy('date', 'ASC')->get(); } - #[\Override] + #[Override] public function getRates(TransactionCurrency $from, TransactionCurrency $to): Collection { // orderBy('date', 'DESC')->toRawSql(); @@ -71,7 +72,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro } - #[\Override] + #[Override] public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate { /** @var null|CurrencyExchangeRate */ @@ -84,7 +85,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro ; } - #[\Override] + #[Override] public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate { $object = new CurrencyExchangeRate(); @@ -100,11 +101,11 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro return $object; } - #[\Override] + #[Override] 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/JournalCLIRepository.php b/app/Repositories/Journal/JournalCLIRepository.php index c3b51cd860..b908dcc82f 100644 --- a/app/Repositories/Journal/JournalCLIRepository.php +++ b/app/Repositories/Journal/JournalCLIRepository.php @@ -32,6 +32,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use stdClass; /** * Class JournalCLIRepository @@ -184,7 +185,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn $result = $query->get(['transaction_journals.id as id', DB::raw('count(transactions.id) as transaction_count')]); // @phpstan-ignore-line $journalIds = []; - /** @var \stdClass $row */ + /** @var stdClass $row */ foreach ($result as $row) { if ((int) $row->transaction_count > 2) { $journalIds[] = (int) $row->id; 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 08a346db38..9b2924b191 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -31,6 +31,7 @@ use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; +use Exception; /** * Class LinkTypeRepository. @@ -46,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(); @@ -71,7 +72,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf } /** - * @throws \Exception + * @throws Exception */ public function destroyLink(TransactionJournalLink $link): bool { @@ -124,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); } @@ -170,23 +171,23 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * Store link between two journals. * - * @throws \Exception + * @throws Exception */ public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink { $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; } @@ -237,7 +238,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf } /** - * @throws \Exception + * @throws Exception */ private function setNoteText(TransactionJournalLink $link, string $text): void { @@ -279,7 +280,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * Update an existing transaction journal link. * - * @throws \Exception + * @throws Exception */ public function updateLink(TransactionJournalLink $journalLink, array $data): TransactionJournalLink { diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php index dd05aefcc4..fdff8e8de0 100644 --- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php +++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php @@ -36,6 +36,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; use FireflyIII\Support\Http\Api\ExchangeRateConverter; use Illuminate\Support\Facades\Log; +use Exception; /** * Trait ModifiesPiggyBanks @@ -142,7 +143,7 @@ trait ModifiesPiggyBanks } /** - * @throws \Exception + * @throws Exception */ public function destroy(PiggyBank $piggyBank): bool { diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index 9296d3c977..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; @@ -41,6 +42,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; +use Override; /** * Class PiggyBankRepository. @@ -68,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; @@ -76,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; @@ -132,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; @@ -266,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; @@ -310,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); } @@ -390,7 +392,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte return $balance; } - #[\Override] + #[Override] public function purgeAll(): void { PiggyBank::withTrashed() @@ -407,7 +409,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte ; } - #[\Override] + #[Override] public function resetOrder(): void { $factory = new PiggyBankFactory(); 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/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 1af214b037..5774e84e9e 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -33,6 +33,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use FireflyIII\Support\Search\OperatorQuerySearch; use Illuminate\Support\Collection; +use Exception; /** * Class RuleRepository. @@ -42,7 +43,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface use UserGroupTrait; /** - * @throws \Exception + * @throws Exception */ public function destroy(Rule $rule): bool { diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index 8615e346ec..3e1694baee 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -32,6 +32,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Exception; /** * Class RuleGroupRepository. @@ -72,13 +73,13 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte } /** - * @throws \Exception + * @throws Exception */ public function destroy(RuleGroup $ruleGroup, ?RuleGroup $moveTo): bool { /** @var Rule $rule */ foreach ($ruleGroup->rules as $rule) { - if (null === $moveTo) { + if (!$moveTo instanceof RuleGroup) { $rule->delete(); continue; @@ -91,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 425582b559..ad3ada6789 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -37,6 +37,7 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; +use Exception; /** * Class TagRepository. @@ -51,7 +52,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface } /** - * @throws \Exception + * @throws Exception */ public function destroy(Tag $tag): bool { @@ -230,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); } @@ -353,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 c9c3063685..8ca4cfcd8c 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -48,6 +48,9 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use Exception; + +use function Safe\json_decode; /** * Class TransactionGroupRepository @@ -244,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 @@ -268,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 @@ -291,7 +292,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** * Return object with all found meta field things as Carbon objects. * - * @throws \Exception + * @throws Exception */ public function getMetaDateFields(int $journalId, array $fields): NullArrayObject { @@ -304,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); @@ -324,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 9abc8554a3..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; @@ -34,6 +35,8 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; use Illuminate\Support\Str; +use Exception; +use Override; /** * Class UserRepository. @@ -44,7 +47,7 @@ class UserRepository implements UserRepositoryInterface * This updates the users email address and records some things so it can be confirmed or undone later. * The user is blocked until the change is confirmed. * - * @throws \Exception + * @throws Exception * * @see updateEmail */ @@ -54,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))); @@ -99,7 +102,7 @@ class UserRepository implements UserRepositoryInterface } /** - * @throws \Exception + * @throws Exception */ public function destroy(User $user): bool { @@ -228,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) { @@ -243,7 +246,7 @@ class UserRepository implements UserRepositoryInterface return false; } - #[\Override] + #[Override] public function getUserGroups(User $user): Collection { $memberships = $user->groupMemberships()->get(); @@ -389,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(); @@ -403,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 e2c266b5e1..f30033dea3 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -35,6 +35,8 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use FireflyIII\User; use Illuminate\Support\Collection; +use Override; +use ValueError; /** * Class UserGroupRepository @@ -132,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 */ @@ -176,13 +178,13 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte return UserGroup::all(); } - #[\Override] + #[Override] public function getById(int $id): ?UserGroup { return UserGroup::find($id); } - #[\Override] + #[Override] public function getMembershipsFromGroupId(int $groupId): Collection { return $this->user->groupMemberships()->where('user_group_id', $groupId)->get(); @@ -286,7 +288,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte foreach ($rolesSimplified as $role) { try { $enum = UserRoleEnum::from($role); - } catch (\ValueError) { + } catch (ValueError) { // TODO error message continue; } @@ -313,7 +315,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte return $roles; } - #[\Override] + #[Override] public function useUserGroup(UserGroup $userGroup): void { $this->user->user_group_id = $userGroup->id; diff --git a/app/Repositories/UserGroups/Account/AccountRepository.php b/app/Repositories/UserGroups/Account/AccountRepository.php index f7aae4dfce..418f16ef8b 100644 --- a/app/Repositories/UserGroups/Account/AccountRepository.php +++ b/app/Repositories/UserGroups/Account/AccountRepository.php @@ -37,6 +37,10 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use Override; +use stdClass; + +use function Safe\json_encode; /** * Class AccountRepository @@ -47,7 +51,7 @@ class AccountRepository implements AccountRepositoryInterface { use UserGroupTrait; - #[\Override] + #[Override] public function countAccounts(array $types): int { $query = $this->userGroup->accounts(); @@ -66,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); } @@ -120,7 +124,7 @@ class AccountRepository implements AccountRepositoryInterface return $account; } - #[\Override] + #[Override] public function getAccountBalances(Account $account): Collection { return $account->accountBalances; @@ -165,14 +169,14 @@ 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 */ return $account; } - #[\Override] + #[Override] public function getAccountTypes(Collection $accounts): Collection { return AccountType::leftJoin('accounts', 'accounts.account_type_id', '=', 'account_types.id') @@ -195,7 +199,7 @@ class AccountRepository implements AccountRepositoryInterface return $query->get(['accounts.*']); } - #[\Override] + #[Override] public function getAccountsInOrder(array $types, array $sort, int $startRow, int $endRow): Collection { $query = $this->userGroup->accounts(); @@ -235,7 +239,7 @@ class AccountRepository implements AccountRepositoryInterface return $query->get(['accounts.*']); } - #[\Override] + #[Override] public function getLastActivity(Collection $accounts): array { return Transaction::whereIn('account_id', $accounts->pluck('id')->toArray()) @@ -245,7 +249,7 @@ class AccountRepository implements AccountRepositoryInterface ; } - #[\Override] + #[Override] public function getMetaValues(Collection $accounts, array $fields): Collection { $query = AccountMeta::whereIn('account_id', $accounts->pluck('id')->toArray()); @@ -256,7 +260,7 @@ class AccountRepository implements AccountRepositoryInterface return $query->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data']); } - #[\Override] + #[Override] public function getObjectGroups(Collection $accounts): array { $groupIds = []; @@ -265,14 +269,14 @@ class AccountRepository implements AccountRepositoryInterface ->whereIn('object_groupable_id', $accounts->pluck('id')->toArray())->get() ; - /** @var \stdClass $row */ + /** @var stdClass $row */ foreach ($set as $row) { $groupIds[] = $row->object_group_id; } $groupIds = array_unique($groupIds); $groups = ObjectGroup::whereIn('id', $groupIds)->get(); - /** @var \stdClass $row */ + /** @var stdClass $row */ foreach ($set as $row) { if (!array_key_exists($row->object_groupable_id, $return)) { /** @var null|ObjectGroup $group */ @@ -368,7 +372,7 @@ class AccountRepository implements AccountRepositoryInterface return $query->get(['accounts.*']); } - #[\Override] + #[Override] public function update(Account $account, array $data): Account { /** @var AccountUpdateService $service */ 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 2460d7d572..3dc1d6a797 100644 --- a/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/UserGroups/ExchangeRate/ExchangeRateRepository.php @@ -30,6 +30,7 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; +use Override; /** * Class ExchangeRateRepository @@ -40,19 +41,19 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface { use UserGroupTrait; - #[\Override] + #[Override] public function deleteRate(CurrencyExchangeRate $rate): void { $this->userGroup->currencyExchangeRates()->where('id', $rate->id)->delete(); } - #[\Override] + #[Override] public function getAll(): Collection { return $this->userGroup->currencyExchangeRates()->orderBy('date', 'ASC')->get(); } - #[\Override] + #[Override] public function getRates(TransactionCurrency $from, TransactionCurrency $to): Collection { // orderBy('date', 'DESC')->toRawSql(); @@ -75,7 +76,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface } - #[\Override] + #[Override] public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate { /** @var null|CurrencyExchangeRate */ @@ -88,7 +89,7 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface ; } - #[\Override] + #[Override] public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate { $object = new CurrencyExchangeRate(); @@ -104,11 +105,11 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface return $object; } - #[\Override] + #[Override] 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/Account/IsValidAccountType.php b/app/Rules/Account/IsValidAccountType.php index 7987b5385c..52042572f1 100644 --- a/app/Rules/Account/IsValidAccountType.php +++ b/app/Rules/Account/IsValidAccountType.php @@ -26,13 +26,15 @@ namespace FireflyIII\Rules\Account; use FireflyIII\Support\Http\Api\AccountFilter; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; +use Override; class IsValidAccountType implements ValidationRule { use AccountFilter; - #[\Override] - public function validate(string $attribute, mixed $value, \Closure $fail): void + #[Override] + public function validate(string $attribute, mixed $value, Closure $fail): void { // only check the type. if (array_key_exists('type', $value)) { diff --git a/app/Rules/Admin/IsValidDiscordUrl.php b/app/Rules/Admin/IsValidDiscordUrl.php index 9d328612d5..ccb4800935 100644 --- a/app/Rules/Admin/IsValidDiscordUrl.php +++ b/app/Rules/Admin/IsValidDiscordUrl.php @@ -28,6 +28,7 @@ namespace FireflyIII\Rules\Admin; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; class IsValidDiscordUrl implements ValidationRule { @@ -36,7 +37,7 @@ class IsValidDiscordUrl implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('' === $value) { diff --git a/app/Rules/Admin/IsValidSlackOrDiscordUrl.php b/app/Rules/Admin/IsValidSlackOrDiscordUrl.php index 866127f988..5b9f6063da 100644 --- a/app/Rules/Admin/IsValidSlackOrDiscordUrl.php +++ b/app/Rules/Admin/IsValidSlackOrDiscordUrl.php @@ -28,6 +28,7 @@ namespace FireflyIII\Rules\Admin; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; class IsValidSlackOrDiscordUrl implements ValidationRule { @@ -36,7 +37,7 @@ class IsValidSlackOrDiscordUrl implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('' === $value) { diff --git a/app/Rules/Admin/IsValidSlackUrl.php b/app/Rules/Admin/IsValidSlackUrl.php index e7e12fd464..90fc1dafcd 100644 --- a/app/Rules/Admin/IsValidSlackUrl.php +++ b/app/Rules/Admin/IsValidSlackUrl.php @@ -28,6 +28,7 @@ namespace FireflyIII\Rules\Admin; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; class IsValidSlackUrl implements ValidationRule { @@ -36,7 +37,7 @@ class IsValidSlackUrl implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('' === $value) { diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php index 564b030443..2e1fa3a9c2 100644 --- a/app/Rules/BelongsUser.php +++ b/app/Rules/BelongsUser.php @@ -32,13 +32,14 @@ use FireflyIII\Models\Category; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\TransactionJournal; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class BelongsUser */ class BelongsUser implements ValidationRule { - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $attribute = $this->parseAttribute($attribute); if (!auth()->check()) { diff --git a/app/Rules/BelongsUserGroup.php b/app/Rules/BelongsUserGroup.php index 8a4f1519c5..fe29b1fbef 100644 --- a/app/Rules/BelongsUserGroup.php +++ b/app/Rules/BelongsUserGroup.php @@ -33,6 +33,7 @@ use FireflyIII\Models\PiggyBank; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class BelongsUserGroup @@ -47,7 +48,7 @@ class BelongsUserGroup implements ValidationRule */ public function __construct(private readonly UserGroup $userGroup) {} - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $attribute = $this->parseAttribute($attribute); if (!auth()->check()) { diff --git a/app/Rules/IsAllowedGroupAction.php b/app/Rules/IsAllowedGroupAction.php index 46c717ef44..f3a197f113 100644 --- a/app/Rules/IsAllowedGroupAction.php +++ b/app/Rules/IsAllowedGroupAction.php @@ -31,6 +31,8 @@ use FireflyIII\User; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; +use Override; class IsAllowedGroupAction implements ValidationRule { @@ -47,8 +49,8 @@ class IsAllowedGroupAction implements ValidationRule /** * @throws AuthorizationException */ - #[\Override] - public function validate(string $attribute, mixed $value, \Closure $fail): void + #[Override] + public function validate(string $attribute, mixed $value, Closure $fail): void { if ('GET' === $this->methodName) { // need at least "read only rights". @@ -69,7 +71,7 @@ class IsAllowedGroupAction implements ValidationRule $this->validateUserGroup((int) $value, $fail); } - private function validateUserGroup(int $userGroupId, \Closure $fail): void + private function validateUserGroup(int $userGroupId, Closure $fail): void { Log::debug(sprintf('validateUserGroup: %s', static::class)); if (!auth()->check()) { diff --git a/app/Rules/IsAssetAccountId.php b/app/Rules/IsAssetAccountId.php index 7eb128dbaf..e8d26937fd 100644 --- a/app/Rules/IsAssetAccountId.php +++ b/app/Rules/IsAssetAccountId.php @@ -26,6 +26,7 @@ namespace FireflyIII\Rules; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsAssetAccountId @@ -35,7 +36,7 @@ class IsAssetAccountId implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $accountId = (int) $value; diff --git a/app/Rules/IsBoolean.php b/app/Rules/IsBoolean.php index 9ffd5a7366..28c1ca3781 100644 --- a/app/Rules/IsBoolean.php +++ b/app/Rules/IsBoolean.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsBoolean @@ -34,7 +35,7 @@ class IsBoolean implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (is_bool($value)) { return; diff --git a/app/Rules/IsDateOrTime.php b/app/Rules/IsDateOrTime.php index 209d64ce12..64d711ec99 100644 --- a/app/Rules/IsDateOrTime.php +++ b/app/Rules/IsDateOrTime.php @@ -28,6 +28,7 @@ use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsDateOrTime @@ -37,7 +38,7 @@ class IsDateOrTime implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('' === $value) { diff --git a/app/Rules/IsDefaultUserGroupName.php b/app/Rules/IsDefaultUserGroupName.php index 6f314e8dff..81b366a2e6 100644 --- a/app/Rules/IsDefaultUserGroupName.php +++ b/app/Rules/IsDefaultUserGroupName.php @@ -28,6 +28,7 @@ use FireflyIII\Models\UserGroup; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsDefaultUserGroupName @@ -39,7 +40,7 @@ class IsDefaultUserGroupName implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); diff --git a/app/Rules/IsDuplicateTransaction.php b/app/Rules/IsDuplicateTransaction.php index b8076b20f6..e0f6d4ac23 100644 --- a/app/Rules/IsDuplicateTransaction.php +++ b/app/Rules/IsDuplicateTransaction.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * TODO not sure where this is used. @@ -38,7 +39,7 @@ class IsDuplicateTransaction implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $this->value = $value; diff --git a/app/Rules/IsFilterValueIn.php b/app/Rules/IsFilterValueIn.php index dddd247fa9..e167bdb79c 100644 --- a/app/Rules/IsFilterValueIn.php +++ b/app/Rules/IsFilterValueIn.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; class IsFilterValueIn implements ValidationRule { @@ -33,7 +34,7 @@ class IsFilterValueIn implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (!is_array($value)) { return; diff --git a/app/Rules/IsTransferAccount.php b/app/Rules/IsTransferAccount.php index ef78af6d98..22f1fc5d8c 100644 --- a/app/Rules/IsTransferAccount.php +++ b/app/Rules/IsTransferAccount.php @@ -27,6 +27,7 @@ namespace FireflyIII\Rules; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Validation\AccountValidator; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsTransferAccount @@ -36,7 +37,7 @@ class IsTransferAccount implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); diff --git a/app/Rules/IsValidActionExpression.php b/app/Rules/IsValidActionExpression.php index 48fcb02efc..d12b507bd3 100644 --- a/app/Rules/IsValidActionExpression.php +++ b/app/Rules/IsValidActionExpression.php @@ -28,17 +28,18 @@ namespace FireflyIII\Rules; use FireflyIII\TransactionRules\Expressions\ActionExpression; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Translation\PotentiallyTranslatedString; +use Closure; class IsValidActionExpression implements ValidationRule { /** * Check that the given action expression is syntactically valid. * - * @param \Closure(string): PotentiallyTranslatedString $fail + * @param Closure(string): PotentiallyTranslatedString $fail * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (false === config('firefly.feature_flags.expression_engine')) { return; diff --git a/app/Rules/IsValidAmount.php b/app/Rules/IsValidAmount.php index b39dfa13ab..208d60c696 100644 --- a/app/Rules/IsValidAmount.php +++ b/app/Rules/IsValidAmount.php @@ -28,6 +28,7 @@ namespace FireflyIII\Rules; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; class IsValidAmount implements ValidationRule { @@ -36,7 +37,7 @@ class IsValidAmount implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index 16388e6242..093e650cf2 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -41,6 +41,7 @@ use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class IsValidAttachmentModel @@ -70,7 +71,7 @@ class IsValidAttachmentModel implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (!auth()->check()) { $fail('validation.model_id_invalid')->translate(); diff --git a/app/Rules/IsValidBulkClause.php b/app/Rules/IsValidBulkClause.php index 148d5600b1..8be8759eed 100644 --- a/app/Rules/IsValidBulkClause.php +++ b/app/Rules/IsValidBulkClause.php @@ -26,6 +26,10 @@ namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Validator; +use Closure; +use JsonException; + +use function Safe\json_decode; /** * Class IsValidBulkClause @@ -49,7 +53,7 @@ class IsValidBulkClause implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $result = $this->basicValidation((string) $value); if (false === $result) { @@ -63,8 +67,8 @@ class IsValidBulkClause implements ValidationRule private function basicValidation(string $value): bool { try { - $array = \Safe\json_decode($value, true, 8, JSON_THROW_ON_ERROR); - } catch (\JsonException) { + $array = json_decode($value, true, 8, JSON_THROW_ON_ERROR); + } catch (JsonException) { $this->error = (string) trans('validation.json'); return false; diff --git a/app/Rules/IsValidDateRange.php b/app/Rules/IsValidDateRange.php index 3d35f011be..faf4b4343e 100644 --- a/app/Rules/IsValidDateRange.php +++ b/app/Rules/IsValidDateRange.php @@ -28,13 +28,14 @@ use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; class IsValidDateRange implements ValidationRule { /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('' === $value) { diff --git a/app/Rules/IsValidPositiveAmount.php b/app/Rules/IsValidPositiveAmount.php index 5f3cc94f66..2c6eeb63cd 100644 --- a/app/Rules/IsValidPositiveAmount.php +++ b/app/Rules/IsValidPositiveAmount.php @@ -28,6 +28,9 @@ namespace FireflyIII\Rules; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; + +use function Safe\json_encode; class IsValidPositiveAmount implements ValidationRule { @@ -36,11 +39,11 @@ class IsValidPositiveAmount implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { 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/IsValidZeroOrMoreAmount.php b/app/Rules/IsValidZeroOrMoreAmount.php index 263691ff8a..3c93762333 100644 --- a/app/Rules/IsValidZeroOrMoreAmount.php +++ b/app/Rules/IsValidZeroOrMoreAmount.php @@ -28,6 +28,7 @@ namespace FireflyIII\Rules; use FireflyIII\Support\Validation\ValidatesAmountsTrait; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Closure; class IsValidZeroOrMoreAmount implements ValidationRule { @@ -38,7 +39,7 @@ class IsValidZeroOrMoreAmount implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (true === $this->nullable && null === $value) { return; diff --git a/app/Rules/LessThanPiggyTarget.php b/app/Rules/LessThanPiggyTarget.php index 2fa6a729eb..78df186875 100644 --- a/app/Rules/LessThanPiggyTarget.php +++ b/app/Rules/LessThanPiggyTarget.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class LessThanPiggyTarget @@ -42,7 +43,7 @@ class LessThanPiggyTarget implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { // TODO not sure if this is still used. } diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index 3e02e2c7e9..9cfae9d359 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -28,6 +28,9 @@ use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\AccountMeta; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; + +use function Safe\json_encode; /** * Class UniqueAccountNumber @@ -66,7 +69,7 @@ class UniqueAccountNumber implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (!auth()->check()) { return; @@ -133,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 b6aca57927..9246326c15 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -28,6 +28,7 @@ use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class UniqueIban @@ -69,7 +70,7 @@ class UniqueIban implements ValidationRule return (string) trans('validation.unique_iban_for_user'); } - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { if (!$this->passes($attribute, $value)) { $fail((string) trans('validation.unique_iban_for_user')); @@ -159,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/Rules/ValidJournals.php b/app/Rules/ValidJournals.php index 68368d21fd..2e2b6c6230 100644 --- a/app/Rules/ValidJournals.php +++ b/app/Rules/ValidJournals.php @@ -26,6 +26,7 @@ namespace FireflyIII\Rules; use FireflyIII\Models\TransactionJournal; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class ValidJournals @@ -35,7 +36,7 @@ class ValidJournals implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { app('log')->debug('In ValidJournals::passes'); if (!is_array($value)) { diff --git a/app/Rules/ValidRecurrenceRepetitionType.php b/app/Rules/ValidRecurrenceRepetitionType.php index d11eded70c..f8e0fe3606 100644 --- a/app/Rules/ValidRecurrenceRepetitionType.php +++ b/app/Rules/ValidRecurrenceRepetitionType.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Rules; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; /** * Class ValidRecurrenceRepetitionType @@ -36,7 +37,7 @@ class ValidRecurrenceRepetitionType implements ValidationRule * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; if ('daily' === $value) { diff --git a/app/Rules/ValidRecurrenceRepetitionValue.php b/app/Rules/ValidRecurrenceRepetitionValue.php index 71576e9cf1..5a1a4b9031 100644 --- a/app/Rules/ValidRecurrenceRepetitionValue.php +++ b/app/Rules/ValidRecurrenceRepetitionValue.php @@ -26,6 +26,8 @@ namespace FireflyIII\Rules; use Carbon\Carbon; use Illuminate\Contracts\Validation\ValidationRule; +use Closure; +use InvalidArgumentException; /** * Class ValidRecurrenceRepetitionValue @@ -35,7 +37,7 @@ class ValidRecurrenceRepetitionValue implements ValidationRule /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validate(string $attribute, mixed $value, \Closure $fail): void + public function validate(string $attribute, mixed $value, Closure $fail): void { $value = (string) $value; @@ -102,7 +104,7 @@ class ValidRecurrenceRepetitionValue implements ValidationRule try { Carbon::createFromFormat('Y-m-d', $dateString); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { app('log')->debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage())); return false; diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index 29499570bc..9516071ddb 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -29,6 +29,9 @@ use FireflyIII\Events\NewVersionAvailable; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use Illuminate\Support\Facades\Log; +use JsonException; + +use function Safe\json_decode; /** * Class UpdateRequest @@ -99,8 +102,8 @@ class UpdateRequest implements UpdateRequestInterface $body = (string) $res->getBody(); try { - $json = \Safe\json_decode($body, true, 512, JSON_THROW_ON_ERROR); - } catch (\JsonException) { + $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { Log::error('Body is not valid JSON'); Log::error($body); $return['message'] = 'Invalid JSON :('; @@ -117,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 44fbaea069..e2e4cb994b 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -32,6 +32,7 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; +use stdClass; /** * Class AccountDestroyService @@ -43,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); } @@ -119,7 +120,7 @@ class AccountDestroyService $service = app(JournalDestroyService::class); $user = $account->user; - /** @var \stdClass $row */ + /** @var stdClass $row */ foreach ($collection as $row) { if ((int) $row->the_count > 1) { $journalId = $row->transaction_journal_id; 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/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php index aff42c2d05..28b5f36f00 100644 --- a/app/Services/Internal/Update/CategoryUpdateService.php +++ b/app/Services/Internal/Update/CategoryUpdateService.php @@ -30,6 +30,7 @@ use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; use FireflyIII\User; +use Exception; /** * Class CategoryUpdateService @@ -59,7 +60,7 @@ class CategoryUpdateService } /** - * @throws \Exception + * @throws Exception */ public function update(Category $category, array $data): Category { @@ -128,7 +129,7 @@ class CategoryUpdateService } /** - * @throws \Exception + * @throws Exception */ private function updateNotes(Category $category, array $data): void { 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 264e754bc8..0962d538aa 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -32,6 +32,9 @@ use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; +use JsonException; + +use function Safe\json_encode; /** * Class StandardWebhookSender @@ -80,8 +83,8 @@ 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); - } catch (\JsonException $e) { + $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()); app('log')->error($e->getTraceAsString()); diff --git a/app/Support/Amount.php b/app/Support/Amount.php index 7fc77c0229..e58c313aac 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -31,6 +31,7 @@ use FireflyIII\Models\UserGroup; use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Support\Collection; +use NumberFormatter; /** * Class Amount. @@ -60,10 +61,10 @@ class Amount $rounded = app('steam')->bcround($amount, $decimalPlaces); $coloured ??= true; - $fmt = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); - $fmt->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $symbol); - $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); - $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); + $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol); + $fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); + $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); $result = (string) $fmt->format((float) $rounded); // intentional float if (true === $coloured) { @@ -114,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))); } @@ -262,10 +263,10 @@ class Amount $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space'); $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space'); - $fmt = new \NumberFormatter($locale, \NumberFormatter::CURRENCY); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); - $info['mon_decimal_point'] = $fmt->getSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL); - $info['mon_thousands_sep'] = $fmt->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL); + $info['mon_decimal_point'] = $fmt->getSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL); + $info['mon_thousands_sep'] = $fmt->getSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL); return $info; } @@ -285,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) { @@ -294,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 @@ -339,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/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php index 2fc06cd450..629ea7d5be 100644 --- a/app/Support/Authentication/RemoteUserProvider.php +++ b/app/Support/Authentication/RemoteUserProvider.php @@ -31,13 +31,14 @@ use FireflyIII\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Str; +use Override; /** * Class RemoteUserProvider */ class RemoteUserProvider implements UserProvider { - #[\Override] + #[Override] public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false): void { app('log')->debug(sprintf('Now at %s', __METHOD__)); diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index 2a95210a8c..b81f040467 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -23,8 +23,12 @@ 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. @@ -79,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)); - } catch (\JsonException) { + $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 a2941a5400..8d200fba17 100644 --- a/app/Support/Calendar/Calculator.php +++ b/app/Support/Calendar/Calculator.php @@ -26,15 +26,16 @@ namespace FireflyIII\Support\Calendar; use Carbon\Carbon; use FireflyIII\Exceptions\IntervalException; +use SplObjectStorage; /** * Class Calculator */ class Calculator { - public const int DEFAULT_INTERVAL = 1; - private static ?\SplObjectStorage $intervalMap = null; // @phpstan-ignore-line - private static array $intervals = []; + public const int DEFAULT_INTERVAL = 1; + private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line + private static array $intervals = []; /** * @throws IntervalException @@ -62,12 +63,12 @@ class Calculator return self::loadIntervalMap()->contains($periodicity); } - private static function loadIntervalMap(): \SplObjectStorage + private static function loadIntervalMap(): SplObjectStorage { - if (null !== self::$intervalMap) { + if (self::$intervalMap instanceof SplObjectStorage) { return self::$intervalMap; } - self::$intervalMap = new \SplObjectStorage(); + self::$intervalMap = new SplObjectStorage(); foreach (Periodicity::cases() as $interval) { $periodicityClass = __NAMESPACE__."\\Periodicity\\{$interval->name}"; self::$intervals[] = $interval->name; 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 0cfb0a0967..15e3eb5221 100644 --- a/app/Support/Cronjobs/UpdateCheckCronjob.php +++ b/app/Support/Cronjobs/UpdateCheckCronjob.php @@ -24,16 +24,18 @@ 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; use Illuminate\Support\Facades\Log; +use Override; class UpdateCheckCronjob extends AbstractCronjob { use UpdateTrait; - #[\Override] + #[Override] public function fire(): void { Log::debug('Now in checkForUpdates()'); @@ -54,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) { @@ -63,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/ExpandedForm.php b/app/Support/ExpandedForm.php index 68e2c07064..e460353ac2 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -27,6 +27,7 @@ use Illuminate\Database\Eloquent\Model; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Form\FormSupport; use Illuminate\Support\Collection; +use Throwable; /** * Class ExpandedForm. @@ -56,7 +57,7 @@ class ExpandedForm // } try { $html = view('form.amount-no-currency', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); $html = 'Could not render amountNoCurrency.'; @@ -91,7 +92,7 @@ class ExpandedForm try { $html = view('form.checkbox', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); $html = 'Could not render checkbox.'; @@ -116,7 +117,7 @@ class ExpandedForm try { $html = view('form.date', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render date(): %s', $e->getMessage())); $html = 'Could not render date.'; @@ -138,7 +139,7 @@ class ExpandedForm try { $html = view('form.file', compact('classes', 'name', 'label', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render file(): %s', $e->getMessage())); $html = 'Could not render file.'; @@ -164,7 +165,7 @@ class ExpandedForm try { $html = view('form.integer', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render integer(): %s', $e->getMessage())); $html = 'Could not render integer.'; @@ -189,7 +190,7 @@ class ExpandedForm try { $html = view('form.location', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render location(): %s', $e->getMessage())); $html = 'Could not render location.'; @@ -242,7 +243,7 @@ class ExpandedForm try { $html = view('form.object_group', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); $html = 'Could not render objectGroup.'; @@ -259,7 +260,7 @@ class ExpandedForm { try { $html = view('form.options', compact('type', 'name'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render optionsList.'; @@ -280,7 +281,7 @@ class ExpandedForm try { $html = view('form.password', compact('classes', 'name', 'label', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render password(): %s', $e->getMessage())); $html = 'Could not render password.'; @@ -301,7 +302,7 @@ class ExpandedForm try { $html = view('form.password', compact('classes', 'value', 'name', 'label', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); $html = 'Could not render passwordWithValue.'; @@ -329,7 +330,7 @@ class ExpandedForm try { $html = view('form.percentage', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render percentage(): %s', $e->getMessage())); $html = 'Could not render percentage.'; @@ -352,7 +353,7 @@ class ExpandedForm try { $html = view('form.static', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render staticText(): %s', $e->getMessage())); $html = 'Could not render staticText.'; @@ -376,7 +377,7 @@ class ExpandedForm try { $html = view('form.text', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render text(): %s', $e->getMessage())); $html = 'Could not render text.'; @@ -405,7 +406,7 @@ class ExpandedForm try { $html = view('form.textarea', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render textarea(): %s', $e->getMessage())); $html = 'Could not render textarea.'; diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index 009fc71390..832a020951 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -30,6 +30,7 @@ use Illuminate\Contracts\Encryption\EncryptException; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; +use Exception; /** * Class FireflyConfig. @@ -53,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) { @@ -88,7 +89,7 @@ class FireflyConfig try { /** @var null|Configuration $config */ $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); - } catch (\Exception|QueryException $e) { + } catch (Exception|QueryException $e) { throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage()), 0, $e); } diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index 348983ed23..19a043c76d 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -28,6 +28,7 @@ use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Throwable; /** * Class AccountForm @@ -58,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); @@ -124,7 +125,7 @@ class AccountForm try { $html = view('form.assetAccountCheckList', compact('classes', 'selected', 'name', 'label', 'options', 'grouped'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); $html = 'Could not render assetAccountCheckList.'; diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index ad0997025a..378375a351 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -28,6 +28,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use Illuminate\Support\Collection; +use Throwable; /** * Class CurrencyForm @@ -92,7 +93,7 @@ class CurrencyForm try { $html = view('form.'.$view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; @@ -161,7 +162,7 @@ class CurrencyForm try { $html = view('form.'.$view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index 4b0417f2be..8240bc45a1 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -28,6 +28,7 @@ use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use Illuminate\Support\MessageBag; +use Throwable; /** * Trait FormSupport @@ -46,7 +47,7 @@ trait FormSupport try { $html = view('form.multi-select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render multi-select(): %s', $e->getMessage())); $html = 'Could not render multi-select.'; } @@ -84,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'; } /** @@ -111,7 +111,7 @@ trait FormSupport } if ($value instanceof Carbon) { - $value = $value->format('Y-m-d'); + return $value->format('Y-m-d'); } return $value; @@ -131,7 +131,7 @@ trait FormSupport try { $html = view('form.select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render select.'; } 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/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 0d995753e2..65fd660211 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -32,6 +32,7 @@ use FireflyIII\Models\Tag; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Throwable; /** * Trait ModelInformation @@ -55,7 +56,7 @@ trait ModelInformation 'count' => 1, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); $result = 'Could not render view. See log files.'; @@ -142,7 +143,7 @@ trait ModelInformation 'triggers' => $triggers, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); app('log')->debug($e->getTraceAsString()); @@ -258,7 +259,7 @@ trait ModelInformation 'triggers' => $triggers, ]; $string = view('rules.partials.trigger', $renderInfo)->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getTriggersForJournal(): %s', $e->getMessage())); app('log')->debug($e->getTraceAsString()); diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index 4bb800469f..4c5f8348c6 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -37,6 +37,7 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Support\Search\OperatorQuerySearch; +use Throwable; /** * Trait RenderPartialViews @@ -68,7 +69,7 @@ trait RenderPartialViews try { $view = view('popup.report.balance-amount', compact('journals', 'budget', 'account'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -91,7 +92,7 @@ trait RenderPartialViews try { $result = view('reports.options.budget', compact('budgets'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; @@ -123,7 +124,7 @@ trait RenderPartialViews try { $view = view('popup.report.budget-spent-amount', compact('journals', 'budget'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -150,7 +151,7 @@ trait RenderPartialViews try { $view = view('popup.report.category-entry', compact('journals', 'category'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -173,7 +174,7 @@ trait RenderPartialViews try { $result = view('reports.options.category', compact('categories'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.options.category: %s', $e->getMessage())); $result = 'Could not render view.'; @@ -215,7 +216,7 @@ trait RenderPartialViews try { $result = view('reports.options.double', compact('set'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; @@ -248,7 +249,7 @@ trait RenderPartialViews try { $view = view('popup.report.expense-entry', compact('journals', 'account'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -284,7 +285,7 @@ trait RenderPartialViews 'count' => $count, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); @@ -339,7 +340,7 @@ trait RenderPartialViews 'triggers' => $triggers, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); @@ -375,7 +376,7 @@ trait RenderPartialViews try { $view = view('popup.report.income-entry', compact('journals', 'account'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -394,7 +395,7 @@ trait RenderPartialViews { try { $result = view('reports.options.no-options')->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.options.no-options: %s', $e->getMessage())); $result = 'Could not render view.'; @@ -417,7 +418,7 @@ trait RenderPartialViews try { $result = view('reports.options.tag', compact('tags'))->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index 96e6edcfac..dd6badda30 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -34,6 +34,9 @@ use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Routing\Route; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Route as RouteFacade; +use Hash; + +use function Safe\parse_url; /** * Trait RequestInformation @@ -46,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'] ?? ''; } @@ -94,7 +97,7 @@ trait RequestInformation $shownDemo = app('preferences')->get($key, false)->data; } if (!is_bool($shownDemo)) { - $shownDemo = true; + return true; } return $shownDemo; @@ -122,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; } /** @@ -146,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(); @@ -169,7 +171,7 @@ trait RequestInformation */ final protected function validatePassword(User $user, string $current, string $new): bool // get request info { - if (!\Hash::check($current, $user->password)) { + if (!Hash::check($current, $user->password)) { throw new ValidationException((string) trans('firefly.invalid_current_password')); } diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index a334161ee0..6b88c3524c 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -28,6 +28,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Support\Search\OperatorQuerySearch; use Illuminate\Http\Request; +use Throwable; /** * Trait RuleManagement @@ -54,7 +55,7 @@ trait RuleManagement 'count' => $index + 1, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->error(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); @@ -99,7 +100,7 @@ trait RuleManagement 'triggers' => $triggers, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); @@ -145,7 +146,7 @@ trait RuleManagement 'triggers' => $triggers, ] )->render(); - } catch (\Throwable $e) { + } catch (Throwable $e) { app('log')->debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); diff --git a/app/Support/JsonApi/Enrichments/AccountEnrichment.php b/app/Support/JsonApi/Enrichments/AccountEnrichment.php index 2de881736e..9318a27293 100644 --- a/app/Support/JsonApi/Enrichments/AccountEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AccountEnrichment.php @@ -39,6 +39,7 @@ use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Override; /** * Class AccountEnrichment @@ -78,7 +79,7 @@ class AccountEnrichment implements EnrichmentInterface // $this->end = null; } - #[\Override] + #[Override] public function enrichSingle(array|Model $model): Account|array { Log::debug(__METHOD__); @@ -88,7 +89,7 @@ class AccountEnrichment implements EnrichmentInterface return $collection->first(); } - #[\Override] + #[Override] /** * Do the actual enrichment. */ diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php index 6e9b516235..9bac754a7c 100644 --- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php +++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php @@ -39,6 +39,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; +use Override; class TransactionGroupEnrichment implements EnrichmentInterface { @@ -64,7 +65,7 @@ class TransactionGroupEnrichment implements EnrichmentInterface $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; } - #[\Override] + #[Override] public function enrichSingle(array|Model $model): array|TransactionGroup { Log::debug(__METHOD__); @@ -78,7 +79,7 @@ class TransactionGroupEnrichment implements EnrichmentInterface throw new FireflyException('Cannot enrich single model.'); } - #[\Override] + #[Override] public function enrich(Collection $collection): Collection { Log::debug(sprintf('Now doing account enrichment for %d transaction group(s)', $collection->count())); 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 c17d7c5193..0b336ed8bc 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -30,6 +30,7 @@ use FireflyIII\Helpers\Fiscal\FiscalHelperInterface; use FireflyIII\Support\Calendar\Calculator; use FireflyIII\Support\Calendar\Periodicity; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class Navigation. @@ -93,7 +94,7 @@ class Navigation return $this->calculator->nextDateByInterval($epoch, $periodicity, $skipInterval); } catch (IntervalException $exception) { Log::warning($exception->getMessage(), ['exception' => $exception]); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { Log::error($exception->getMessage(), ['exception' => $exception]); } @@ -420,7 +421,7 @@ class Navigation $currentEnd->{$function}(); // @phpstan-ignore-line } - if (null !== $maxDate && $currentEnd > $maxDate) { + if ($maxDate instanceof Carbon && $currentEnd > $maxDate) { return clone $maxDate; } @@ -501,7 +502,7 @@ class Navigation if ($diff >= 12.001) { // Log::debug(sprintf('Return Y because %s', $diff)); - $format = 'Y'; + return 'Y'; } return $format; @@ -564,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); } /** @@ -582,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'; } /** @@ -600,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'; } /** @@ -618,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/NullArrayObject.php b/app/Support/NullArrayObject.php index f4a0c7f4fa..a1b6b190de 100644 --- a/app/Support/NullArrayObject.php +++ b/app/Support/NullArrayObject.php @@ -24,10 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Support; +use ArrayObject; + /** * Class NullArrayObject */ -class NullArrayObject extends \ArrayObject +class NullArrayObject extends ArrayObject { /** * NullArrayObject constructor. 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 519258c1fa..095162de47 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -48,6 +48,8 @@ use FireflyIII\Support\Search\QueryParser\StringNode; use FireflyIII\User; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; +use LogicException; +use TypeError; /** * Class OperatorQuerySearch @@ -143,7 +145,7 @@ class OperatorQuerySearch implements SearchInterface try { $parsedQuery = $parser->parse($query); - } catch (\LogicException|\TypeError $e) { + } catch (LogicException|TypeError $e) { app('log')->error($e->getMessage()); app('log')->error(sprintf('Could not parse search: "%s".', $query)); @@ -717,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(); } @@ -728,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(); } @@ -739,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(); } @@ -750,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(); } @@ -2107,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 aa802e0df0..a402013e48 100644 --- a/app/Support/Search/QueryParser/GdbotsQueryParser.php +++ b/app/Support/Search/QueryParser/GdbotsQueryParser.php @@ -30,6 +30,10 @@ use Gdbots\QueryParser\Enum\BoolOperator; use Gdbots\QueryParser\Node as GdbotsNode; use Gdbots\QueryParser\QueryParser as BaseQueryParser; use Illuminate\Support\Facades\Log; +use LogicException; +use TypeError; + +use function Safe\fwrite; class GdbotsQueryParser implements QueryParserInterface { @@ -53,8 +57,8 @@ class GdbotsQueryParser implements QueryParserInterface ); return new NodeGroup($nodes); - } catch (\LogicException|\TypeError $e) { - \Safe\fwrite(STDERR, "Setting up GdbotsQueryParserTest\n"); + } catch (LogicException|TypeError $e) { + fwrite(STDERR, "Setting up GdbotsQueryParserTest\n"); app('log')->error($e->getMessage()); app('log')->error(sprintf('Could not parse search: "%s".', $query)); 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/Search/QueryParser/QueryParserInterface.php b/app/Support/Search/QueryParser/QueryParserInterface.php index 158452ff98..809f7b02c1 100644 --- a/app/Support/Search/QueryParser/QueryParserInterface.php +++ b/app/Support/Search/QueryParser/QueryParserInterface.php @@ -25,11 +25,14 @@ declare(strict_types=1); namespace FireflyIII\Support\Search\QueryParser; +use LogicException; +use TypeError; + interface QueryParserInterface { /** - * @throws \LogicException - * @throws \TypeError + * @throws LogicException + * @throws TypeError */ public function parse(string $query): NodeGroup; } diff --git a/app/Support/Steam.php b/app/Support/Steam.php index b6da6a44dd..033081a6ed 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -34,6 +34,11 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; +use Exception; +use ValueError; + +use function Safe\preg_replace; +use function Safe\parse_url; /** * Class Steam. @@ -95,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]); } @@ -184,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); } @@ -221,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)); @@ -339,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. @@ -466,7 +471,7 @@ class Steam try { $hostName = gethostbyaddr($ipAddress); - } catch (\Exception $e) { + } catch (Exception $e) { app('log')->error($e->getMessage()); $hostName = $ipAddress; } @@ -514,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; @@ -566,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; @@ -576,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; @@ -590,7 +595,7 @@ class Steam $amount = $this->floatalize($amount); if (1 === bccomp($amount, '0')) { - $amount = bcmul($amount, '-1'); + return bcmul($amount, '-1'); } return $amount; @@ -673,7 +678,7 @@ class Steam if (-1 === bccomp($amount, '0')) { $amount = bcmul($amount, '-1'); } - } catch (\ValueError $e) { + } catch (ValueError $e) { Log::error(sprintf('ValueError in Steam::positive("%s"): %s', $amount, $e->getMessage())); Log::error($e->getTraceAsString()); 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/AmountFormat.php b/app/Support/Twig/AmountFormat.php index 4cf3ac7b07..70581d32a9 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -31,13 +31,14 @@ use Illuminate\Support\Facades\Log; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; use Twig\TwigFunction; +use Override; /** * Contains all amount formatting routines. */ class AmountFormat extends AbstractExtension { - #[\Override] + #[Override] public function getFilters(): array { return [ @@ -72,7 +73,7 @@ class AmountFormat extends AbstractExtension ); } - #[\Override] + #[Override] public function getFunctions(): array { return [ diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 6e369e4086..61cbd5eba4 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -37,13 +37,16 @@ use Illuminate\Support\Facades\Route; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; use Twig\TwigFunction; +use Override; + +use function Safe\parse_url; /** * Class TwigSupport. */ class General extends AbstractExtension { - #[\Override] + #[Override] public function getFilters(): array { return [ @@ -63,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'; } @@ -179,15 +182,15 @@ 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)); } ); } - #[\Override] + #[Override] public function getFunctions(): array { return [ diff --git a/app/Support/Twig/Rule.php b/app/Support/Twig/Rule.php index 45e763da1b..c833745d40 100644 --- a/app/Support/Twig/Rule.php +++ b/app/Support/Twig/Rule.php @@ -25,13 +25,15 @@ namespace FireflyIII\Support\Twig; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; +use Config; +use Override; /** * Class Rule. */ class Rule extends AbstractExtension { - #[\Override] + #[Override] public function getFunctions(): array { return [ @@ -79,7 +81,7 @@ class Rule extends AbstractExtension 'allRuleActions', static function () { // array of valid values for actions - $ruleActions = array_keys(\Config::get('firefly.rule-actions')); + $ruleActions = array_keys(Config::get('firefly.rule-actions')); $possibleActions = []; foreach ($ruleActions as $key) { $possibleActions[$key] = (string) trans('firefly.rule_action_'.$key.'_choice'); diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index bc338d4b22..81cf8db231 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -33,13 +33,16 @@ use FireflyIII\Models\TransactionJournalMeta; use Illuminate\Support\Facades\DB; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; +use Override; + +use function Safe\json_decode; /** * Class TransactionGroupTwig */ class TransactionGroupTwig extends AbstractExtension { - #[\Override] + #[Override] public function getFunctions(): array { return [ @@ -90,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; @@ -110,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; @@ -133,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; @@ -181,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; @@ -216,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; @@ -255,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)); } ); } @@ -276,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/Support/Twig/Translation.php b/app/Support/Twig/Translation.php index 7167ebb3a4..bb19890ff9 100644 --- a/app/Support/Twig/Translation.php +++ b/app/Support/Twig/Translation.php @@ -26,13 +26,14 @@ namespace FireflyIII\Support\Twig; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; use Twig\TwigFunction; +use Override; /** * Class Budget. */ class Translation extends AbstractExtension { - #[\Override] + #[Override] public function getFilters(): array { return [ @@ -44,7 +45,7 @@ class Translation extends AbstractExtension ]; } - #[\Override] + #[Override] public function getFunctions(): array { return [ 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 e23bd8506b..e9f3b12128 100644 --- a/app/Transformers/V2/TransactionGroupTransformer.php +++ b/app/Transformers/V2/TransactionGroupTransformer.php @@ -40,6 +40,7 @@ use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\NullArrayObject; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use stdClass; /** * Class TransactionGroupTransformer @@ -169,7 +170,7 @@ class TransactionGroupTransformer extends AbstractTransformer ->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag']) ; - /** @var \stdClass $tag */ + /** @var stdClass $tag */ foreach ($tags as $tag) { $id = (int) $tag->transaction_journal_id; $this->journals[$id]['tags'][] = $tag->tag; @@ -464,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; } @@ -475,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; } @@ -484,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 5271582bbb..0839a7c437 100644 --- a/app/Transformers/WebhookMessageTransformer.php +++ b/app/Transformers/WebhookMessageTransformer.php @@ -25,6 +25,9 @@ declare(strict_types=1); namespace FireflyIII\Transformers; use FireflyIII\Models\WebhookMessage; +use JsonException; + +use function Safe\json_encode; /** * Class WebhookMessageTransformer @@ -39,8 +42,8 @@ class WebhookMessageTransformer extends AbstractTransformer $json = '{}'; try { - $json = \Safe\json_encode($message->message, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + $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/User.php b/app/User.php index f6bc724e5f..46a0041ec3 100644 --- a/app/User.php +++ b/app/User.php @@ -66,6 +66,7 @@ use Illuminate\Support\Str; use Laravel\Passport\HasApiTokens; use NotificationChannels\Pushover\PushoverReceiver; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Exception; class User extends Authenticatable { @@ -166,7 +167,7 @@ class User extends Authenticatable /** * Generates access token. * - * @throws \Exception + * @throws Exception */ public function generateAccessToken(): string { 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 0ea1c687fd..c24fcd54ea 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -45,6 +45,12 @@ use PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException; use PragmaRX\Google2FA\Exceptions\InvalidCharactersException; use PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException; use PragmaRX\Google2FALaravel\Facade; +use Config; +use ValueError; + +use function Safe\preg_match; +use function Safe\iconv; +use function Safe\json_encode; /** * Class FireflyValidator. @@ -111,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; } @@ -201,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']; @@ -216,7 +222,7 @@ class FireflyValidator extends Validator try { $checksum = bcmod($iban, '97'); - } catch (\ValueError $e) { // @phpstan-ignore-line + } catch (ValueError $e) { // @phpstan-ignore-line $message = sprintf('Could not validate IBAN check value "%s" (IBAN "%s")', $iban, $value); Log::error($message); Log::error($e->getTraceAsString()); @@ -537,7 +543,7 @@ class FireflyValidator extends Validator private function validateByAccountTypeString(string $value, array $parameters, string $type): bool { /** @var null|array $search */ - $search = \Config::get('firefly.accountTypeByIdentifier.'.$type); + $search = Config::get('firefly.accountTypeByIdentifier.'.$type); if (null === $search) { return false; @@ -635,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 7c87c20b32..52b829203e 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -28,6 +28,7 @@ use Carbon\Carbon; use FireflyIII\Models\Recurrence; use FireflyIII\Models\RecurrenceTransaction; use Illuminate\Validation\Validator; +use InvalidArgumentException; /** * Trait RecurrenceValidation @@ -165,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')); } @@ -294,7 +295,7 @@ trait RecurrenceValidation { try { Carbon::createFromFormat('Y-m-d', $moment); - } catch (\InvalidArgumentException $e) { // @phpstan-ignore-line + } catch (InvalidArgumentException $e) { // @phpstan-ignore-line app('log')->debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } 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 diff --git a/bootstrap/app.php b/bootstrap/app.php index e5fc51d13d..9c9c5c85b1 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -21,6 +21,11 @@ declare(strict_types=1); +use Illuminate\Foundation\Application; +use Illuminate\Contracts\Http\Kernel; +use Illuminate\Contracts\Debug\ExceptionHandler; +use FireflyIII\Exceptions\Handler; + /* |-------------------------------------------------------------------------- | Create The Application @@ -45,7 +50,7 @@ if (!function_exists('envNonEmpty')) { { $result = env($key, $default); // @phpstan-ignore-line if ('' === $result) { - $result = $default; + return $default; } return $result; @@ -65,7 +70,7 @@ if (!function_exists('stringIsEqual')) { } } -$app = new Illuminate\Foundation\Application( +$app = new Application( (string)realpath(__DIR__ . '/../') ); @@ -81,7 +86,7 @@ $app = new Illuminate\Foundation\Application( */ $app->singleton( - Illuminate\Contracts\Http\Kernel::class, + Kernel::class, FireflyIII\Http\Kernel::class ); @@ -91,8 +96,8 @@ $app->singleton( ); $app->singleton( - Illuminate\Contracts\Debug\ExceptionHandler::class, - FireflyIII\Exceptions\Handler::class + ExceptionHandler::class, + Handler::class ); /* diff --git a/database/seeders/AccountTypeSeeder.php b/database/seeders/AccountTypeSeeder.php index e52e06136c..0b9dda0723 100644 --- a/database/seeders/AccountTypeSeeder.php +++ b/database/seeders/AccountTypeSeeder.php @@ -26,6 +26,7 @@ namespace Database\Seeders; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\AccountType; use Illuminate\Database\Seeder; +use PDOException; /** * Class AccountTypeSeeder. @@ -53,7 +54,7 @@ class AccountTypeSeeder extends Seeder if (null === AccountType::where('type', $type)->first()) { try { AccountType::create(['type' => $type]); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/database/seeders/LinkTypeSeeder.php b/database/seeders/LinkTypeSeeder.php index 48fc038cf6..7f2aa36bbd 100644 --- a/database/seeders/LinkTypeSeeder.php +++ b/database/seeders/LinkTypeSeeder.php @@ -25,6 +25,7 @@ namespace Database\Seeders; use FireflyIII\Models\LinkType; use Illuminate\Database\Seeder; +use PDOException; /** * Class LinkTypeSeeder. @@ -63,7 +64,7 @@ class LinkTypeSeeder extends Seeder if (null === LinkType::where('name', $type['name'])->first()) { try { LinkType::create($type); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/database/seeders/PermissionSeeder.php b/database/seeders/PermissionSeeder.php index 7e3234af11..5c66b3af29 100644 --- a/database/seeders/PermissionSeeder.php +++ b/database/seeders/PermissionSeeder.php @@ -25,6 +25,7 @@ namespace Database\Seeders; use FireflyIII\Models\Role; use Illuminate\Database\Seeder; +use PDOException; /** * Class PermissionSeeder. @@ -49,7 +50,7 @@ class PermissionSeeder extends Seeder if (null === Role::where('name', $role['name'])->first()) { try { Role::create($role); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/database/seeders/TransactionCurrencySeeder.php b/database/seeders/TransactionCurrencySeeder.php index d21be80335..ea8adf0e78 100644 --- a/database/seeders/TransactionCurrencySeeder.php +++ b/database/seeders/TransactionCurrencySeeder.php @@ -25,6 +25,7 @@ namespace Database\Seeders; use FireflyIII\Models\TransactionCurrency; use Illuminate\Database\Seeder; +use PDOException; /** * Class TransactionCurrencySeeder. @@ -82,7 +83,7 @@ class TransactionCurrencySeeder extends Seeder if (null === TransactionCurrency::where('code', $currency['code'])->first()) { try { TransactionCurrency::create($currency); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/database/seeders/TransactionTypeSeeder.php b/database/seeders/TransactionTypeSeeder.php index 401f993c2e..2a7d813164 100644 --- a/database/seeders/TransactionTypeSeeder.php +++ b/database/seeders/TransactionTypeSeeder.php @@ -26,6 +26,7 @@ namespace Database\Seeders; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\TransactionType; use Illuminate\Database\Seeder; +use PDOException; /** * Class TransactionTypeSeeder. @@ -48,7 +49,7 @@ class TransactionTypeSeeder extends Seeder if (null === TransactionType::where('type', $type)->first()) { try { TransactionType::create(['type' => $type]); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/database/seeders/UserRoleSeeder.php b/database/seeders/UserRoleSeeder.php index bc117c9e19..c779b91812 100644 --- a/database/seeders/UserRoleSeeder.php +++ b/database/seeders/UserRoleSeeder.php @@ -27,6 +27,7 @@ namespace Database\Seeders; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Models\UserRole; use Illuminate\Database\Seeder; +use PDOException; /** * Class UserRoleSeeder @@ -48,7 +49,7 @@ class UserRoleSeeder extends Seeder if (null === UserRole::where('title', $role)->first()) { try { UserRole::create(['title' => $role]); - } catch (\PDOException $e) { + } catch (PDOException $e) { // @ignoreException } } diff --git a/public/index.php b/public/index.php index 22c05fd592..e1efbd4614 100644 --- a/public/index.php +++ b/public/index.php @@ -1,4 +1,9 @@ make(Illuminate\Contracts\Http\Kernel::class); +$kernel = $app->make(Kernel::class); $response = $kernel->handle( - $request = Illuminate\Http\Request::capture() + $request = Request::capture() ); $response->send(); diff --git a/resources/views/list/groups.twig b/resources/views/list/groups.twig index 832b55c6a9..0ef4a4899b 100644 --- a/resources/views/list/groups.twig +++ b/resources/views/list/groups.twig @@ -263,7 +263,7 @@ {% if currency.id == transaction.currency_id %} {{ formatAmountBySymbol(transaction.destination_balance_after, transaction.currency_symbol, transaction.currency_decimal_places) }} {% endif %} - {% if currency.id == transaction.foreign_currency_id %} + {% if currency.id == transaction.foreign_currency_id and null != transaction.destination_balance_after %} {{ formatAmountBySymbol(transaction.destination_balance_after, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }} {% endif %} diff --git a/routes/breadcrumbs.php b/routes/breadcrumbs.php index 2ea63de4d2..0519d8eacd 100644 --- a/routes/breadcrumbs.php +++ b/routes/breadcrumbs.php @@ -54,12 +54,11 @@ if (!function_exists('limitStringLength')) { { $maxChars = 75; $length = strlen($string); - $result = $string; if ($length > $maxChars) { - $result = substr_replace($string, ' ... ', (int)($maxChars / 2), $length - $maxChars); + return substr_replace($string, ' ... ', (int)($maxChars / 2), $length - $maxChars); } - return $result; + return $string; } } @@ -109,7 +108,7 @@ Breadcrumbs::for( $breadcrumbs->parent('accounts.index', $what); $breadcrumbs->push(limitStringLength($account->name), route('accounts.show.all', [$account->id])); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $title = trans( 'firefly.between_dates_breadcrumb', [ @@ -451,7 +450,7 @@ Breadcrumbs::for( static function (Generator $breadcrumbs, ?Carbon $start = null, ?Carbon $end = null): void { $breadcrumbs->parent('budgets.index'); $breadcrumbs->push(trans('firefly.journals_without_budget'), route('budgets.no-budget')); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $title = trans( 'firefly.between_dates_breadcrumb', [ @@ -539,7 +538,7 @@ Breadcrumbs::for( static function (Generator $breadcrumbs, Category $category, ?Carbon $start = null, ?Carbon $end = null): void { $breadcrumbs->parent('categories.index'); $breadcrumbs->push(limitStringLength($category->name), route('categories.show', [$category->id])); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $title = trans( 'firefly.between_dates_breadcrumb', [ @@ -566,7 +565,7 @@ Breadcrumbs::for( static function (Generator $breadcrumbs, ?Carbon $start = null, ?Carbon $end = null): void { $breadcrumbs->parent('categories.index'); $breadcrumbs->push(trans('firefly.journals_without_category'), route('categories.no-category')); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $title = trans( 'firefly.between_dates_breadcrumb', [ @@ -965,10 +964,10 @@ Breadcrumbs::for( 'rules.create', static function (Generator $breadcrumbs, ?RuleGroup $ruleGroup = null): void { $breadcrumbs->parent('rules.index'); - if (null === $ruleGroup) { + if (!$ruleGroup instanceof RuleGroup) { $breadcrumbs->push(trans('firefly.make_new_rule_no_group'), route('rules.create')); } - if (null !== $ruleGroup) { + if ($ruleGroup instanceof RuleGroup) { $breadcrumbs->push(trans('firefly.make_new_rule', ['title' => $ruleGroup->title]), route('rules.create', [$ruleGroup])); } } @@ -1096,7 +1095,7 @@ Breadcrumbs::for( $breadcrumbs->parent('tags.index'); $breadcrumbs->push($tag->tag, route('tags.show', [$tag->id, $start, $end])); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { $title = trans( 'firefly.between_dates_breadcrumb', [ @@ -1127,7 +1126,7 @@ Breadcrumbs::for( $breadcrumbs->parent('home'); $breadcrumbs->push(trans('breadcrumbs.'.$what.'_list'), route('transactions.index', [$what])); - if (null !== $start && null !== $end) { + if ($start instanceof Carbon && $end instanceof Carbon) { // add date range: $title = trans( 'firefly.between_dates_breadcrumb', diff --git a/tests/integration/Api/About/AboutControllerTest.php b/tests/integration/Api/About/AboutControllerTest.php index 77f0402c87..f12179e6a1 100644 --- a/tests/integration/Api/About/AboutControllerTest.php +++ b/tests/integration/Api/About/AboutControllerTest.php @@ -27,6 +27,7 @@ namespace Tests\integration\Api\About; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Testing\Fluent\AssertableJson; use Tests\integration\TestCase; +use Override; /** * Class AboutControllerTest @@ -40,7 +41,7 @@ final class AboutControllerTest extends TestCase use RefreshDatabase; private $user; - #[\Override] + #[Override] protected function setUp(): void { parent::setUp(); diff --git a/tests/integration/Api/Autocomplete/BillControllerTest.php b/tests/integration/Api/Autocomplete/BillControllerTest.php index 41ca56d6ef..f94daa714a 100644 --- a/tests/integration/Api/Autocomplete/BillControllerTest.php +++ b/tests/integration/Api/Autocomplete/BillControllerTest.php @@ -29,6 +29,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; use FireflyIII\User; use FireflyIII\Models\UserGroup; +use Override; /** * Class BillControllerTest @@ -44,7 +45,7 @@ final class BillControllerTest extends TestCase */ use RefreshDatabase; - #[\Override] + #[Override] protected function createAuthenticatedUser(): User { $userGroup = UserGroup::create(['title' => 'Test Group']); diff --git a/tests/integration/Api/Autocomplete/BudgetControllerTest.php b/tests/integration/Api/Autocomplete/BudgetControllerTest.php index fe247ddd5b..8e27714807 100644 --- a/tests/integration/Api/Autocomplete/BudgetControllerTest.php +++ b/tests/integration/Api/Autocomplete/BudgetControllerTest.php @@ -29,6 +29,7 @@ use FireflyIII\Models\UserGroup; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; use FireflyIII\User; +use Override; /** * Class BudgetControllerTest @@ -44,7 +45,7 @@ final class BudgetControllerTest extends TestCase */ use RefreshDatabase; - #[\Override] + #[Override] protected function createAuthenticatedUser(): User { $userGroup = UserGroup::create(['title' => 'Test Group']); diff --git a/tests/integration/Api/Autocomplete/CategoryControllerTest.php b/tests/integration/Api/Autocomplete/CategoryControllerTest.php index 66eccc7bf7..492b103669 100644 --- a/tests/integration/Api/Autocomplete/CategoryControllerTest.php +++ b/tests/integration/Api/Autocomplete/CategoryControllerTest.php @@ -29,6 +29,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; use FireflyIII\User; use FireflyIII\Models\UserGroup; +use Override; /** * Class CategoryControllerTest @@ -44,7 +45,7 @@ final class CategoryControllerTest extends TestCase */ use RefreshDatabase; - #[\Override] + #[Override] protected function createAuthenticatedUser(): User { $userGroup = UserGroup::create(['title' => 'Test Group']); diff --git a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php index 1122503bb9..80f92f7079 100644 --- a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php +++ b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php @@ -29,6 +29,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; use FireflyIII\User; use FireflyIII\Models\UserGroup; +use Override; /** * Class CurrencyControllerTest @@ -44,7 +45,7 @@ final class CurrencyControllerTest extends TestCase */ use RefreshDatabase; - #[\Override] + #[Override] protected function createAuthenticatedUser(): User { $userGroup = UserGroup::create(['title' => 'Test Group']); diff --git a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php index 74ad04420f..051492f6bc 100644 --- a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php +++ b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php @@ -29,6 +29,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; use FireflyIII\User; use FireflyIII\Models\UserGroup; +use Override; /** * Class ObjectGroupControllerTest @@ -44,7 +45,7 @@ final class ObjectGroupControllerTest extends TestCase */ use RefreshDatabase; - #[\Override] + #[Override] protected function createAuthenticatedUser(): User { $userGroup = UserGroup::create(['title' => 'Test Group']); diff --git a/tests/integration/Support/Models/BillDateCalculatorTest.php b/tests/integration/Support/Models/BillDateCalculatorTest.php index c5dba4eed9..1164fce606 100644 --- a/tests/integration/Support/Models/BillDateCalculatorTest.php +++ b/tests/integration/Support/Models/BillDateCalculatorTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\integration\Support\Models; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Models\BillDateCalculator; use PHPUnit\Framework\Attributes\DataProvider; @@ -40,6 +42,7 @@ final class BillDateCalculatorTest extends TestCase { private BillDateCalculator $calculator; + #[Override] protected function setUp(): void { parent::setUp(); @@ -56,25 +59,25 @@ final class BillDateCalculatorTest extends TestCase self::assertSame($expected, $result); } - public static function provideDates(): iterable + public static function provideDates(): Iterator { // Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, ?Carbon $lastPaid - return [ - // basic monthly bill.x - '1Ma' => ['earliest' => Carbon::parse('2023-11-01'), 'latest' => Carbon::parse('2023-11-30'), 'billStart' => Carbon::parse('2023-01-01'), 'period' => 'monthly', 'skip' => 0, 'lastPaid' => null, 'expected' => ['2023-11-01']], - // already paid on the first, expect it next month. - '1Mb' => ['earliest' => Carbon::parse('2023-11-01'), 'latest' => Carbon::parse('2023-11-30'), 'billStart' => Carbon::parse('2023-01-01'), 'period' => 'monthly', 'skip' => 0, 'lastPaid' => Carbon::parse('2023-11-01'), 'expected' => ['2023-12-01']], - // already paid on the 12th, expect it next month. - '1Mc' => ['earliest' => Carbon::parse('2023-11-01'), 'latest' => Carbon::parse('2023-11-30'), 'billStart' => Carbon::parse('2023-01-01'), 'period' => 'monthly', 'skip' => 0, 'lastPaid' => Carbon::parse('2023-11-12'), 'expected' => ['2023-12-01']], + // basic monthly bill.x + yield '1Ma' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, null, ['2023-11-01']]; - // every month, start on 2024-01-30, view is quarterly - '1Md' => ['earliest' => Carbon::parse('2023-01-01'), 'latest' => Carbon::parse('2023-03-31'), 'billStart' => Carbon::parse('2023-01-29'), 'period' => 'monthly', 'skip' => 0, 'lastPaid' => null, 'expected' => ['2023-01-29', '2023-02-28', '2023-03-29']], + // already paid on the first, expect it next month. + yield '1Mb' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, Carbon::parse('2023-11-01'), ['2023-12-01']]; - // every month, start on 2024-01-30, view is quarterly - '1Me' => ['earliest' => Carbon::parse('2024-01-01'), 'latest' => Carbon::parse('2024-03-31'), 'billStart' => Carbon::parse('2023-01-30'), 'period' => 'monthly', 'skip' => 0, 'lastPaid' => null, 'expected' => ['2024-01-30', '2024-02-29', '2024-03-30']], + // already paid on the 12th, expect it next month. + yield '1Mc' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, Carbon::parse('2023-11-12'), ['2023-12-01']]; - // yearly not due this month. Should jump to next year. - '1Ya' => ['earliest' => Carbon::parse('2023-11-01'), 'latest' => Carbon::parse('2023-11-30'), 'billStart' => Carbon::parse('2021-05-01'), 'period' => 'yearly', 'skip' => 0, 'lastPaid' => Carbon::parse('2023-05-02'), 'expected' => ['2024-05-01']], - ]; + // every month, start on 2024-01-30, view is quarterly + yield '1Md' => [Carbon::parse('2023-01-01'), Carbon::parse('2023-03-31'), Carbon::parse('2023-01-29'), 'monthly', 0, null, ['2023-01-29', '2023-02-28', '2023-03-29']]; + + // every month, start on 2024-01-30, view is quarterly + yield '1Me' => [Carbon::parse('2024-01-01'), Carbon::parse('2024-03-31'), Carbon::parse('2023-01-30'), 'monthly', 0, null, ['2024-01-30', '2024-02-29', '2024-03-30']]; + + // yearly not due this month. Should jump to next year. + yield '1Ya' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2021-05-01'), 'yearly', 0, Carbon::parse('2023-05-02'), ['2024-05-01']]; } } diff --git a/tests/unit/Support/Calendar/CalculatorProvider.php b/tests/unit/Support/Calendar/CalculatorProvider.php index 839f422957..4133f435ed 100644 --- a/tests/unit/Support/Calendar/CalculatorProvider.php +++ b/tests/unit/Support/Calendar/CalculatorProvider.php @@ -27,6 +27,7 @@ namespace Tests\unit\Support\Calendar; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use Tests\unit\Support\Calendar\Periodicity\IntervalProvider; +use Generator; readonly class CalculatorProvider { @@ -37,7 +38,7 @@ readonly class CalculatorProvider $this->label = "{$this->periodicity->name} {$this->intervalProvider->label}"; } - public static function providePeriodicityWithSkippedIntervals(): \Generator + public static function providePeriodicityWithSkippedIntervals(): Generator { $intervals = [ self::from(Periodicity::Daily, new IntervalProvider(Carbon::now(), Carbon::now()->addDays(2)), 1), diff --git a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php index 0c17381cad..b667107a3c 100644 --- a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Bimonthly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class BimonthlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Bimonthly(); + return new Bimonthly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/DailyTest.php b/tests/unit/Support/Calendar/Periodicity/DailyTest.php index 697b16d736..1c5dd1560c 100644 --- a/tests/unit/Support/Calendar/Periodicity/DailyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/DailyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Daily; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class DailyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Daily(); + return new Daily(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php index 8f0e2824ce..fdb8eac236 100644 --- a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Fortnightly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class FortnightlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Fortnightly(); + return new Fortnightly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php index acb1facfc0..f71779ce59 100644 --- a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\HalfYearly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class HalfYearlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\HalfYearly(); + return new HalfYearly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php index 56ce40f45e..afe440e976 100644 --- a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Monthly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class MonthlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Monthly(); + return new Monthly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php index defe22c283..3e73794f24 100644 --- a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Quarterly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class QuarterlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Quarterly(); + return new Quarterly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php b/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php index 093abce06a..f347d11222 100644 --- a/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Weekly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class WeeklyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Weekly(); + return new Weekly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php index 4b255d4d7c..27fbc1c56e 100644 --- a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Yearly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Calendar\Periodicity\Interval; @@ -42,7 +43,7 @@ final class YearlyTest extends IntervalTestCase { public static function factory(): Interval { - return new Periodicity\Yearly(); + return new Yearly(); } public static function provideIntervals(): array diff --git a/tests/unit/Support/NavigationAddPeriodTest.php b/tests/unit/Support/NavigationAddPeriodTest.php index 1920c16a6a..e492584c50 100644 --- a/tests/unit/Support/NavigationAddPeriodTest.php +++ b/tests/unit/Support/NavigationAddPeriodTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Navigation; @@ -43,6 +45,7 @@ final class NavigationAddPeriodTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -108,30 +111,47 @@ final class NavigationAddPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function providePeriods(): iterable + public static function providePeriods(): Iterator { - return [ - '1D' => ['frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::tomorrow()], - 'daily' => ['frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::tomorrow()], - '1W' => ['frequency' => '1W', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(1)], - 'weekly' => ['frequency' => 'weekly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(1)], - 'week' => ['frequency' => 'week', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(1)], - '3M' => ['frequency' => '3M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - 'quarter' => ['frequency' => 'quarter', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - 'quarterly' => ['frequency' => 'quarterly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - '6M' => ['frequency' => '6M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'half-year' => ['frequency' => 'half-year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'year' => ['frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - 'yearly' => ['frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - '1Y' => ['frequency' => '1Y', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - 'last7' => ['frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(7)], - 'last30' => ['frequency' => 'last30', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(1)], - 'last90' => ['frequency' => 'last90', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - 'last365' => ['frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - 'MTD' => ['frequency' => 'MTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(1)], - 'QTD' => ['frequency' => 'QTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - 'YTD' => ['frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - ]; + yield '1D' => ['1D', Carbon::now(), Carbon::tomorrow()]; + + yield 'daily' => ['daily', Carbon::now(), Carbon::tomorrow()]; + + yield '1W' => ['1W', Carbon::now(), Carbon::now()->addWeeks(1)]; + + yield 'weekly' => ['weekly', Carbon::now(), Carbon::now()->addWeeks(1)]; + + yield 'week' => ['week', Carbon::now(), Carbon::now()->addWeeks(1)]; + + yield '3M' => ['3M', Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield 'quarter' => ['quarter', Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield 'quarterly' => ['quarterly', Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield '6M' => ['6M', Carbon::now(), Carbon::now()->addMonthsNoOverflow(6)]; + + yield 'half-year' => ['half-year', Carbon::now(), Carbon::now()->addMonthsNoOverflow(6)]; + + yield 'year' => ['year', Carbon::now(), Carbon::now()->addYears(1)]; + + yield 'yearly' => ['yearly', Carbon::now(), Carbon::now()->addYears(1)]; + + yield '1Y' => ['1Y', Carbon::now(), Carbon::now()->addYears(1)]; + + yield 'last7' => ['last7', Carbon::now(), Carbon::now()->addDays(7)]; + + yield 'last30' => ['last30', Carbon::now(), Carbon::now()->addMonthsNoOverflow(1)]; + + yield 'last90' => ['last90', Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield 'last365' => ['last365', Carbon::now(), Carbon::now()->addYears(1)]; + + yield 'MTD' => ['MTD', Carbon::now(), Carbon::now()->addMonthsNoOverflow(1)]; + + yield 'QTD' => ['QTD', Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield 'YTD' => ['YTD', Carbon::now(), Carbon::now()->addYears(1)]; } #[DataProvider('provideFrequencies')] @@ -141,32 +161,51 @@ final class NavigationAddPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function provideFrequencies(): iterable + public static function provideFrequencies(): Iterator { - return [ - Periodicity::Daily->name => ['periodicity' => Periodicity::Daily, 'from' => Carbon::now(), 'expected' => Carbon::tomorrow()], - Periodicity::Weekly->name => ['periodicity' => Periodicity::Weekly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(1)], - Periodicity::Fortnightly->name => ['periodicity' => Periodicity::Fortnightly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], - Periodicity::Monthly->name => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(1)], - '2019-01-01 to 2019-02-01' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2019-01-01'), 'expected' => Carbon::parse('2019-02-01')], - '2019-01-29 to 2019-02-28' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2019-01-29'), 'expected' => Carbon::parse('2019-02-28')], - '2019-01-30 to 2019-02-28' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2019-01-30'), 'expected' => Carbon::parse('2019-02-28')], - '2019-01-31 to 2019-02-28' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-02-28')], - '2023-03-31 to 2023-04-30' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2023-03-31'), 'expected' => Carbon::parse('2023-04-30')], - '2023-05-31 to 2023-06-30' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2023-05-31'), 'expected' => Carbon::parse('2023-06-30')], - '2023-08-31 to 2023-09-30' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2023-08-31'), 'expected' => Carbon::parse('2023-09-30')], - '2023-10-31 to 2023-11-30' => ['periodicity' => Periodicity::Monthly, 'from' => Carbon::parse('2023-10-31'), 'expected' => Carbon::parse('2023-11-30')], - Periodicity::Quarterly->name => ['periodicity' => Periodicity::Quarterly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(3)], - '2019-01-29 to 2020-04-29' => ['periodicity' => Periodicity::Quarterly, 'from' => Carbon::parse('2019-01-29'), 'expected' => Carbon::parse('2019-04-29')], - '2019-01-30 to 2020-04-30' => ['periodicity' => Periodicity::Quarterly, 'from' => Carbon::parse('2019-01-30'), 'expected' => Carbon::parse('2019-04-30')], - '2019-01-31 to 2020-04-30' => ['periodicity' => Periodicity::Quarterly, 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-04-30')], - Periodicity::HalfYearly->name => ['periodicity' => Periodicity::HalfYearly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - '2019-01-31 to 2020-07-29' => ['periodicity' => Periodicity::HalfYearly, 'from' => Carbon::parse('2019-01-29'), 'expected' => Carbon::parse('2019-07-29')], - '2019-01-31 to 2020-07-30' => ['periodicity' => Periodicity::HalfYearly, 'from' => Carbon::parse('2019-01-30'), 'expected' => Carbon::parse('2019-07-30')], - '2019-01-31 to 2020-07-31' => ['periodicity' => Periodicity::HalfYearly, 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-07-31')], - Periodicity::Yearly->name => ['periodicity' => Periodicity::Yearly, 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(1)], - '2020-02-29 to 2021-02-28' => ['periodicity' => Periodicity::Yearly, 'from' => Carbon::parse('2020-02-29'), 'expected' => Carbon::parse('2021-02-28')], - ]; + yield Periodicity::Daily->name => [Periodicity::Daily, Carbon::now(), Carbon::tomorrow()]; + + yield Periodicity::Weekly->name => [Periodicity::Weekly, Carbon::now(), Carbon::now()->addWeeks(1)]; + + yield Periodicity::Fortnightly->name => [Periodicity::Fortnightly, Carbon::now(), Carbon::now()->addWeeks(2)]; + + yield Periodicity::Monthly->name => [Periodicity::Monthly, Carbon::now(), Carbon::now()->addMonthsNoOverflow(1)]; + + yield '2019-01-01 to 2019-02-01' => [Periodicity::Monthly, Carbon::parse('2019-01-01'), Carbon::parse('2019-02-01')]; + + yield '2019-01-29 to 2019-02-28' => [Periodicity::Monthly, Carbon::parse('2019-01-29'), Carbon::parse('2019-02-28')]; + + yield '2019-01-30 to 2019-02-28' => [Periodicity::Monthly, Carbon::parse('2019-01-30'), Carbon::parse('2019-02-28')]; + + yield '2019-01-31 to 2019-02-28' => [Periodicity::Monthly, Carbon::parse('2019-01-31'), Carbon::parse('2019-02-28')]; + + yield '2023-03-31 to 2023-04-30' => [Periodicity::Monthly, Carbon::parse('2023-03-31'), Carbon::parse('2023-04-30')]; + + yield '2023-05-31 to 2023-06-30' => [Periodicity::Monthly, Carbon::parse('2023-05-31'), Carbon::parse('2023-06-30')]; + + yield '2023-08-31 to 2023-09-30' => [Periodicity::Monthly, Carbon::parse('2023-08-31'), Carbon::parse('2023-09-30')]; + + yield '2023-10-31 to 2023-11-30' => [Periodicity::Monthly, Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')]; + + yield Periodicity::Quarterly->name => [Periodicity::Quarterly, Carbon::now(), Carbon::now()->addMonthsNoOverflow(3)]; + + yield '2019-01-29 to 2020-04-29' => [Periodicity::Quarterly, Carbon::parse('2019-01-29'), Carbon::parse('2019-04-29')]; + + yield '2019-01-30 to 2020-04-30' => [Periodicity::Quarterly, Carbon::parse('2019-01-30'), Carbon::parse('2019-04-30')]; + + yield '2019-01-31 to 2020-04-30' => [Periodicity::Quarterly, Carbon::parse('2019-01-31'), Carbon::parse('2019-04-30')]; + + yield Periodicity::HalfYearly->name => [Periodicity::HalfYearly, Carbon::now(), Carbon::now()->addMonthsNoOverflow(6)]; + + yield '2019-01-31 to 2020-07-29' => [Periodicity::HalfYearly, Carbon::parse('2019-01-29'), Carbon::parse('2019-07-29')]; + + yield '2019-01-31 to 2020-07-30' => [Periodicity::HalfYearly, Carbon::parse('2019-01-30'), Carbon::parse('2019-07-30')]; + + yield '2019-01-31 to 2020-07-31' => [Periodicity::HalfYearly, Carbon::parse('2019-01-31'), Carbon::parse('2019-07-31')]; + + yield Periodicity::Yearly->name => [Periodicity::Yearly, Carbon::now(), Carbon::now()->addYears(1)]; + + yield '2020-02-29 to 2021-02-28' => [Periodicity::Yearly, Carbon::parse('2020-02-29'), Carbon::parse('2021-02-28')]; } #[DataProvider('provideMonthPeriods')] @@ -176,19 +215,26 @@ final class NavigationAddPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function provideMonthPeriods(): iterable + public static function provideMonthPeriods(): Iterator { - return [ - '1M' => ['frequency' => '1M', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)], - 'month' => ['frequency' => 'month', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)], - 'monthly' => ['frequency' => 'monthly', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)], - '2019-01-29 to 2019-02-28' => ['frequency' => 'monthly', 'from' => Carbon::parse('2019-01-29'), 'expected' => Carbon::parse('2019-02-28')], - '2019-01-30 to 2019-02-28' => ['frequency' => 'monthly', 'from' => Carbon::parse('2019-01-30'), 'expected' => Carbon::parse('2019-02-28')], - '2019-01-31 to 2019-02-28' => ['frequency' => 'monthly', 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-02-28')], - '2023-03-31 to 2023-04-30' => ['frequency' => 'monthly', 'from' => Carbon::parse('2023-03-31'), 'expected' => Carbon::parse('2023-04-30')], - '2023-05-31 to 2023-06-30' => ['frequency' => 'monthly', 'from' => Carbon::parse('2023-05-31'), 'expected' => Carbon::parse('2023-06-30')], - '2023-08-31 to 2023-09-30' => ['frequency' => 'monthly', 'from' => Carbon::parse('2023-08-31'), 'expected' => Carbon::parse('2023-09-30')], - '2023-10-31 to 2023-11-30' => ['frequency' => 'monthly', 'from' => Carbon::parse('2023-10-31'), 'expected' => Carbon::parse('2023-11-30')], - ]; + yield '1M' => ['1M', Carbon::parse('2023-06-25'), Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)]; + + yield 'month' => ['month', Carbon::parse('2023-06-25'), Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)]; + + yield 'monthly' => ['monthly', Carbon::parse('2023-06-25'), Carbon::parse('2023-06-25')->addMonthsNoOverflow(1)]; + + yield '2019-01-29 to 2019-02-28' => ['monthly', Carbon::parse('2019-01-29'), Carbon::parse('2019-02-28')]; + + yield '2019-01-30 to 2019-02-28' => ['monthly', Carbon::parse('2019-01-30'), Carbon::parse('2019-02-28')]; + + yield '2019-01-31 to 2019-02-28' => ['monthly', Carbon::parse('2019-01-31'), Carbon::parse('2019-02-28')]; + + yield '2023-03-31 to 2023-04-30' => ['monthly', Carbon::parse('2023-03-31'), Carbon::parse('2023-04-30')]; + + yield '2023-05-31 to 2023-06-30' => ['monthly', Carbon::parse('2023-05-31'), Carbon::parse('2023-06-30')]; + + yield '2023-08-31 to 2023-09-30' => ['monthly', Carbon::parse('2023-08-31'), Carbon::parse('2023-09-30')]; + + yield '2023-10-31 to 2023-11-30' => ['monthly', Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')]; } } diff --git a/tests/unit/Support/NavigationEndOfPeriodTest.php b/tests/unit/Support/NavigationEndOfPeriodTest.php index 4a8e6a03bc..f76bb84be9 100644 --- a/tests/unit/Support/NavigationEndOfPeriodTest.php +++ b/tests/unit/Support/NavigationEndOfPeriodTest.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use Illuminate\Support\Facades\Log; @@ -42,6 +44,7 @@ final class NavigationEndOfPeriodTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -55,35 +58,56 @@ final class NavigationEndOfPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function provideDates(): iterable + public static function provideDates(): Iterator { - return [ - '1D' => ['frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::now()->endOfDay()], - 'daily' => ['frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::now()->endOfDay()], - '1W' => ['frequency' => '1W', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeek()->subDay()->endOfDay()], - 'week' => ['frequency' => 'week', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeek()->subDay()->endOfDay()], - 'weekly' => ['frequency' => 'weekly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeek()->subDay()->endOfDay()], - 'month' => ['frequency' => 'month', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonth()->subDay()->endOfDay()], - '1M' => ['frequency' => '1M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonth()->subDay()->endOfDay()], - 'monthly' => ['frequency' => 'monthly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonth()->subDay()->endOfDay()], - '3M' => ['frequency' => '3M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addQuarter()->subDay()->endOfDay()], - 'quarter' => ['frequency' => 'quarter', 'from' => Carbon::now(), 'expected' => Carbon::now()->addQuarter()->subDay()->endOfDay()], - 'quarterly' => ['frequency' => 'quarterly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addQuarter()->subDay()->endOfDay()], - 'year' => ['frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()], - 'yearly' => ['frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()], - '1Y' => ['frequency' => '1Y', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()], - 'half-year' => ['frequency' => 'half-year', 'from' => Carbon::parse('2023-05-20'), 'expected' => Carbon::parse('2023-11-19')->endOfDay()], - '6M' => ['frequency' => '6M', 'from' => Carbon::parse('2023-08-20'), 'expected' => Carbon::parse('2024-02-19')], - 'last7' => ['frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(7)->endOfDay()], - 'last30' => ['frequency' => 'last30', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(30)->endOfDay()], - 'last90' => ['frequency' => 'last90', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(90)->endOfDay()], - 'last365' => ['frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(365)->endOfDay()], - 'MTD' => ['frequency' => 'MTD', 'from' => Carbon::now(), - 'expected' => Carbon::now()->isSameMonth(Carbon::now()) ? Carbon::now()->endOfDay() : Carbon::now()->endOfMonth()], - 'QTD' => ['frequency' => 'QTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfQuarter()->startOfDay()], - 'YTD' => ['frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfYear()->startOfDay()], - 'week 2023-08-05 to 2023-08-11' => ['frequency' => '1W', 'from' => Carbon::parse('2023-08-05'), 'expected' => Carbon::parse('2023-08-11')->endOfDay()], - ]; + yield '1D' => ['1D', Carbon::now(), Carbon::now()->endOfDay()]; + + yield 'daily' => ['daily', Carbon::now(), Carbon::now()->endOfDay()]; + + yield '1W' => ['1W', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + + yield 'week' => ['week', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + + yield 'weekly' => ['weekly', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + + yield 'month' => ['month', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + + yield '1M' => ['1M', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + + yield 'monthly' => ['monthly', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + + yield '3M' => ['3M', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + + yield 'quarter' => ['quarter', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + + yield 'quarterly' => ['quarterly', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + + yield 'year' => ['year', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + + yield 'yearly' => ['yearly', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + + yield '1Y' => ['1Y', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + + yield 'half-year' => ['half-year', Carbon::parse('2023-05-20'), Carbon::parse('2023-11-19')->endOfDay()]; + + yield '6M' => ['6M', Carbon::parse('2023-08-20'), Carbon::parse('2024-02-19')]; + + yield 'last7' => ['last7', Carbon::now(), Carbon::now()->addDays(7)->endOfDay()]; + + yield 'last30' => ['last30', Carbon::now(), Carbon::now()->addDays(30)->endOfDay()]; + + yield 'last90' => ['last90', Carbon::now(), Carbon::now()->addDays(90)->endOfDay()]; + + yield 'last365' => ['last365', Carbon::now(), Carbon::now()->addDays(365)->endOfDay()]; + + yield 'MTD' => ['MTD', Carbon::now(), + Carbon::now()->isSameMonth(Carbon::now()) ? Carbon::now()->endOfDay() : Carbon::now()->endOfMonth()]; + + yield 'QTD' => ['QTD', Carbon::now(), Carbon::now()->firstOfQuarter()->startOfDay()]; + + yield 'YTD' => ['YTD', Carbon::now(), Carbon::now()->firstOfYear()->startOfDay()]; + + yield 'week 2023-08-05 to 2023-08-11' => ['1W', Carbon::parse('2023-08-05'), Carbon::parse('2023-08-11')->endOfDay()]; } #[DataProvider('provideUnknownFrequencies')] @@ -98,12 +122,12 @@ final class NavigationEndOfPeriodTest extends TestCase Log::shouldHaveReceived('error', [$expectedMessage]); } - public static function provideUnknownFrequencies(): iterable + public static function provideUnknownFrequencies(): Iterator { - return [ - '1day' => ['frequency' => '1day', 'from' => Carbon::now(), 'expected' => Carbon::now()], - 'unknown' => ['frequency' => 'unknown', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - 'empty' => ['frequency' => '', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - ]; + yield '1day' => ['1day', Carbon::now(), Carbon::now()]; + + yield 'unknown' => ['unknown', Carbon::now(), Carbon::now()->startOfDay()]; + + yield 'empty' => ['', Carbon::now(), Carbon::now()->startOfDay()]; } } diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php index 166a68b37b..6f25d44beb 100644 --- a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php +++ b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use FireflyIII\Support\Navigation; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -41,6 +43,7 @@ final class NavigationPreferredCarbonFormatByPeriodTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -54,15 +57,18 @@ final class NavigationPreferredCarbonFormatByPeriodTest extends TestCase self::assertSame($expected, $formatPeriod); } - public static function providePeriods(): iterable + public static function providePeriods(): Iterator { - return [ - 'unknown' => ['period' => '1day', 'expected' => 'Y-m-d'], - 'week' => ['period' => '1W', 'expected' => '\WW,Y'], - 'month' => ['period' => '1M', 'expected' => 'Y-m'], - 'quarterly' => ['period' => '3M', 'expected' => '\QQ,Y'], - 'half-yearly' => ['period' => '6M', 'expected' => '\QQ,Y'], - 'yearly' => ['period' => '1Y', 'expected' => 'Y'], - ]; + yield 'unknown' => ['1day', 'Y-m-d']; + + yield 'week' => ['1W', '\WW,Y']; + + yield 'month' => ['1M', 'Y-m']; + + yield 'quarterly' => ['3M', '\QQ,Y']; + + yield 'half-yearly' => ['6M', '\QQ,Y']; + + yield 'yearly' => ['1Y', 'Y']; } } diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php index b0a08cec13..01f06aad2b 100644 --- a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php +++ b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use PHPUnit\Framework\Attributes\DataProvider; @@ -42,6 +44,7 @@ final class NavigationPreferredCarbonFormatTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -55,21 +58,30 @@ final class NavigationPreferredCarbonFormatTest extends TestCase self::assertSame($expected, $carbonFormat); } - public static function providePeriods(): iterable + public static function providePeriods(): Iterator { - return [ - '1 week' => ['start' => Carbon::now(), 'end' => Carbon::now()->addWeek(), 'expected' => 'Y-m-d'], - '1 month' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonth(), 'expected' => 'Y-m-d'], - '2 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(2), 'expected' => 'Y-m'], - '3 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(3), 'expected' => 'Y-m'], - '6 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(6), 'expected' => 'Y-m'], - '7 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(7), 'expected' => 'Y-m'], - '11 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(11), 'expected' => 'Y-m'], - '12 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(12), 'expected' => 'Y-m'], - '13 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(13), 'expected' => 'Y'], - '16 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(16), 'expected' => 'Y'], - '1 year' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYear(), 'expected' => 'Y-m'], - '2 years' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYears(2), 'expected' => 'Y'], - ]; + yield '1 week' => [Carbon::now(), Carbon::now()->addWeek(), 'Y-m-d']; + + yield '1 month' => [Carbon::now(), Carbon::now()->addMonth(), 'Y-m-d']; + + yield '2 months' => [Carbon::now(), Carbon::now()->addMonths(2), 'Y-m']; + + yield '3 months' => [Carbon::now(), Carbon::now()->addMonths(3), 'Y-m']; + + yield '6 months' => [Carbon::now(), Carbon::now()->addMonths(6), 'Y-m']; + + yield '7 months' => [Carbon::now(), Carbon::now()->addMonths(7), 'Y-m']; + + yield '11 months' => [Carbon::now(), Carbon::now()->addMonths(11), 'Y-m']; + + yield '12 months' => [Carbon::now(), Carbon::now()->addMonths(12), 'Y-m']; + + yield '13 months' => [Carbon::now(), Carbon::now()->addMonths(13), 'Y']; + + yield '16 months' => [Carbon::now(), Carbon::now()->addMonths(16), 'Y']; + + yield '1 year' => [Carbon::now(), Carbon::now()->addYear(), 'Y-m']; + + yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), 'Y']; } } diff --git a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php index 74b4b091c8..95bf81b575 100644 --- a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php +++ b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use PHPUnit\Framework\Attributes\DataProvider; @@ -42,6 +44,7 @@ final class NavigationPreferredEndOfPeriodTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -55,21 +58,30 @@ final class NavigationPreferredEndOfPeriodTest extends TestCase self::assertSame($expected, $formatPeriod); } - public static function providePeriods(): iterable + public static function providePeriods(): Iterator { - return [ - '1 week' => ['start' => Carbon::now(), 'end' => Carbon::now()->addWeek(), 'expected' => 'endOfDay'], - '1 month' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonth(), 'expected' => 'endOfDay'], - '2 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(2), 'expected' => 'endOfMonth'], - '3 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(3), 'expected' => 'endOfMonth'], - '6 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(6), 'expected' => 'endOfMonth'], - '7 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(7), 'expected' => 'endOfMonth'], - '11 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(11), 'expected' => 'endOfMonth'], - '12 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(12), 'expected' => 'endOfMonth'], - '13 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(13), 'expected' => 'endOfYear'], - '16 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(16), 'expected' => 'endOfYear'], - '1 year' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYear(), 'expected' => 'endOfMonth'], - '2 years' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYears(2), 'expected' => 'endOfYear'], - ]; + yield '1 week' => [Carbon::now(), Carbon::now()->addWeek(), 'endOfDay']; + + yield '1 month' => [Carbon::now(), Carbon::now()->addMonth(), 'endOfDay']; + + yield '2 months' => [Carbon::now(), Carbon::now()->addMonths(2), 'endOfMonth']; + + yield '3 months' => [Carbon::now(), Carbon::now()->addMonths(3), 'endOfMonth']; + + yield '6 months' => [Carbon::now(), Carbon::now()->addMonths(6), 'endOfMonth']; + + yield '7 months' => [Carbon::now(), Carbon::now()->addMonths(7), 'endOfMonth']; + + yield '11 months' => [Carbon::now(), Carbon::now()->addMonths(11), 'endOfMonth']; + + yield '12 months' => [Carbon::now(), Carbon::now()->addMonths(12), 'endOfMonth']; + + yield '13 months' => [Carbon::now(), Carbon::now()->addMonths(13), 'endOfYear']; + + yield '16 months' => [Carbon::now(), Carbon::now()->addMonths(16), 'endOfYear']; + + yield '1 year' => [Carbon::now(), Carbon::now()->addYear(), 'endOfMonth']; + + yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), 'endOfYear']; } } diff --git a/tests/unit/Support/NavigationPreferredRangeFormatTest.php b/tests/unit/Support/NavigationPreferredRangeFormatTest.php index daae6b3731..6c0eff7d07 100644 --- a/tests/unit/Support/NavigationPreferredRangeFormatTest.php +++ b/tests/unit/Support/NavigationPreferredRangeFormatTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use PHPUnit\Framework\Attributes\DataProvider; @@ -42,6 +44,7 @@ final class NavigationPreferredRangeFormatTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -55,21 +58,30 @@ final class NavigationPreferredRangeFormatTest extends TestCase self::assertSame($expected, $formatPeriod); } - public static function providePeriods(): iterable + public static function providePeriods(): Iterator { - return [ - '1 week' => ['start' => Carbon::now(), 'end' => Carbon::now()->addWeek(), 'expected' => '1D'], - '1 month' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonth(), 'expected' => '1D'], - '2 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(2), 'expected' => '1M'], - '3 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(3), 'expected' => '1M'], - '6 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(6), 'expected' => '1M'], - '7 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(7), 'expected' => '1M'], - '11 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(11), 'expected' => '1M'], - '12 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(12), 'expected' => '1M'], - '13 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(13), 'expected' => '1Y'], - '16 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(16), 'expected' => '1Y'], - '1 year' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYear(), 'expected' => '1M'], - '2 years' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYears(2), 'expected' => '1Y'], - ]; + yield '1 week' => [Carbon::now(), Carbon::now()->addWeek(), '1D']; + + yield '1 month' => [Carbon::now(), Carbon::now()->addMonth(), '1D']; + + yield '2 months' => [Carbon::now(), Carbon::now()->addMonths(2), '1M']; + + yield '3 months' => [Carbon::now(), Carbon::now()->addMonths(3), '1M']; + + yield '6 months' => [Carbon::now(), Carbon::now()->addMonths(6), '1M']; + + yield '7 months' => [Carbon::now(), Carbon::now()->addMonths(7), '1M']; + + yield '11 months' => [Carbon::now(), Carbon::now()->addMonths(11), '1M']; + + yield '12 months' => [Carbon::now(), Carbon::now()->addMonths(12), '1M']; + + yield '13 months' => [Carbon::now(), Carbon::now()->addMonths(13), '1Y']; + + yield '16 months' => [Carbon::now(), Carbon::now()->addMonths(16), '1Y']; + + yield '1 year' => [Carbon::now(), Carbon::now()->addYear(), '1M']; + + yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), '1Y']; } } diff --git a/tests/unit/Support/NavigationPreferredSqlFormatTest.php b/tests/unit/Support/NavigationPreferredSqlFormatTest.php index 4bf135cf2a..fa44b76178 100644 --- a/tests/unit/Support/NavigationPreferredSqlFormatTest.php +++ b/tests/unit/Support/NavigationPreferredSqlFormatTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use PHPUnit\Framework\Attributes\DataProvider; @@ -42,6 +44,7 @@ final class NavigationPreferredSqlFormatTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -55,21 +58,30 @@ final class NavigationPreferredSqlFormatTest extends TestCase self::assertSame($expected, $formatPeriod); } - public static function provideDates(): iterable + public static function provideDates(): Iterator { - return [ - '1 week' => ['start' => Carbon::now(), 'end' => Carbon::now()->addWeek(), 'expected' => '%Y-%m-%d'], - '1 month' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonth(), 'expected' => '%Y-%m-%d'], - '2 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(2), 'expected' => '%Y-%m'], - '3 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(3), 'expected' => '%Y-%m'], - '6 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(6), 'expected' => '%Y-%m'], - '7 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(7), 'expected' => '%Y-%m'], - '11 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(11), 'expected' => '%Y-%m'], - '12 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(12), 'expected' => '%Y-%m'], - '13 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(13), 'expected' => '%Y'], - '16 months' => ['start' => Carbon::now(), 'end' => Carbon::now()->addMonths(16), 'expected' => '%Y'], - '1 year' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYear(), 'expected' => '%Y-%m'], - '2 years' => ['start' => Carbon::now(), 'end' => Carbon::now()->addYears(2), 'expected' => '%Y'], - ]; + yield '1 week' => [Carbon::now(), Carbon::now()->addWeek(), '%Y-%m-%d']; + + yield '1 month' => [Carbon::now(), Carbon::now()->addMonth(), '%Y-%m-%d']; + + yield '2 months' => [Carbon::now(), Carbon::now()->addMonths(2), '%Y-%m']; + + yield '3 months' => [Carbon::now(), Carbon::now()->addMonths(3), '%Y-%m']; + + yield '6 months' => [Carbon::now(), Carbon::now()->addMonths(6), '%Y-%m']; + + yield '7 months' => [Carbon::now(), Carbon::now()->addMonths(7), '%Y-%m']; + + yield '11 months' => [Carbon::now(), Carbon::now()->addMonths(11), '%Y-%m']; + + yield '12 months' => [Carbon::now(), Carbon::now()->addMonths(12), '%Y-%m']; + + yield '13 months' => [Carbon::now(), Carbon::now()->addMonths(13), '%Y']; + + yield '16 months' => [Carbon::now(), Carbon::now()->addMonths(16), '%Y']; + + yield '1 year' => [Carbon::now(), Carbon::now()->addYear(), '%Y-%m']; + + yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), '%Y']; } } diff --git a/tests/unit/Support/NavigationStartOfPeriodTest.php b/tests/unit/Support/NavigationStartOfPeriodTest.php index c037fa3f10..ffe2514683 100644 --- a/tests/unit/Support/NavigationStartOfPeriodTest.php +++ b/tests/unit/Support/NavigationStartOfPeriodTest.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; +use Override; +use Iterator; use Carbon\Carbon; use FireflyIII\Support\Navigation; use Illuminate\Support\Facades\Log; @@ -43,6 +45,7 @@ final class NavigationStartOfPeriodTest extends TestCase { private Navigation $navigation; + #[Override] protected function setUp(): void { parent::setUp(); @@ -56,34 +59,55 @@ final class NavigationStartOfPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function provideDates(): iterable + public static function provideDates(): Iterator { - return [ - 'custom' => ['frequency' => 'custom', 'from' => Carbon::now(), 'expected' => Carbon::now()], - '1D' => ['frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - 'daily' => ['frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - '1W' => ['frequency' => '1W', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfWeek()], - 'week' => ['frequency' => 'week', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfWeek()], - 'weekly' => ['frequency' => 'weekly', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfWeek()], - 'month' => ['frequency' => 'month', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfMonth()], - '1M' => ['frequency' => '1M', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfMonth()], - 'monthly' => ['frequency' => 'monthly', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfMonth()], - '3M' => ['frequency' => '3M', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfQuarter()], - 'quarter' => ['frequency' => 'quarter', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfQuarter()], - 'quarterly' => ['frequency' => 'quarterly', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfQuarter()], - 'year' => ['frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfYear()], - 'yearly' => ['frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfYear()], - '1Y' => ['frequency' => '1Y', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfYear()], - 'half-year' => ['frequency' => 'half-year', 'from' => Carbon::parse('2023-05-20'), 'expected' => Carbon::parse('2023-01-01')->startOfYear()], - '6M' => ['frequency' => '6M', 'from' => Carbon::parse('2023-08-20'), 'expected' => Carbon::parse('2023-07-01')], - 'last7' => ['frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->subDays(7)->startOfDay()], - 'last30' => ['frequency' => 'last30', 'from' => Carbon::now(), 'expected' => Carbon::now()->subDays(30)->startOfDay()], - 'last90' => ['frequency' => 'last90', 'from' => Carbon::now(), 'expected' => Carbon::now()->subDays(90)->startOfDay()], - 'last365' => ['frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->subDays(365)->startOfDay()], - 'MTD' => ['frequency' => 'MTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfMonth()->startOfDay()], - 'QTD' => ['frequency' => 'QTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->firstOfQuarter()->startOfDay()], - 'YTD' => ['frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfYear()->startOfDay()], - ]; + yield 'custom' => ['custom', Carbon::now(), Carbon::now()]; + + yield '1D' => ['1D', Carbon::now(), Carbon::now()->startOfDay()]; + + yield 'daily' => ['daily', Carbon::now(), Carbon::now()->startOfDay()]; + + yield '1W' => ['1W', Carbon::now(), Carbon::now()->startOfWeek()]; + + yield 'week' => ['week', Carbon::now(), Carbon::now()->startOfWeek()]; + + yield 'weekly' => ['weekly', Carbon::now(), Carbon::now()->startOfWeek()]; + + yield 'month' => ['month', Carbon::now(), Carbon::now()->startOfMonth()]; + + yield '1M' => ['1M', Carbon::now(), Carbon::now()->startOfMonth()]; + + yield 'monthly' => ['monthly', Carbon::now(), Carbon::now()->startOfMonth()]; + + yield '3M' => ['3M', Carbon::now(), Carbon::now()->firstOfQuarter()]; + + yield 'quarter' => ['quarter', Carbon::now(), Carbon::now()->firstOfQuarter()]; + + yield 'quarterly' => ['quarterly', Carbon::now(), Carbon::now()->firstOfQuarter()]; + + yield 'year' => ['year', Carbon::now(), Carbon::now()->startOfYear()]; + + yield 'yearly' => ['yearly', Carbon::now(), Carbon::now()->startOfYear()]; + + yield '1Y' => ['1Y', Carbon::now(), Carbon::now()->startOfYear()]; + + yield 'half-year' => ['half-year', Carbon::parse('2023-05-20'), Carbon::parse('2023-01-01')->startOfYear()]; + + yield '6M' => ['6M', Carbon::parse('2023-08-20'), Carbon::parse('2023-07-01')]; + + yield 'last7' => ['last7', Carbon::now(), Carbon::now()->subDays(7)->startOfDay()]; + + yield 'last30' => ['last30', Carbon::now(), Carbon::now()->subDays(30)->startOfDay()]; + + yield 'last90' => ['last90', Carbon::now(), Carbon::now()->subDays(90)->startOfDay()]; + + yield 'last365' => ['last365', Carbon::now(), Carbon::now()->subDays(365)->startOfDay()]; + + yield 'MTD' => ['MTD', Carbon::now(), Carbon::now()->startOfMonth()->startOfDay()]; + + yield 'QTD' => ['QTD', Carbon::now(), Carbon::now()->firstOfQuarter()->startOfDay()]; + + yield 'YTD' => ['YTD', Carbon::now(), Carbon::now()->startOfYear()->startOfDay()]; } #[DataProvider('provideUnknownFrequencies')] @@ -100,12 +124,12 @@ final class NavigationStartOfPeriodTest extends TestCase self::assertSame($expected->toDateString(), $period->toDateString()); } - public static function provideUnknownFrequencies(): iterable + public static function provideUnknownFrequencies(): Iterator { - return [ - '1day' => ['frequency' => '1day', 'from' => Carbon::now(), 'expected' => Carbon::now()], - 'unknown' => ['frequency' => 'unknown', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - 'empty' => ['frequency' => '', 'from' => Carbon::now(), 'expected' => Carbon::now()->startOfDay()], - ]; + yield '1day' => ['1day', Carbon::now(), Carbon::now()]; + + yield 'unknown' => ['unknown', Carbon::now(), Carbon::now()->startOfDay()]; + + yield 'empty' => ['', Carbon::now(), Carbon::now()->startOfDay()]; } } diff --git a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php index 780f00d113..311e745586 100644 --- a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php +++ b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\unit\Support\Search\QueryParser; +use Iterator; use FireflyIII\Support\Search\QueryParser\FieldNode; use FireflyIII\Support\Search\QueryParser\QueryParserInterface; use FireflyIII\Support\Search\QueryParser\StringNode; @@ -29,170 +30,190 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase } - public static function queryDataProvider(): iterable + public static function queryDataProvider(): Iterator { - return [ - 'empty query' => [ - 'query' => '', - 'expected' => new NodeGroup([]), - ], - 'simple word' => [ - 'query' => 'groceries', - 'expected' => new NodeGroup([new StringNode('groceries')]), - ], - 'prohibited word' => [ - 'query' => '-groceries', - 'expected' => new NodeGroup([new StringNode('groceries', true)]), - ], - 'prohibited field' => [ - 'query' => '-amount:100', - 'expected' => new NodeGroup([new FieldNode('amount', '100', true)]), - ], - 'quoted word' => [ - 'query' => '"test phrase"', - 'expected' => new NodeGroup([new StringNode('test phrase')]), - ], - 'prohibited quoted word' => [ - 'query' => '-"test phrase"', - 'expected' => new NodeGroup([new StringNode('test phrase', true)]), - ], - 'multiple words' => [ - 'query' => 'groceries shopping market', - 'expected' => new NodeGroup([ - new StringNode('groceries'), - new StringNode('shopping'), - new StringNode('market'), - ]), - ], - 'field operator' => [ - 'query' => 'amount:100', - 'expected' => new NodeGroup([new FieldNode('amount', '100')]), - ], - 'quoted field value with single space' => [ - 'query' => 'description:"test phrase"', - 'expected' => new NodeGroup([new FieldNode('description', 'test phrase')]), - ], - 'multiple fields' => [ - 'query' => 'amount:100 category:food', - 'expected' => new NodeGroup([ + yield 'empty query' => [ + '', + new NodeGroup([]), + ]; + + yield 'simple word' => [ + 'groceries', + new NodeGroup([new StringNode('groceries')]), + ]; + + yield 'prohibited word' => [ + '-groceries', + new NodeGroup([new StringNode('groceries', true)]), + ]; + + yield 'prohibited field' => [ + '-amount:100', + new NodeGroup([new FieldNode('amount', '100', true)]), + ]; + + yield 'quoted word' => [ + '"test phrase"', + new NodeGroup([new StringNode('test phrase')]), + ]; + + yield 'prohibited quoted word' => [ + '-"test phrase"', + new NodeGroup([new StringNode('test phrase', true)]), + ]; + + yield 'multiple words' => [ + 'groceries shopping market', + new NodeGroup([ + new StringNode('groceries'), + new StringNode('shopping'), + new StringNode('market'), + ]), + ]; + + yield 'field operator' => [ + 'amount:100', + new NodeGroup([new FieldNode('amount', '100')]), + ]; + + yield 'quoted field value with single space' => [ + 'description:"test phrase"', + new NodeGroup([new FieldNode('description', 'test phrase')]), + ]; + + yield 'multiple fields' => [ + 'amount:100 category:food', + new NodeGroup([ + new FieldNode('amount', '100'), + new FieldNode('category', 'food'), + ]), + ]; + + yield 'simple subquery' => [ + '(amount:100 category:food)', + new NodeGroup([ + new NodeGroup([ new FieldNode('amount', '100'), new FieldNode('category', 'food'), ]), - ], - 'simple subquery' => [ - 'query' => '(amount:100 category:food)', - 'expected' => new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ]), - ]), - ], - 'prohibited subquery' => [ - 'query' => '-(amount:100 category:food)', - 'expected' => new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ], true), - ]), - ], - 'nested subquery' => [ - 'query' => '(amount:100 (description:"test" category:food))', - 'expected' => new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new NodeGroup([ - new FieldNode('description', 'test'), - new FieldNode('category', 'food'), - ]), - ]), - ]), - ], - 'mixed words and operators' => [ - 'query' => 'groceries amount:50 shopping', - 'expected' => new NodeGroup([ - new StringNode('groceries'), - new FieldNode('amount', '50'), - new StringNode('shopping'), - ]), - ], - 'subquery after field value' => [ - 'query' => 'amount:100 (description:"market" category:food)', - 'expected' => new NodeGroup([ + ]), + ]; + + yield 'prohibited subquery' => [ + '-(amount:100 category:food)', + new NodeGroup([ + new NodeGroup([ + new FieldNode('amount', '100'), + new FieldNode('category', 'food'), + ], true), + ]), + ]; + + yield 'nested subquery' => [ + '(amount:100 (description:"test" category:food))', + new NodeGroup([ + new NodeGroup([ new FieldNode('amount', '100'), new NodeGroup([ - new FieldNode('description', 'market'), + new FieldNode('description', 'test'), new FieldNode('category', 'food'), ]), ]), - ], - 'word followed by subquery' => [ - 'query' => 'groceries (amount:100 description_contains:"test")', - 'expected' => new NodeGroup([ - new StringNode('groceries'), + ]), + ]; + + yield 'mixed words and operators' => [ + 'groceries amount:50 shopping', + new NodeGroup([ + new StringNode('groceries'), + new FieldNode('amount', '50'), + new StringNode('shopping'), + ]), + ]; + + yield 'subquery after field value' => [ + 'amount:100 (description:"market" category:food)', + new NodeGroup([ + new FieldNode('amount', '100'), + new NodeGroup([ + new FieldNode('description', 'market'), + new FieldNode('category', 'food'), + ]), + ]), + ]; + + yield 'word followed by subquery' => [ + 'groceries (amount:100 description_contains:"test")', + new NodeGroup([ + new StringNode('groceries'), + new NodeGroup([ + new FieldNode('amount', '100'), + new FieldNode('description_contains', 'test'), + ]), + ]), + ]; + + yield 'nested subquery with prohibited field' => [ + '(amount:100 (description_contains:"test payment" -has_attachments:true))', + new NodeGroup([ + new NodeGroup([ + new FieldNode('amount', '100'), new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('description_contains', 'test'), + new FieldNode('description_contains', 'test payment'), + new FieldNode('has_attachments', 'true', true), ]), ]), - ], - 'nested subquery with prohibited field' => [ - 'query' => '(amount:100 (description_contains:"test payment" -has_attachments:true))', - 'expected' => new NodeGroup([ + ]), + ]; + + yield 'complex nested subqueries' => [ + 'shopping (amount:50 market (-category:food word description:"test phrase" (has_notes:true)))', + new NodeGroup([ + new StringNode('shopping'), + new NodeGroup([ + new FieldNode('amount', '50'), + new StringNode('market'), new NodeGroup([ - new FieldNode('amount', '100'), + new FieldNode('category', 'food', true), + new StringNode('word'), + new FieldNode('description', 'test phrase'), new NodeGroup([ - new FieldNode('description_contains', 'test payment'), - new FieldNode('has_attachments', 'true', true), + new FieldNode('has_notes', 'true'), ]), ]), ]), - ], - 'complex nested subqueries' => [ - 'query' => 'shopping (amount:50 market (-category:food word description:"test phrase" (has_notes:true)))', - 'expected' => new NodeGroup([ - new StringNode('shopping'), - new NodeGroup([ - new FieldNode('amount', '50'), - new StringNode('market'), - new NodeGroup([ - new FieldNode('category', 'food', true), - new StringNode('word'), - new FieldNode('description', 'test phrase'), - new NodeGroup([ - new FieldNode('has_notes', 'true'), - ]), - ]), - ]), + ]), + ]; + + yield 'word with multiple spaces' => [ + '"multiple spaces"', + new NodeGroup([new StringNode('multiple spaces')]), + ]; + + yield 'field with multiple spaces in value' => [ + 'description:"multiple spaces here"', + new NodeGroup([new FieldNode('description', 'multiple spaces here')]), + ]; + + yield 'unmatched right parenthesis in word' => [ + 'test)word', + new NodeGroup([new StringNode('test)word')]), + ]; + + yield 'unmatched right parenthesis in field' => [ + 'description:test)phrase', + new NodeGroup([new FieldNode('description', 'test)phrase')]), + ]; + + yield 'subquery followed by word' => [ + '(amount:100 category:food) shopping', + new NodeGroup([ + new NodeGroup([ + new FieldNode('amount', '100'), + new FieldNode('category', 'food'), ]), - ], - 'word with multiple spaces' => [ - 'query' => '"multiple spaces"', - 'expected' => new NodeGroup([new StringNode('multiple spaces')]), - ], - 'field with multiple spaces in value' => [ - 'query' => 'description:"multiple spaces here"', - 'expected' => new NodeGroup([new FieldNode('description', 'multiple spaces here')]), - ], - 'unmatched right parenthesis in word' => [ - 'query' => 'test)word', - 'expected' => new NodeGroup([new StringNode('test)word')]), - ], - 'unmatched right parenthesis in field' => [ - 'query' => 'description:test)phrase', - 'expected' => new NodeGroup([new FieldNode('description', 'test)phrase')]), - ], - 'subquery followed by word' => [ - 'query' => '(amount:100 category:food) shopping', - 'expected' => new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ]), - new StringNode('shopping'), - ]), - ], + new StringNode('shopping'), + ]), ]; } }