diff --git a/.ci/phpstan.neon b/.ci/phpstan.neon index 44091826a9..199a9a91bf 100644 --- a/.ci/phpstan.neon +++ b/.ci/phpstan.neon @@ -10,6 +10,19 @@ parameters: - '#is neither abstract nor final#' - '#Control structures using switch should not be used\.#' - '#has a nullable return type declaration#' + - '#with a nullable type declaration#' + - '#with null as default value#' + - '#Constructor in [a-zA-Z0-9\\_]+ has parameter \$[a-zA-Z0-9\\_]+ with default value#' + - + message: '#Function compact\(\) should not be used.#' + paths: + - ../app/Http/Controllers + - ../app/Support/Http/Controllers/RenderPartialViews.php + - ../app/Support/Form/FormSupport.php + - ../app/Support/Form/CurrencyForm.php + - ../app/Support/Form/AccountForm.php + - ../app/Support/ExpandedForm.php + - ../app/Generator/Report paths: - ../app - ../database @@ -17,4 +30,4 @@ parameters: - ../bootstrap/app.php # The level 8 is the highest level. original was 5 - level: 5 + level: 2 diff --git a/.ci/phpstan.sh b/.ci/phpstan.sh index 01e34546b3..4ffaffe5a4 100755 --- a/.ci/phpstan.sh +++ b/.ci/phpstan.sh @@ -21,12 +21,13 @@ # # Install composer packages -composer install --no-scripts --no-ansi +#composer install --no-scripts --no-ansi # enable test .env file. cp .ci/.env.ci .env # Do static code analysis. -./vendor/bin/phpstan analyse -c .ci/phpstan.neon --no-progress +# ./vendor/bin/phpstan analyse -c .ci/phpstan.neon --no-progress +./vendor/bin/phpstan analyse -c .ci/phpstan.neon exit 0 \ No newline at end of file diff --git a/.ci/phpunit.sh b/.ci/phpunit.sh index c96fa69e96..e7c47d109c 100755 --- a/.ci/phpunit.sh +++ b/.ci/phpunit.sh @@ -24,6 +24,7 @@ cp .ci/.env.ci ../.env # download test database +# TODO no longer exists wget --quiet https://raw.githubusercontent.com/firefly-iii/test-data/main/test_db.sqlite -o storage/database/test_db.sqlite # run phpunit diff --git a/.env.example b/.env.example index c349c993fd..e9f1dd6cb9 100644 --- a/.env.example +++ b/.env.example @@ -155,8 +155,16 @@ SEND_REPORT_JOURNALS=true # Set a Mapbox API key here (see mapbox.com) so there might be a map available at various places. # If you use Docker or similar, you can set this variable from a file by appending it with _FILE +# Take note: it is no longer necessary to set this value, and it will be removed in future versions. MAPBOX_API_KEY= +# +# Instead of the mapbox API key, just set this value to true if you want to set the location +# of certain things, like transactions. Since this involves an external service, it's optional +# and disabled by default. +# +ENABLE_EXTERNAL_MAP=false + # The map will default to this location: MAP_DEFAULT_LAT=51.983333 MAP_DEFAULT_LONG=5.916667 diff --git a/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php b/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php index 3181f350c0..00342d21a4 100644 --- a/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php +++ b/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php @@ -66,7 +66,7 @@ class ObjectGroupController extends Controller $return = []; $result = $this->repository->search($data['query'], $data['limit']); - /** @var ObjectGroup $account */ + /** @var ObjectGroup $objectGroup */ foreach ($result as $objectGroup) { $return[] = [ 'id' => (string)$objectGroup->id, diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 4f7d27061e..52187964a5 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -86,12 +86,12 @@ class AccountController extends Controller $defaultSet = $this->repository->getAccountsByType([AccountType::ASSET])->pluck('id')->toArray(); $frontPage = app('preferences')->get('frontPageAccounts', $defaultSet); $default = app('amount')->getDefaultCurrency(); - // @codeCoverageIgnoreStart + if (0 === count($frontPage->data)) { $frontPage->data = $defaultSet; $frontPage->save(); } - // @codeCoverageIgnoreEnd + // get accounts: $accounts = $this->repository->getAccountsById($frontPage->data); @@ -100,7 +100,7 @@ class AccountController extends Controller foreach ($accounts as $account) { $currency = $this->repository->getAccountCurrency($account); if (null === $currency) { - $currency = $default; // @codeCoverageIgnore + $currency = $default; } $currentSet = [ 'label' => $account->name, @@ -108,8 +108,8 @@ class AccountController extends Controller 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, - 'start_date' => $start->format('Y-m-d'), - 'end_date' => $end->format('Y-m-d'), + 'start_date' => $start->toAtomString(), + 'end_date' => $end->toAtomString(), 'type' => 'line', // line, area or bar 'yAxisID' => 0, // 0, 1, 2 'entries' => [], @@ -120,7 +120,7 @@ class AccountController extends Controller $previous = round((float)array_values($range)[0], 12); while ($currentStart <= $end) { $format = $currentStart->format('Y-m-d'); - $label = $currentStart->format('Y-m-d'); + $label = $currentStart->toAtomString(); $balance = array_key_exists($format, $range) ? round((float)$range[$format], 12) : $previous; $previous = $balance; $currentStart->addDay(); diff --git a/app/Api/V1/Controllers/Data/Bulk/AccountController.php b/app/Api/V1/Controllers/Data/Bulk/AccountController.php new file mode 100644 index 0000000000..be559d1ead --- /dev/null +++ b/app/Api/V1/Controllers/Data/Bulk/AccountController.php @@ -0,0 +1,71 @@ +. + */ + +namespace FireflyIII\Api\V1\Controllers\Data\Bulk; + + +use FireflyIII\Api\V1\Controllers\Controller; +use FireflyIII\Api\V1\Requests\Data\Bulk\MoveTransactionsRequest; +use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Services\Internal\Destroy\AccountDestroyService; +use Illuminate\Http\JsonResponse; + +/** + * Class AccountController + */ +class AccountController extends Controller +{ + private AccountRepositoryInterface $repository; + + public function __construct() + { + parent::__construct(); + $this->middleware( + function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); + + return $next($request); + } + ); + } + + /** + * @param MoveTransactionsRequest $request + * + * @return JsonResponse + */ + public function moveTransactions(MoveTransactionsRequest $request): JsonResponse + { + $accountIds = $request->getAll(); + $original = $this->repository->findNull($accountIds['original_account']); + $destination = $this->repository->findNull($accountIds['destination_account']); + + /** @var AccountDestroyService $service */ + $service = app(AccountDestroyService::class); + $service->moveTransactions($original, $destination); + + return response()->json([], 204); + + } + +} diff --git a/app/Api/V1/Controllers/Data/Export/ExportController.php b/app/Api/V1/Controllers/Data/Export/ExportController.php index fa5a8583c5..a84a9efa27 100644 --- a/app/Api/V1/Controllers/Data/Export/ExportController.php +++ b/app/Api/V1/Controllers/Data/Export/ExportController.php @@ -25,7 +25,6 @@ namespace FireflyIII\Api\V1\Controllers\Data\Export; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Data\Export\ExportRequest; use FireflyIII\Support\Export\ExportDataGenerator; -use FireflyIII\User; use Illuminate\Http\Response as LaravelResponse; use League\Csv\CannotInsertRecord; @@ -44,11 +43,8 @@ class ExportController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - /** @var ExportDataGenerator $exporter */ $this->exporter = app(ExportDataGenerator::class); - $this->exporter->setUser($user); + $this->exporter->setUser(auth()->user()); return $next($request); } @@ -92,7 +88,7 @@ class ExportController extends Controller ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', strlen($data[$key])); + ->header('Content-Length', (string)strlen($data[$key])); return $response; } diff --git a/app/Api/V1/Controllers/Insight/Expense/TagController.php b/app/Api/V1/Controllers/Insight/Expense/TagController.php index 7feb8f9d48..bdbeeb8f23 100644 --- a/app/Api/V1/Controllers/Insight/Expense/TagController.php +++ b/app/Api/V1/Controllers/Insight/Expense/TagController.php @@ -44,9 +44,8 @@ class TagController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - $user = auth()->user(); $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } @@ -128,7 +127,7 @@ class TagController extends Controller $collector->setTypes([TransactionType::WITHDRAWAL])->setRange($start, $end)->setSourceAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); - /** @var array $entry */ + /** @var array $journal */ foreach ($genericSet as $journal) { $currencyId = (int)$journal['currency_id']; $foreignCurrencyId = (int)$journal['foreign_currency_id']; diff --git a/app/Api/V1/Controllers/Insight/Income/TagController.php b/app/Api/V1/Controllers/Insight/Income/TagController.php index 5549fe8725..6b3714f7ac 100644 --- a/app/Api/V1/Controllers/Insight/Income/TagController.php +++ b/app/Api/V1/Controllers/Insight/Income/TagController.php @@ -130,7 +130,7 @@ class TagController extends Controller $collector->setTypes([TransactionType::DEPOSIT])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); - /** @var array $entry */ + /** @var array $journal */ foreach ($genericSet as $journal) { $currencyId = (int)$journal['currency_id']; $foreignCurrencyId = (int)$journal['foreign_currency_id']; diff --git a/app/Api/V1/Controllers/Insight/Transfer/TagController.php b/app/Api/V1/Controllers/Insight/Transfer/TagController.php index cfadadd10b..6a9f765d8b 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/TagController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/TagController.php @@ -132,7 +132,7 @@ class TagController extends Controller $collector->setTypes([TransactionType::TRANSFER])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); - /** @var array $entry */ + /** @var array $journal */ foreach ($genericSet as $journal) { $currencyId = (int)$journal['currency_id']; $foreignCurrencyId = (int)$journal['foreign_currency_id']; diff --git a/app/Api/V1/Controllers/Models/Attachment/ShowController.php b/app/Api/V1/Controllers/Models/Attachment/ShowController.php index 574db4add7..879b5460e2 100644 --- a/app/Api/V1/Controllers/Models/Attachment/ShowController.php +++ b/app/Api/V1/Controllers/Models/Attachment/ShowController.php @@ -100,7 +100,7 @@ class ShowController extends Controller ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', strlen($content)); + ->header('Content-Length', (string)strlen($content)); return $response; } diff --git a/app/Api/V1/Controllers/Models/Bill/DestroyController.php b/app/Api/V1/Controllers/Models/Bill/DestroyController.php index 06d40de10f..7e5c0ac4d8 100644 --- a/app/Api/V1/Controllers/Models/Bill/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Bill/DestroyController.php @@ -46,12 +46,8 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var BillRepositoryInterface repository */ $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Bill/ListController.php b/app/Api/V1/Controllers/Models/Bill/ListController.php index ac8aa382c1..691b4bda8e 100644 --- a/app/Api/V1/Controllers/Models/Bill/ListController.php +++ b/app/Api/V1/Controllers/Models/Bill/ListController.php @@ -57,12 +57,8 @@ class ListController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var BillRepositoryInterface repository */ $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Bill/ShowController.php b/app/Api/V1/Controllers/Models/Bill/ShowController.php index 8ba46997b4..3e43b29ef2 100644 --- a/app/Api/V1/Controllers/Models/Bill/ShowController.php +++ b/app/Api/V1/Controllers/Models/Bill/ShowController.php @@ -51,12 +51,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var BillRepositoryInterface repository */ $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.php index bffec9a225..5ef3bc4bb5 100644 --- a/app/Api/V1/Controllers/Models/Bill/StoreController.php +++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php @@ -52,12 +52,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var BillRepositoryInterface repository */ $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Bill/UpdateController.php b/app/Api/V1/Controllers/Models/Bill/UpdateController.php index cbdc6a69fd..2240463648 100644 --- a/app/Api/V1/Controllers/Models/Bill/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Bill/UpdateController.php @@ -49,12 +49,8 @@ class UpdateController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var BillRepositoryInterface repository */ $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Category/DestroyController.php b/app/Api/V1/Controllers/Models/Category/DestroyController.php index 62e74982fd..4e609fdb5e 100644 --- a/app/Api/V1/Controllers/Models/Category/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Category/DestroyController.php @@ -46,12 +46,8 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CategoryRepositoryInterface repository */ $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Category/ListController.php b/app/Api/V1/Controllers/Models/Category/ListController.php index bee9f4453e..019b9e875f 100644 --- a/app/Api/V1/Controllers/Models/Category/ListController.php +++ b/app/Api/V1/Controllers/Models/Category/ListController.php @@ -56,12 +56,8 @@ class ListController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CategoryRepositoryInterface repository */ $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Category/ShowController.php b/app/Api/V1/Controllers/Models/Category/ShowController.php index e7d30a53b3..3525791328 100644 --- a/app/Api/V1/Controllers/Models/Category/ShowController.php +++ b/app/Api/V1/Controllers/Models/Category/ShowController.php @@ -51,12 +51,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CategoryRepositoryInterface repository */ $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Category/StoreController.php b/app/Api/V1/Controllers/Models/Category/StoreController.php index d733697364..c799d9eee7 100644 --- a/app/Api/V1/Controllers/Models/Category/StoreController.php +++ b/app/Api/V1/Controllers/Models/Category/StoreController.php @@ -49,12 +49,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CategoryRepositoryInterface repository */ $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Category/UpdateController.php b/app/Api/V1/Controllers/Models/Category/UpdateController.php index f05625dcdc..bcab8b0778 100644 --- a/app/Api/V1/Controllers/Models/Category/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Category/UpdateController.php @@ -49,12 +49,8 @@ class UpdateController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CategoryRepositoryInterface repository */ $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php b/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php index 7e63348ec5..6c44dd1e60 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php @@ -46,12 +46,8 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/ListController.php b/app/Api/V1/Controllers/Models/Recurrence/ListController.php index a493df5377..1b989425c0 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ListController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ListController.php @@ -54,12 +54,8 @@ class ListController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php index bfa6bbcd58..d8e70cbea0 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php @@ -51,12 +51,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php index 8b0a7c2275..2c53478ec3 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php @@ -49,12 +49,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php b/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php deleted file mode 100644 index 0848c80b19..0000000000 --- a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php +++ /dev/null @@ -1,86 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V1\Controllers\Models\Recurrence; - -use FireflyIII\Api\V1\Controllers\Controller; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; -use FireflyIII\Support\Cronjobs\RecurringCronjob; -use FireflyIII\User; -use Illuminate\Http\JsonResponse; -use Log; - -/** - * Class TriggerController - */ -class TriggerController extends Controller -{ - private RecurringRepositoryInterface $repository; - - /** - * RecurrenceController constructor. - * - * @codeCoverageIgnore - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); - - return $next($request); - } - ); - } - - /** - * @return JsonResponse - * @throws FireflyException - * @codeCoverageIgnore - * - * TODO currently unused + unreachable. - */ - public function trigger(): JsonResponse - { - /** @var RecurringCronjob $recurring */ - $recurring = app(RecurringCronjob::class); - try { - $result = $recurring->fire(); - } catch (FireflyException $e) { - Log::error($e->getMessage()); - throw new FireflyException('200022: Error in cron job.', 0, $e); - } - if (false === $result) { - return response()->json([], 204); - } - - return response()->json(); - } -} diff --git a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php index 7d4c4646bb..2f15eb071f 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php @@ -49,12 +49,8 @@ class UpdateController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - - /** @var RecurringRepositoryInterface repository */ $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php index fd79c5d4ed..963c0490ef 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php @@ -37,6 +37,7 @@ use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Resource\Collection as FractalCollection; +use Exception; /** * Class TriggerController diff --git a/app/Api/V1/Controllers/Models/Transaction/StoreController.php b/app/Api/V1/Controllers/Models/Transaction/StoreController.php index c46fcac390..dcec81a1ca 100644 --- a/app/Api/V1/Controllers/Models/Transaction/StoreController.php +++ b/app/Api/V1/Controllers/Models/Transaction/StoreController.php @@ -94,13 +94,13 @@ class StoreController extends Controller $validator = Validator::make( ['transactions' => [['description' => $e->getMessage()]]], ['transactions.0.description' => new IsDuplicateTransaction] ); - throw new ValidationException($validator); + throw new ValidationException($validator,0, $e); } catch (FireflyException $e) { Log::warning('Caught an exception. Return error message.'); Log::error($e->getMessage()); $message = sprintf('Internal exception: %s', $e->getMessage()); $validator = Validator::make(['transactions' => [['description' => $message]]], ['transactions.0.description' => new IsDuplicateTransaction]); - throw new ValidationException($validator); + throw new ValidationException($validator,0, $e); } app('preferences')->mark(); event(new StoredTransactionGroup($transactionGroup, $data['apply_rules'] ?? true)); diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php index 2e7c76d7b9..53fc0f7a78 100644 --- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php @@ -96,7 +96,7 @@ class UpdateController extends Controller $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { - throw new NotFoundHttpException(); // @codeCoverageIgnore + throw new NotFoundHttpException(); } /** @var TransactionGroupTransformer $transformer */ $transformer = app(TransactionGroupTransformer::class); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php index da72def335..f933b068b5 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php @@ -50,13 +50,9 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CurrencyRepositoryInterface repository */ $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } @@ -79,13 +75,13 @@ class DestroyController extends Controller if (!$this->userRepository->hasRole($admin, 'owner')) { // access denied: - throw new FireflyException('200005: You need the "owner" role to do this.'); // @codeCoverageIgnore + throw new FireflyException('200005: You need the "owner" role to do this.'); } if ($this->repository->currencyInUse($currency)) { - throw new FireflyException('200006: Currency in use.'); // @codeCoverageIgnore + throw new FireflyException('200006: Currency in use.'); } if ($this->repository->isFallbackCurrency($currency)) { - throw new FireflyException('200026: Currency is fallback.'); // @codeCoverageIgnore + throw new FireflyException('200026: Currency is fallback.'); } $this->repository->destroy($currency); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php index 36a9bd080c..bfca5cad4a 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php @@ -77,13 +77,9 @@ class ListController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CurrencyRepositoryInterface repository */ $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php index efb7605fa3..4bd4fc290c 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php @@ -56,12 +56,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CurrencyRepositoryInterface repository */ $this->repository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php index e26e2b1fda..16ef964dfc 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php @@ -56,13 +56,9 @@ class StoreController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CurrencyRepositoryInterface repository */ $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php index 8e8641dd46..219620621f 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php @@ -56,13 +56,9 @@ class UpdateController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var CurrencyRepositoryInterface repository */ $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php index 22f93456cf..087eeae6fd 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php @@ -80,7 +80,7 @@ class StoreController extends Controller $admin = auth()->user(); if (!$this->userRepository->hasRole($admin, 'owner')) { - throw new FireflyException('200005: You need the "owner" role to do this.'); // @codeCoverageIgnore + throw new FireflyException('200005: You need the "owner" role to do this.'); } $data = $request->getAll(); // if currency ID is 0, find the currency by the code: diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php index 5b49acdf06..d97d6a355a 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php @@ -86,7 +86,7 @@ class UpdateController extends Controller $admin = auth()->user(); if (!$this->userRepository->hasRole($admin, 'owner')) { - throw new FireflyException('200005: You need the "owner" role to do this.'); // @codeCoverageIgnore + throw new FireflyException('200005: You need the "owner" role to do this.'); } $data = $request->getAll(); diff --git a/app/Api/V1/Controllers/System/ConfigurationController.php b/app/Api/V1/Controllers/System/ConfigurationController.php index da86e0369c..0ffbb1fc04 100644 --- a/app/Api/V1/Controllers/System/ConfigurationController.php +++ b/app/Api/V1/Controllers/System/ConfigurationController.php @@ -64,7 +64,7 @@ class ConfigurationController extends Controller } catch (FireflyException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException('200030: Could not load config variables.'); + throw new FireflyException('200030: Could not load config variables.', 0, $e); } $staticData = $this->getStaticConfiguration(); $return = []; @@ -161,7 +161,7 @@ class ConfigurationController extends Controller public function update(UpdateRequest $request, string $name): JsonResponse { if (!$this->repository->hasRole(auth()->user(), 'owner')) { - throw new FireflyException('200005: You need the "owner" role to do this.'); // @codeCoverageIgnore + throw new FireflyException('200005: You need the "owner" role to do this.'); } $data = $request->getAll(); $shortName = str_replace('configuration.', '', $name); diff --git a/app/Api/V1/Controllers/System/UserController.php b/app/Api/V1/Controllers/System/UserController.php index 2a83429055..62d48cfddf 100644 --- a/app/Api/V1/Controllers/System/UserController.php +++ b/app/Api/V1/Controllers/System/UserController.php @@ -54,7 +54,6 @@ class UserController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var UserRepositoryInterface repository */ $this->repository = app(UserRepositoryInterface::class); return $next($request); @@ -84,7 +83,7 @@ class UserController extends Controller return response()->json([], 204); } - throw new FireflyException('200025: No access to function.'); // @codeCoverageIgnore + throw new FireflyException('200025: No access to function.'); } /** diff --git a/app/Api/V1/Controllers/Webhook/AttemptController.php b/app/Api/V1/Controllers/Webhook/AttemptController.php index 2f938ebbcc..118480a407 100644 --- a/app/Api/V1/Controllers/Webhook/AttemptController.php +++ b/app/Api/V1/Controllers/Webhook/AttemptController.php @@ -53,12 +53,8 @@ class AttemptController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/DestroyController.php b/app/Api/V1/Controllers/Webhook/DestroyController.php index 5c3e2799f7..bb41507ede 100644 --- a/app/Api/V1/Controllers/Webhook/DestroyController.php +++ b/app/Api/V1/Controllers/Webhook/DestroyController.php @@ -48,12 +48,8 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/MessageController.php b/app/Api/V1/Controllers/Webhook/MessageController.php index 08005210bb..a863ad1778 100644 --- a/app/Api/V1/Controllers/Webhook/MessageController.php +++ b/app/Api/V1/Controllers/Webhook/MessageController.php @@ -49,12 +49,8 @@ class MessageController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/ShowController.php b/app/Api/V1/Controllers/Webhook/ShowController.php index 424f10990e..5fbdf20e37 100644 --- a/app/Api/V1/Controllers/Webhook/ShowController.php +++ b/app/Api/V1/Controllers/Webhook/ShowController.php @@ -50,12 +50,8 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/StoreController.php b/app/Api/V1/Controllers/Webhook/StoreController.php index 28bfb00b28..f61620e769 100644 --- a/app/Api/V1/Controllers/Webhook/StoreController.php +++ b/app/Api/V1/Controllers/Webhook/StoreController.php @@ -47,12 +47,8 @@ class StoreController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/SubmitController.php b/app/Api/V1/Controllers/Webhook/SubmitController.php index c2227b04e5..f81e7efebf 100644 --- a/app/Api/V1/Controllers/Webhook/SubmitController.php +++ b/app/Api/V1/Controllers/Webhook/SubmitController.php @@ -27,7 +27,6 @@ use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Jobs\SendWebhookMessage; use FireflyIII\Models\Webhook; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; -use FireflyIII\User; use Illuminate\Http\JsonResponse; /** @@ -45,12 +44,8 @@ class SubmitController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Controllers/Webhook/UpdateController.php b/app/Api/V1/Controllers/Webhook/UpdateController.php index e7db643085..d69dccf7b7 100644 --- a/app/Api/V1/Controllers/Webhook/UpdateController.php +++ b/app/Api/V1/Controllers/Webhook/UpdateController.php @@ -47,12 +47,8 @@ class UpdateController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - - /** @var WebhookRepositoryInterface repository */ $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository->setUser(auth()->user()); return $next($request); } diff --git a/app/Api/V1/Middleware/ApiDemoUser.php b/app/Api/V1/Middleware/ApiDemoUser.php index fd3b1e35b6..46cecc1966 100644 --- a/app/Api/V1/Middleware/ApiDemoUser.php +++ b/app/Api/V1/Middleware/ApiDemoUser.php @@ -41,7 +41,7 @@ class ApiDemoUser */ public function handle(Request $request, Closure $next) { - /** @var User $user */ + /** @var User|null $user */ $user = $request->user(); if (null === $user) { diff --git a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php new file mode 100644 index 0000000000..0f034d6467 --- /dev/null +++ b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php @@ -0,0 +1,105 @@ +. + */ + +namespace FireflyIII\Api\V1\Requests\Data\Bulk; + +use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Request\ChecksLogin; +use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Validation\Validator; + +/** + * Class MoveTransactionsRequest + */ +class MoveTransactionsRequest extends FormRequest +{ + use ChecksLogin, ConvertsDataTypes; + + /** + * @return array + */ + public function getAll(): array + { + return [ + 'original_account' => $this->integer('original_account'), + 'destination_account' => $this->integer('destination_account'), + ]; + } + + /** + * @return string[] + */ + public function rules(): array + { + return [ + 'original_account' => 'required|different:destination_account|belongsToUser:accounts,id', + 'destination_account' => 'required|different:original_account|belongsToUser:accounts,id', + ]; + } + + /** + * Configure the validator instance with special rules for after the basic validation rules. + * + * @param Validator $validator + * TODO duplicate code. + * + * @return void + */ + public function withValidator(Validator $validator): void + { + $validator->after( + function (Validator $validator) { + // validate start before end only if both are there. + $data = $validator->getData(); + if (array_key_exists('original_account', $data) && array_key_exists('destination_account', $data)) { + $repository = app(AccountRepositoryInterface::class); + $repository->setUser(auth()->user()); + $original = $repository->findNull((int)$data['original_account']); + $destination = $repository->findNull((int)$data['destination_account']); + if ($original->accountType->type !== $destination->accountType->type) { + $validator->errors()->add('title', (string)trans('validation.same_account_type')); + + return; + } + // get currency pref: + $originalCurrency = $repository->getAccountCurrency($original); + $destinationCurrency = $repository->getAccountCurrency($destination); + if (null === $originalCurrency xor null === $destinationCurrency) { + $validator->errors()->add('title', (string)trans('validation.same_account_currency')); + + return; + } + if (null === $originalCurrency && null === $destinationCurrency) { + // this is OK + return; + } + if ($originalCurrency->code !== $destinationCurrency->code) { + $validator->errors()->add('title', (string)trans('validation.same_account_currency')); + + return; + } + } + } + ); + } +} diff --git a/app/Api/V1/Requests/Insight/GenericRequest.php b/app/Api/V1/Requests/Insight/GenericRequest.php index 1f05c08a28..54f71b05a4 100644 --- a/app/Api/V1/Requests/Insight/GenericRequest.php +++ b/app/Api/V1/Requests/Insight/GenericRequest.php @@ -86,9 +86,6 @@ class GenericRequest extends FormRequest */ private function parseAccounts(): void { - if (null === $this->accounts) { - $this->accounts = new Collection; - } if (0 !== $this->accounts->count()) { return; } @@ -121,9 +118,6 @@ class GenericRequest extends FormRequest */ private function parseBills(): void { - if (null === $this->bills) { - $this->bills = new Collection; - } if (0 !== $this->bills->count()) { return; } @@ -156,9 +150,6 @@ class GenericRequest extends FormRequest */ private function parseBudgets(): void { - if (null === $this->budgets) { - $this->budgets = new Collection; - } if (0 !== $this->budgets->count()) { return; } @@ -191,9 +182,6 @@ class GenericRequest extends FormRequest */ private function parseCategories(): void { - if (null === $this->categories) { - $this->categories = new Collection; - } if (0 !== $this->categories->count()) { return; } @@ -284,9 +272,6 @@ class GenericRequest extends FormRequest */ private function parseTags(): void { - if (null === $this->tags) { - $this->tags = new Collection; - } if (0 !== $this->tags->count()) { return; } @@ -311,7 +296,7 @@ class GenericRequest extends FormRequest */ public function rules(): array { - // this is cheating but it works: + // this is cheating but it works to initialize the collections. $this->accounts = new Collection; $this->budgets = new Collection; $this->categories = new Collection; diff --git a/app/Api/V1/Requests/Models/Account/StoreRequest.php b/app/Api/V1/Requests/Models/Account/StoreRequest.php index 0049d2b350..deb9634225 100644 --- a/app/Api/V1/Requests/Models/Account/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Account/StoreRequest.php @@ -59,7 +59,7 @@ class StoreRequest extends FormRequest 'name' => $this->string('name'), 'active' => $active, 'include_net_worth' => $includeNetWorth, - 'account_type' => $this->string('type'), + 'account_type_name' => $this->string('type'), 'account_type_id' => null, 'currency_id' => $this->integer('currency_id'), 'order' => $this->integer('order'), @@ -73,17 +73,17 @@ class StoreRequest extends FormRequest 'opening_balance_date' => $this->date('opening_balance_date'), 'cc_type' => $this->string('credit_card_type'), 'cc_monthly_payment_date' => $this->string('monthly_payment_date'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'interest' => $this->string('interest'), 'interest_period' => $this->string('interest_period'), ]; // append Location information. $data = $this->appendLocationData($data, null); - if ('liability' === $data['account_type'] || 'liabilities' === $data['account_type']) { + if ('liability' === $data['account_type_name'] || 'liabilities' === $data['account_type_name']) { $data['opening_balance'] = bcmul($this->string('liability_amount'), '-1'); $data['opening_balance_date'] = $this->date('liability_start_date'); - $data['account_type'] = $this->string('liability_type'); + $data['account_type_name'] = $this->string('liability_type'); $data['account_type_id'] = null; } diff --git a/app/Api/V1/Requests/Models/Account/UpdateRequest.php b/app/Api/V1/Requests/Models/Account/UpdateRequest.php index c1c484f5f8..4b30887327 100644 --- a/app/Api/V1/Requests/Models/Account/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Account/UpdateRequest.php @@ -51,7 +51,7 @@ class UpdateRequest extends FormRequest 'name' => ['name', 'string'], 'active' => ['active', 'boolean'], 'include_net_worth' => ['include_net_worth', 'boolean'], - 'account_type' => ['type', 'string'], + 'account_type_name' => ['type', 'string'], 'virtual_balance' => ['virtual_balance', 'string'], 'iban' => ['iban', 'string'], 'BIC' => ['bic', 'string'], @@ -62,7 +62,7 @@ class UpdateRequest extends FormRequest 'opening_balance_date' => ['opening_balance_date', 'date'], 'cc_type' => ['credit_card_type', 'string'], 'cc_monthly_payment_date' => ['monthly_payment_date', 'string'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], 'interest' => ['interest', 'string'], 'interest_period' => ['interest_period', 'string'], 'order' => ['order', 'integer'], @@ -72,10 +72,10 @@ class UpdateRequest extends FormRequest $data = $this->getAllData($fields); $data = $this->appendLocationData($data, null); - if (array_key_exists('account_type', $data) && 'liability' === $data['account_type']) { - $data['opening_balance'] = bcmul($this->nullableString('liability_amount'), '-1'); + if (array_key_exists('account_type_name', $data) && 'liability' === $data['account_type_name']) { + $data['opening_balance'] = bcmul($this->string('liability_amount'), '-1'); $data['opening_balance_date'] = $this->date('liability_start_date'); - $data['account_type'] = $this->nullableString('liability_type'); + $data['account_type_name'] = $this->string('liability_type'); $data['account_type_id'] = null; } @@ -97,9 +97,9 @@ class UpdateRequest extends FormRequest $rules = [ 'name' => sprintf('min:1|uniqueAccountForUser:%d', $account->id), 'type' => sprintf('in:%s', $types), - 'iban' => ['iban', 'nullable', new UniqueIban($account, $this->nullableString('type'))], + 'iban' => ['iban', 'nullable', new UniqueIban($account, $this->string('type'))], 'bic' => 'bic|nullable', - 'account_number' => ['between:1,255', 'nullable', new UniqueAccountNumber($account, $this->nullableString('type'))], + 'account_number' => ['between:1,255', 'nullable', new UniqueAccountNumber($account, $this->string('type'))], 'opening_balance' => 'numeric|required_with:opening_balance_date|nullable', 'opening_balance_date' => 'date|required_with:opening_balance|nullable', 'virtual_balance' => 'numeric|nullable', diff --git a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php index 97c43cd933..be13081ab8 100644 --- a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php @@ -47,7 +47,7 @@ class StoreRequest extends FormRequest return [ 'filename' => $this->string('filename'), 'title' => $this->string('title'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'attachable_type' => $this->string('attachable_type'), 'attachable_id' => $this->integer('attachable_id'), ]; diff --git a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php index 3820c7cf79..cb05b390bd 100644 --- a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php @@ -47,7 +47,7 @@ class UpdateRequest extends FormRequest $fields = [ 'filename' => ['filename', 'string'], 'title' => ['title', 'string'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], 'attachable_type' => ['attachable_type', 'string'], 'attachable_id' => ['attachable_id', 'integer'], ]; diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.php index f3f0e1ed6c..88560c1077 100644 --- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php @@ -59,7 +59,7 @@ class StoreRequest extends FormRequest 'skip' => ['skip', 'integer'], 'active' => ['active', 'boolean'], 'order' => ['order', 'integer'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'integer'], 'object_group_title' => ['object_group_title', 'string'], ]; diff --git a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php index 3f01053bba..2a4a89e555 100644 --- a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php @@ -57,7 +57,7 @@ class UpdateRequest extends FormRequest 'skip' => ['skip', 'integer'], 'active' => ['active', 'boolean'], 'order' => ['order', 'integer'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'integer'], 'object_group_title' => ['object_group_title', 'string'], ]; diff --git a/app/Api/V1/Requests/Models/Category/StoreRequest.php b/app/Api/V1/Requests/Models/Category/StoreRequest.php index ddd5bc3216..b6f96bfdc9 100644 --- a/app/Api/V1/Requests/Models/Category/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Category/StoreRequest.php @@ -46,7 +46,7 @@ class StoreRequest extends FormRequest { return [ 'name' => $this->string('name'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), ]; } diff --git a/app/Api/V1/Requests/Models/Category/UpdateRequest.php b/app/Api/V1/Requests/Models/Category/UpdateRequest.php index ee0b56880c..26b9abf33e 100644 --- a/app/Api/V1/Requests/Models/Category/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Category/UpdateRequest.php @@ -45,7 +45,7 @@ class UpdateRequest extends FormRequest { $fields = [ 'name' => ['name', 'string'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], ]; return $this->getAllData($fields); diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php index e42993cea6..082f482412 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php @@ -53,7 +53,7 @@ class StoreRequest extends FormRequest $data['current_amount'] = $this->string('current_amount'); $data['startdate'] = $this->date('start_date'); $data['targetdate'] = $this->date('target_date'); - $data['notes'] = $this->nlString('notes'); + $data['notes'] = $this->stringWithNewlines('notes'); $data['object_group_id'] = $this->integer('object_group_id'); $data['object_group_title'] = $this->string('object_group_title'); diff --git a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php index e5816dc018..e41fc798bf 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php @@ -52,7 +52,7 @@ class UpdateRequest extends FormRequest 'current_amount' => ['current_amount', 'string'], 'startdate' => ['start_date', 'date'], 'targetdate' => ['target_date', 'string'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], 'order' => ['order', 'integer'], 'object_group_title' => ['object_group_title', 'string'], 'object_group_id' => ['object_group_id', 'integer'], diff --git a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php index 99a9d378e5..972952d600 100644 --- a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php @@ -58,7 +58,7 @@ class StoreRequest extends FormRequest 'nr_of_repetitions' => ['nr_of_repetitions', 'integer'], 'apply_rules' => ['apply_rules', 'boolean'], 'active' => ['active', 'boolean'], - 'notes' => ['notes', 'nlString'], + 'notes' => ['notes', 'stringWithNewlines'], ]; $recurrence = $this->getAllData($fields); @@ -79,7 +79,7 @@ class StoreRequest extends FormRequest { $return = []; // transaction data: - /** @var array $transactions */ + /** @var array|null $transactions */ $transactions = $this->get('transactions'); if (null === $transactions) { return []; @@ -101,7 +101,7 @@ class StoreRequest extends FormRequest { $return = []; // repetition data: - /** @var array $repetitions */ + /** @var array|null $repetitions */ $repetitions = $this->get('repetitions'); if (null === $repetitions) { return []; diff --git a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php index 2c76b46ad1..cab0cc29e7 100644 --- a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php @@ -84,7 +84,7 @@ class UpdateRequest extends FormRequest { $return = []; // repetition data: - /** @var array $repetitions */ + /** @var array|null $repetitions */ $repetitions = $this->get('repetitions'); if (null === $repetitions) { return null; @@ -126,7 +126,7 @@ class UpdateRequest extends FormRequest { $return = []; // transaction data: - /** @var array $transactions */ + /** @var array|null $transactions */ $transactions = $this->get('transactions'); if (null === $transactions) { return null; diff --git a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php index f047946fcb..01df50719b 100644 --- a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php @@ -47,7 +47,7 @@ class UpdateRequest extends FormRequest { $fields = [ 'title' => ['title', 'string'], - 'description' => ['description', 'nlString'], + 'description' => ['description', 'stringWithNewlines'], 'rule_group_id' => ['rule_group_id', 'integer'], 'trigger' => ['trigger', 'string'], 'strict' => ['strict', 'boolean'], diff --git a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php index 8b572a96d8..b6896b891f 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php @@ -46,7 +46,7 @@ class UpdateRequest extends FormRequest // This is the way. $fields = [ 'title' => ['title', 'string'], - 'description' => ['description', 'nlString'], + 'description' => ['description', 'stringWithNewlines'], 'active' => ['active', 'boolean'], 'order' => ['order', 'integer'], ]; diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php index 1f442eeaa6..07ffdb674d 100644 --- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php @@ -78,75 +78,75 @@ class StoreRequest extends FormRequest foreach ($this->get('transactions') as $transaction) { $object = new NullArrayObject($transaction); $return[] = [ - 'type' => $this->stringFromValue($object['type']), + 'type' => $this->clearString($object['type'], false), 'date' => $this->dateFromValue($object['date']), 'order' => $this->integerFromValue((string)$object['order']), 'currency_id' => $this->integerFromValue((string)$object['currency_id']), - 'currency_code' => $this->stringFromValue($object['currency_code']), + 'currency_code' => $this->clearString((string)$object['currency_code'], false), // foreign currency info: 'foreign_currency_id' => $this->integerFromValue((string)$object['foreign_currency_id']), - 'foreign_currency_code' => $this->stringFromValue((string)$object['foreign_currency_code']), + 'foreign_currency_code' => $this->clearString((string)$object['foreign_currency_code'], false), // amount and foreign amount. Cannot be 0. - 'amount' => $this->stringFromValue((string)$object['amount']), - 'foreign_amount' => $this->stringFromValue((string)$object['foreign_amount']), + 'amount' => $this->clearString((string)$object['amount'], false), + 'foreign_amount' => $this->clearString((string)$object['foreign_amount'], false), // description. - 'description' => $this->stringFromValue($object['description']), + 'description' => $this->clearString($object['description'], false), // source of transaction. If everything is null, assume cash account. 'source_id' => $this->integerFromValue((string)$object['source_id']), - 'source_name' => $this->stringFromValue((string)$object['source_name']), - 'source_iban' => $this->stringFromValue((string)$object['source_iban']), - 'source_number' => $this->stringFromValue((string)$object['source_number']), - 'source_bic' => $this->stringFromValue((string)$object['source_bic']), + 'source_name' => $this->clearString($object['source_name'], false), + 'source_iban' => $this->clearString($object['source_iban'], false), + 'source_number' => $this->clearString($object['source_number'], false), + 'source_bic' => $this->clearString($object['source_bic'], false), // destination of transaction. If everything is null, assume cash account. 'destination_id' => $this->integerFromValue((string)$object['destination_id']), - 'destination_name' => $this->stringFromValue((string)$object['destination_name']), - 'destination_iban' => $this->stringFromValue((string)$object['destination_iban']), - 'destination_number' => $this->stringFromValue((string)$object['destination_number']), - 'destination_bic' => $this->stringFromValue((string)$object['destination_bic']), + 'destination_name' => $this->clearString($object['destination_name'], false), + 'destination_iban' => $this->clearString($object['destination_iban'], false), + 'destination_number' => $this->clearString($object['destination_number'], false), + 'destination_bic' => $this->clearString($object['destination_bic'], false), // budget info 'budget_id' => $this->integerFromValue((string)$object['budget_id']), - 'budget_name' => $this->stringFromValue((string)$object['budget_name']), + 'budget_name' => $this->clearString((string)$object['budget_name'], false), // category info 'category_id' => $this->integerFromValue((string)$object['category_id']), - 'category_name' => $this->stringFromValue((string)$object['category_name']), + 'category_name' => $this->clearString((string)$object['category_name'], false), // journal bill reference. Optional. Will only work for withdrawals 'bill_id' => $this->integerFromValue((string)$object['bill_id']), - 'bill_name' => $this->stringFromValue((string)$object['bill_name']), + 'bill_name' => $this->clearString((string)$object['bill_name'], false), // piggy bank reference. Optional. Will only work for transfers 'piggy_bank_id' => $this->integerFromValue((string)$object['piggy_bank_id']), - 'piggy_bank_name' => $this->stringFromValue((string)$object['piggy_bank_name']), + 'piggy_bank_name' => $this->clearString((string)$object['piggy_bank_name'], false), // some other interesting properties 'reconciled' => $this->convertBoolean((string)$object['reconciled']), - 'notes' => $this->nlStringFromValue((string)$object['notes']), + 'notes' => $this->clearString((string)$object['notes']), 'tags' => $this->arrayFromValue($object['tags']), // all custom fields: - 'internal_reference' => $this->stringFromValue((string)$object['internal_reference']), - 'external_id' => $this->stringFromValue((string)$object['external_id']), + 'internal_reference' => $this->clearString((string)$object['internal_reference'], false), + 'external_id' => $this->clearString((string)$object['external_id'], false), 'original_source' => sprintf('ff3-v%s|api-v%s', config('firefly.version'), config('firefly.api_version')), 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), - 'bunq_payment_id' => $this->stringFromValue((string)$object['bunq_payment_id']), - 'external_uri' => $this->stringFromValue((string)$object['external_uri']), + 'bunq_payment_id' => $this->clearString((string)$object['bunq_payment_id'], false), + 'external_uri' => $this->clearString((string)$object['external_uri'], false), - 'sepa_cc' => $this->stringFromValue($object['sepa_cc']), - 'sepa_ct_op' => $this->stringFromValue($object['sepa_ct_op']), - 'sepa_ct_id' => $this->stringFromValue($object['sepa_ct_id']), - 'sepa_db' => $this->stringFromValue($object['sepa_db']), - 'sepa_country' => $this->stringFromValue($object['sepa_country']), - 'sepa_ep' => $this->stringFromValue($object['sepa_ep']), - 'sepa_ci' => $this->stringFromValue($object['sepa_ci']), - 'sepa_batch_id' => $this->stringFromValue($object['sepa_batch_id']), + 'sepa_cc' => $this->clearString((string)$object['sepa_cc'], false), + 'sepa_ct_op' => $this->clearString((string)$object['sepa_ct_op'], false), + 'sepa_ct_id' => $this->clearString((string)$object['sepa_ct_id'], false), + 'sepa_db' => $this->clearString((string)$object['sepa_db'], false), + 'sepa_country' => $this->clearString((string)$object['sepa_country'], false), + 'sepa_ep' => $this->clearString((string)$object['sepa_ep'], false), + 'sepa_ci' => $this->clearString((string)$object['sepa_ci'], false), + 'sepa_batch_id' => $this->clearString((string)$object['sepa_batch_id'], false), // custom date fields. Must be Carbon objects. Presence is optional. 'interest_date' => $this->dateFromValue($object['interest_date']), 'book_date' => $this->dateFromValue($object['book_date']), diff --git a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php index 21ae0d8f92..dc4a0593ce 100644 --- a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php @@ -150,10 +150,7 @@ class UpdateRequest extends FormRequest return $return; } - /** - * @var int $index - * @var array $transaction - */ + /** @var array $transaction */ foreach ($this->get('transactions') as $transaction) { // default response is to update nothing in the transaction: $current = []; @@ -197,7 +194,7 @@ class UpdateRequest extends FormRequest { foreach ($this->stringFields as $fieldName) { if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->stringFromValue((string)$transaction[$fieldName]); + $current[$fieldName] = $this->clearString((string)$transaction[$fieldName], false); } } @@ -214,7 +211,7 @@ class UpdateRequest extends FormRequest { foreach ($this->textareaFields as $fieldName) { if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->nlStringFromValue((string)$transaction[$fieldName]); + $current[$fieldName] = $this->clearString((string)$transaction[$fieldName]); } } diff --git a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php index fb7c1741b1..eaf55ed30f 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php @@ -50,7 +50,7 @@ class StoreRequest extends FormRequest 'link_type_name' => $this->string('link_type_name'), 'inward_id' => $this->integer('inward_id'), 'outward_id' => $this->integer('outward_id'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), ]; } diff --git a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php index 143c284056..51937db61a 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php @@ -50,7 +50,7 @@ class UpdateRequest extends FormRequest 'link_type_name' => $this->string('link_type_name'), 'inward_id' => $this->integer('inward_id'), 'outward_id' => $this->integer('outward_id'), - 'notes' => $this->nullableNlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), ]; } @@ -117,12 +117,6 @@ class UpdateRequest extends FormRequest $validator->errors()->add('outward_id', 'Inward ID must be different from outward ID.'); } - if (null === $inward) { - $validator->errors()->add('inward_id', 'This is not a valid inward journal.'); - } - if (null === $outward) { - $validator->errors()->add('inward_id', 'This is not a valid outward journal.'); - } $inDB = $repository->findSpecificLink($existing->linkType, $inward, $outward); if (null === $inDB) { return; diff --git a/app/Api/V1/Requests/System/UpdateRequest.php b/app/Api/V1/Requests/System/UpdateRequest.php index a123e5477a..3386d17165 100644 --- a/app/Api/V1/Requests/System/UpdateRequest.php +++ b/app/Api/V1/Requests/System/UpdateRequest.php @@ -57,7 +57,7 @@ class UpdateRequest extends FormRequest return ['value' => $this->integer('value')]; } - return ['value' => $this->string('value')]; // @codeCoverageIgnore + return ['value' => $this->string('value')]; } /** @@ -80,6 +80,6 @@ class UpdateRequest extends FormRequest return ['value' => 'required|numeric|min:464272080']; } - return ['value' => 'required']; // @codeCoverageIgnore + return ['value' => 'required']; } } diff --git a/app/Console/Commands/Correction/DeleteEmptyJournals.php b/app/Console/Commands/Correction/DeleteEmptyJournals.php index 01aa71d030..7fe3f66778 100644 --- a/app/Console/Commands/Correction/DeleteEmptyJournals.php +++ b/app/Console/Commands/Correction/DeleteEmptyJournals.php @@ -77,11 +77,11 @@ class DeleteEmptyJournals extends Command // uneven number, delete journal and transactions: try { TransactionJournal::find((int)$row->transaction_journal_id)->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::info(sprintf('Could not delete journal: %s', $e->getMessage())); } - // @codeCoverageIgnoreEnd + Transaction::where('transaction_journal_id', (int)$row->transaction_journal_id)->delete(); $this->info(sprintf('Deleted transaction journal #%d because it had an uneven number of transactions.', $row->transaction_journal_id)); @@ -105,11 +105,11 @@ class DeleteEmptyJournals extends Command foreach ($set as $entry) { try { TransactionJournal::find($entry->id)->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::info(sprintf('Could not delete entry: %s', $e->getMessage())); } - // @codeCoverageIgnoreEnd + $this->info(sprintf('Deleted empty transaction journal #%d', $entry->id)); ++$count; diff --git a/app/Console/Commands/Correction/DeleteOrphanedTransactions.php b/app/Console/Commands/Correction/DeleteOrphanedTransactions.php index 71085e35b2..114353aff9 100644 --- a/app/Console/Commands/Correction/DeleteOrphanedTransactions.php +++ b/app/Console/Commands/Correction/DeleteOrphanedTransactions.php @@ -118,11 +118,11 @@ class DeleteOrphanedTransactions extends Command if ($journal) { try { $journal->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::info(sprintf('Could not delete journal %s', $e->getMessage())); } - // @codeCoverageIgnoreEnd + } Transaction::where('transaction_journal_id', (int)$transaction->transaction_journal_id)->delete(); $this->line( diff --git a/app/Console/Commands/Correction/DeleteZeroAmount.php b/app/Console/Commands/Correction/DeleteZeroAmount.php index f96b426eee..9e99cb5573 100644 --- a/app/Console/Commands/Correction/DeleteZeroAmount.php +++ b/app/Console/Commands/Correction/DeleteZeroAmount.php @@ -64,11 +64,11 @@ class DeleteZeroAmount extends Command $this->info(sprintf('Deleted transaction journal #%d because the amount is zero (0.00).', $journal->id)); try { $journal->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line $this->line($e->getMessage()); } - // @codeCoverageIgnoreEnd + Transaction::where('transaction_journal_id', $journal->id)->delete(); } if (0 === $journals->count()) { diff --git a/app/Console/Commands/Correction/FixAccountTypes.php b/app/Console/Commands/Correction/FixAccountTypes.php index 5736970505..048c32d9b5 100644 --- a/app/Console/Commands/Correction/FixAccountTypes.php +++ b/app/Console/Commands/Correction/FixAccountTypes.php @@ -121,12 +121,12 @@ class FixAccountTypes extends Command $destAccountType = $destAccount->accountType->type; if (!array_key_exists($type, $this->expected)) { - // @codeCoverageIgnoreStart + Log::info(sprintf('No source/destination info for transaction type %s.', $type)); $this->info(sprintf('No source/destination info for transaction type %s.', $type)); return; - // @codeCoverageIgnoreEnd + } if (!array_key_exists($sourceAccountType, $this->expected[$type])) { Log::debug(sprintf('Going to fix journal #%d', $journal->id)); diff --git a/app/Console/Commands/Correction/FixPiggies.php b/app/Console/Commands/Correction/FixPiggies.php index 274e5265b4..8076663b95 100644 --- a/app/Console/Commands/Correction/FixPiggies.php +++ b/app/Console/Commands/Correction/FixPiggies.php @@ -70,14 +70,14 @@ class FixPiggies extends Command } /** @var TransactionJournal $journal */ $journal = $event->transactionJournal; - // @codeCoverageIgnoreStart + if (null === $journal) { $event->transaction_journal_id = null; $event->save(); $this->count++; continue; } - // @codeCoverageIgnoreEnd + $type = $journal->transactionType->type; if (TransactionType::TRANSFER !== $type) { diff --git a/app/Console/Commands/Correction/FixUnevenAmount.php b/app/Console/Commands/Correction/FixUnevenAmount.php index 28b28ab7e9..157e955164 100644 --- a/app/Console/Commands/Correction/FixUnevenAmount.php +++ b/app/Console/Commands/Correction/FixUnevenAmount.php @@ -91,7 +91,7 @@ class FixUnevenAmount extends Command // one of the transactions is bad. $journal = TransactionJournal::find($param); if (!$journal) { - return; // @codeCoverageIgnore + return; } /** @var Transaction $source */ $source = $journal->transactions()->where('amount', '<', 0)->first(); diff --git a/app/Console/Commands/DecryptDatabase.php b/app/Console/Commands/DecryptDatabase.php index 41e8004fa8..a9e8cfb548 100644 --- a/app/Console/Commands/DecryptDatabase.php +++ b/app/Console/Commands/DecryptDatabase.php @@ -188,7 +188,7 @@ class DecryptDatabase extends Command $value = Crypt::decrypt($value); } catch (DecryptException $e) { if ('The MAC is invalid.' === $e->getMessage()) { - throw new FireflyException($e->getMessage()); // @codeCoverageIgnore + throw new FireflyException($e->getMessage(), 0, $e); } } diff --git a/app/Console/Commands/Export/ExportData.php b/app/Console/Commands/Export/ExportData.php index d5da37c14a..5f70ddef59 100644 --- a/app/Console/Commands/Export/ExportData.php +++ b/app/Console/Commands/Export/ExportData.php @@ -124,11 +124,11 @@ class ExportData extends Command $exporter->setExportBills($options['export']['bills']); $exporter->setExportPiggies($options['export']['piggies']); $data = $exporter->export(); - if (empty($data)) { + if (0===count($data)) { $this->error('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org'); } $returnCode = 0; - if (!empty($data)) { + if (0!== count($data)) { try { $this->exportData($options, $data); app('telemetry')->feature('system.command.executed', $this->signature); diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index d01e63fba3..dba8126ab7 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -214,14 +214,6 @@ class ApplyRules extends Command $finalList = new Collection; $accountList = explode(',', $accountString); - // @codeCoverageIgnoreStart - if (0 === count($accountList)) { - $this->error('Please use the --accounts option to indicate the accounts to apply rules to.'); - - return false; - } - // @codeCoverageIgnoreEnd - /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); $accountRepository->setUser($this->getUser()); @@ -255,12 +247,7 @@ class ApplyRules extends Command return true; } $ruleGroupList = explode(',', $ruleGroupString); - // @codeCoverageIgnoreStart - if (0 === count($ruleGroupList)) { - // can be empty. - return true; - } - // @codeCoverageIgnoreEnd + foreach ($ruleGroupList as $ruleGroupId) { $ruleGroup = $this->ruleGroupRepository->find((int)$ruleGroupId); if ($ruleGroup->active) { @@ -286,14 +273,6 @@ class ApplyRules extends Command } $ruleList = explode(',', $ruleString); - // @codeCoverageIgnoreStart - if (0 === count($ruleList)) { - // can be empty. - - return true; - } - // @codeCoverageIgnoreEnd - foreach ($ruleList as $ruleId) { $rule = $this->ruleRepository->find((int)$ruleId); if (null !== $rule && $rule->active) { diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index d65dc729fc..a1746a2ffa 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -65,9 +65,8 @@ class Cron extends Command $date = null; try { $date = new Carbon($this->option('date')); - } catch (InvalidArgumentException | Exception $e) { + } catch (InvalidArgumentException $e) { $this->error(sprintf('"%s" is not a valid date', $this->option('date'))); - $e->getMessage(); } $force = (bool)$this->option('force'); @@ -127,13 +126,15 @@ class Cron extends Command $recurring->setDate($date); } - $result = $recurring->fire(); - - if (false === $result) { - $this->line('The recurring transaction cron job did not fire.'); + $recurring->fire(); + if($recurring->jobErrored) { + $this->error(sprintf('Error in "create recurring transactions" cron: %s', $recurring->message)); } - if (true === $result) { - $this->line('The recurring transaction cron job fired successfully.'); + if($recurring->jobFired) { + $this->error(sprintf('"Create recurring transactions" cron fired: %s', $recurring->message)); + } + if($recurring->jobSucceeded) { + $this->error(sprintf('"Create recurring transactions" cron ran with success: %s', $recurring->message)); } } @@ -142,7 +143,6 @@ class Cron extends Command * @param Carbon|null $date * * @throws FireflyException - * @throws Exception */ private function autoBudgetCronJob(bool $force, ?Carbon $date): void { @@ -153,13 +153,16 @@ class Cron extends Command $autoBudget->setDate($date); } - $result = $autoBudget->fire(); + $autoBudget->fire(); - if (false === $result) { - $this->line('The auto budget cron job did not fire.'); + if($autoBudget->jobErrored) { + $this->error(sprintf('Error in "create auto budgets" cron: %s', $autoBudget->message)); } - if (true === $result) { - $this->line('The auto budget cron job fired successfully.'); + if($autoBudget->jobFired) { + $this->error(sprintf('"Create auto budgets" cron fired: %s', $autoBudget->message)); + } + if($autoBudget->jobSucceeded) { + $this->error(sprintf('"Create auto budgets" cron ran with success: %s', $autoBudget->message)); } } @@ -167,6 +170,8 @@ class Cron extends Command /** * @param bool $force * @param Carbon|null $date + * + * @throws FireflyException */ private function telemetryCronJob(bool $force, ?Carbon $date): void { @@ -182,13 +187,16 @@ class Cron extends Command $telemetry->setDate($date); } - $result = $telemetry->fire(); + $telemetry->fire(); - if (false === $result) { - $this->line('The telemetry cron job did not fire.'); + if($telemetry->jobErrored) { + $this->error(sprintf('Error in "send telemetry" cron: %s', $telemetry->message)); } - if (true === $result) { - $this->line('The telemetry cron job fired successfully.'); + if($telemetry->jobFired) { + $this->error(sprintf('"Send telemetry" cron fired: %s', $telemetry->message)); + } + if($telemetry->jobSucceeded) { + $this->error(sprintf('"Send telemetry" cron ran with success: %s', $telemetry->message)); } } diff --git a/app/Console/Commands/Upgrade/AccountCurrencies.php b/app/Console/Commands/Upgrade/AccountCurrencies.php index 3c9a11bad7..78197894f9 100644 --- a/app/Console/Commands/Upgrade/AccountCurrencies.php +++ b/app/Console/Commands/Upgrade/AccountCurrencies.php @@ -114,7 +114,7 @@ class AccountCurrencies extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** @@ -148,7 +148,7 @@ class AccountCurrencies extends Command } Log::debug(sprintf('Users currency pref is %s', $defaultCurrencyCode)); - /** @var TransactionCurrency $defaultCurrency */ + /** @var TransactionCurrency|null $defaultCurrency */ $defaultCurrency = TransactionCurrency::where('code', $defaultCurrencyCode)->first(); if (null === $defaultCurrency) { diff --git a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php index b3fb1a3bc2..3f495c2c74 100644 --- a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php +++ b/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php @@ -73,11 +73,8 @@ class AppendBudgetLimitPeriods extends Command private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - if (null !== $configVar) { - return (bool)$configVar->data; - } - return false; // @codeCoverageIgnore + return (bool)$configVar->data; } /** diff --git a/app/Console/Commands/Upgrade/BackToJournals.php b/app/Console/Commands/Upgrade/BackToJournals.php index a499a83009..10522e030c 100644 --- a/app/Console/Commands/Upgrade/BackToJournals.php +++ b/app/Console/Commands/Upgrade/BackToJournals.php @@ -58,7 +58,7 @@ class BackToJournals extends Command */ public function handle(): int { - // @codeCoverageIgnoreStart + $start = microtime(true); if (!$this->isMigrated()) { $this->error('Please run firefly-iii:migrate-to-groups first.'); @@ -71,7 +71,7 @@ class BackToJournals extends Command if (true === $this->option('force')) { $this->warn('Forcing the command.'); } - // @codeCoverageIgnoreEnd + $this->migrateAll(); $end = round(microtime(true) - $start, 2); @@ -87,11 +87,8 @@ class BackToJournals extends Command private function isMigrated(): bool { $configVar = app('fireflyconfig')->get(MigrateToGroups::CONFIG_NAME, false); - if (null !== $configVar) { - return (bool)$configVar->data; - } - return false; // @codeCoverageIgnore + return (bool)$configVar->data; } /** @@ -100,11 +97,8 @@ class BackToJournals extends Command private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - if (null !== $configVar) { - return (bool)$configVar->data; - } - return false; // @codeCoverageIgnore + return (bool)$configVar->data; } /** @@ -145,15 +139,13 @@ class BackToJournals extends Command */ private function getIdsForBudgets(): array { - $transactions = DB::table('budget_transaction')->distinct()->get(['transaction_id'])->pluck('transaction_id')->toArray(); + $transactions = DB::table('budget_transaction')->distinct()->get(['transaction_id'])->pluck('transaction_id')->toArray(); // @phpstan-ignore-line $array = []; $chunks = array_chunk($transactions, 500); foreach ($chunks as $chunk) { - $set = DB::table('transactions') - ->whereIn('transactions.id', $chunk) + $set = DB::table('transactions')->whereIn('transactions.id', $chunk) ->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); - /** @noinspection SlowArrayOperationsInLoopInspection */ $array = array_merge($array, $set); } @@ -170,11 +162,11 @@ class BackToJournals extends Command /** @var Transaction $transaction */ $transaction = $journal->transactions->first(); if (null === $transaction) { - // @codeCoverageIgnoreStart + $this->info(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); return; - // @codeCoverageIgnoreEnd + } /** @var Budget $budget */ $budget = $transaction->budgets->first(); @@ -225,12 +217,12 @@ class BackToJournals extends Command */ private function getIdsForCategories(): array { - $transactions = DB::table('category_transaction')->distinct()->get(['transaction_id'])->pluck('transaction_id')->toArray(); + $transactions = DB::table('category_transaction')->distinct()->get(['transaction_id'])->pluck('transaction_id')->toArray(); // @phpstan-ignore-line $array = []; $chunks = array_chunk($transactions, 500); foreach ($chunks as $chunk) { - $set = DB::table('transactions') + $set = DB::table('transactions') // @phpstan-ignore-line ->whereIn('transactions.id', $chunk) ->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); /** @noinspection SlowArrayOperationsInLoopInspection */ @@ -249,11 +241,11 @@ class BackToJournals extends Command /** @var Transaction $transaction */ $transaction = $journal->transactions->first(); if (null === $transaction) { - // @codeCoverageIgnoreStart + $this->info(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); return; - // @codeCoverageIgnoreEnd + } /** @var Category $category */ $category = $transaction->categories->first(); diff --git a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php b/app/Console/Commands/Upgrade/BudgetLimitCurrency.php index 0867427b99..9aed01b7f8 100644 --- a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php +++ b/app/Console/Commands/Upgrade/BudgetLimitCurrency.php @@ -54,13 +54,13 @@ class BudgetLimitCurrency extends Command public function handle(): int { $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $count = 0; $budgetLimits = BudgetLimit::get(); @@ -104,7 +104,7 @@ class BudgetLimitCurrency extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/CCLiabilities.php b/app/Console/Commands/Upgrade/CCLiabilities.php index e5736d230f..64e596e75a 100644 --- a/app/Console/Commands/Upgrade/CCLiabilities.php +++ b/app/Console/Commands/Upgrade/CCLiabilities.php @@ -56,13 +56,13 @@ class CCLiabilities extends Command { $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $ccType = AccountType::where('type', AccountType::CREDITCARD)->first(); $debtType = AccountType::where('type', AccountType::DEBT)->first(); @@ -101,7 +101,7 @@ class CCLiabilities extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/MigrateAttachments.php b/app/Console/Commands/Upgrade/MigrateAttachments.php index 512adf9562..3c35ac9415 100644 --- a/app/Console/Commands/Upgrade/MigrateAttachments.php +++ b/app/Console/Commands/Upgrade/MigrateAttachments.php @@ -54,14 +54,14 @@ class MigrateAttachments extends Command */ public function handle(): int { - // @codeCoverageIgnoreStart + $start = microtime(true); if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $attachments = Attachment::get(); $count = 0; @@ -113,7 +113,7 @@ class MigrateAttachments extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/MigrateJournalNotes.php b/app/Console/Commands/Upgrade/MigrateJournalNotes.php index 685e1a77a4..2eb21a5d0f 100644 --- a/app/Console/Commands/Upgrade/MigrateJournalNotes.php +++ b/app/Console/Commands/Upgrade/MigrateJournalNotes.php @@ -56,13 +56,13 @@ class MigrateJournalNotes extends Command public function handle(): int { $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $count = 0; /** @noinspection PhpUndefinedMethodInspection */ $set = TransactionJournalMeta::whereName('notes')->get(); @@ -80,11 +80,11 @@ class MigrateJournalNotes extends Command Log::debug(sprintf('Migrated meta note #%d to Note #%d', $meta->id, $note->id)); try { $meta->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error(sprintf('Could not delete old meta entry #%d: %s', $meta->id, $e->getMessage())); } - // @codeCoverageIgnoreEnd + $count++; } @@ -112,7 +112,7 @@ class MigrateJournalNotes extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php index bb1365ac8f..857f4fbb09 100644 --- a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php +++ b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php @@ -87,7 +87,7 @@ class MigrateRecurrenceMeta extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php b/app/Console/Commands/Upgrade/MigrateRecurrenceType.php index 51d32603c1..0c5f1eb795 100644 --- a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php +++ b/app/Console/Commands/Upgrade/MigrateRecurrenceType.php @@ -82,7 +82,7 @@ class MigrateRecurrenceType extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/MigrateTagLocations.php b/app/Console/Commands/Upgrade/MigrateTagLocations.php index b201db99f2..9b8f41594c 100644 --- a/app/Console/Commands/Upgrade/MigrateTagLocations.php +++ b/app/Console/Commands/Upgrade/MigrateTagLocations.php @@ -80,7 +80,7 @@ class MigrateTagLocations extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } private function migrateTagLocations(): void diff --git a/app/Console/Commands/Upgrade/MigrateToGroups.php b/app/Console/Commands/Upgrade/MigrateToGroups.php index 48f5d709f4..7511eac1ff 100644 --- a/app/Console/Commands/Upgrade/MigrateToGroups.php +++ b/app/Console/Commands/Upgrade/MigrateToGroups.php @@ -75,7 +75,7 @@ class MigrateToGroups extends Command { $this->stupidLaravel(); $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isMigrated() && true !== $this->option('force')) { $this->info('Database already seems to be migrated.'); @@ -85,7 +85,7 @@ class MigrateToGroups extends Command if (true === $this->option('force')) { $this->warn('Forcing the migration.'); } - // @codeCoverageIgnoreEnd + Log::debug('---- start group migration ----'); $this->makeGroupsFromSplitJournals(); @@ -135,7 +135,7 @@ class MigrateToGroups extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** @@ -165,11 +165,11 @@ class MigrateToGroups extends Command { // double check transaction count. if ($journal->transactions->count() <= 2) { - // @codeCoverageIgnoreStart + Log::debug(sprintf('Will not try to convert journal #%d because it has 2 or less transactions.', $journal->id)); return; - // @codeCoverageIgnoreEnd + } Log::debug(sprintf('Will now try to convert journal #%d', $journal->id)); @@ -217,7 +217,7 @@ class MigrateToGroups extends Command $opposingTr = $this->findOpposingTransaction($journal, $transaction); if (null === $opposingTr) { - // @codeCoverageIgnoreStart + $this->error( sprintf( 'Journal #%d has no opposing transaction for transaction #%d. Cannot upgrade this entry.', @@ -226,7 +226,7 @@ class MigrateToGroups extends Command ) ); continue; - // @codeCoverageIgnoreEnd + } // overrule journal category with transaction category. diff --git a/app/Console/Commands/Upgrade/MigrateToRules.php b/app/Console/Commands/Upgrade/MigrateToRules.php index 44024e4077..8f923915d1 100644 --- a/app/Console/Commands/Upgrade/MigrateToRules.php +++ b/app/Console/Commands/Upgrade/MigrateToRules.php @@ -73,13 +73,13 @@ class MigrateToRules extends Command $this->stupidLaravel(); $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $users = $this->userRepository->all(); /** @var User $user */ @@ -127,7 +127,7 @@ class MigrateToRules extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php index f274d63087..a06f6a6401 100644 --- a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php @@ -75,13 +75,13 @@ class OtherCurrenciesCorrections extends Command { $this->stupidLaravel(); $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $this->updateOtherJournalsCurrencies(); $this->markAsExecuted(); @@ -120,7 +120,7 @@ class OtherCurrenciesCorrections extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** @@ -154,18 +154,18 @@ class OtherCurrenciesCorrections extends Command $leadTransaction = $this->getLeadTransaction($journal); if (null === $leadTransaction) { - // @codeCoverageIgnoreStart + $this->error(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id)); return; - // @codeCoverageIgnoreEnd + } /** @var Account $account */ $account = $leadTransaction->account; $currency = $this->getCurrency($account); if (null === $currency) { - // @codeCoverageIgnoreStart + $this->error( sprintf( 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected', $account->id, $account->name, $journal->id @@ -174,7 +174,7 @@ class OtherCurrenciesCorrections extends Command $this->count++; return; - // @codeCoverageIgnoreEnd + } // fix each transaction: $journal->transactions->each( @@ -246,18 +246,18 @@ class OtherCurrenciesCorrections extends Command { $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { - return null; // @codeCoverageIgnore + return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { - return $this->accountCurrencies[$accountId]; // @codeCoverageIgnore + return $this->accountCurrencies[$accountId]; } $currency = $this->accountRepos->getAccountCurrency($account); if (null === $currency) { - // @codeCoverageIgnoreStart + $this->accountCurrencies[$accountId] = 0; return null; - // @codeCoverageIgnoreEnd + } $this->accountCurrencies[$accountId] = $currency; diff --git a/app/Console/Commands/Upgrade/RenameAccountMeta.php b/app/Console/Commands/Upgrade/RenameAccountMeta.php index 9e12c60d7b..37f86dd6cc 100644 --- a/app/Console/Commands/Upgrade/RenameAccountMeta.php +++ b/app/Console/Commands/Upgrade/RenameAccountMeta.php @@ -53,13 +53,13 @@ class RenameAccountMeta extends Command public function handle(): int { $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $array = [ 'accountRole' => 'account_role', 'ccType' => 'cc_type', @@ -104,7 +104,7 @@ class RenameAccountMeta extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/Console/Commands/Upgrade/TransactionIdentifier.php b/app/Console/Commands/Upgrade/TransactionIdentifier.php index 3628af9d9c..c9fd6bb629 100644 --- a/app/Console/Commands/Upgrade/TransactionIdentifier.php +++ b/app/Console/Commands/Upgrade/TransactionIdentifier.php @@ -72,7 +72,7 @@ class TransactionIdentifier extends Command { $this->stupidLaravel(); $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); @@ -83,7 +83,7 @@ class TransactionIdentifier extends Command if (!Schema::hasTable('transaction_journals')) { return 0; } - // @codeCoverageIgnoreEnd + $journals = $this->cliRepository->getSplitJournals(); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { @@ -128,7 +128,7 @@ class TransactionIdentifier extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** @@ -178,7 +178,7 @@ class TransactionIdentifier extends Command ->where('amount', $amount)->where('identifier', '=', 0) ->whereNotIn('id', $exclude) ->first(); - // @codeCoverageIgnoreStart + } catch (QueryException $e) { Log::error($e->getMessage()); $this->error('Firefly III could not find the "identifier" field in the "transactions" table.'); @@ -188,9 +188,6 @@ class TransactionIdentifier extends Command return null; } - - // @codeCoverageIgnoreEnd - return $opposing; } diff --git a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php index 9524a85c4a..777b671b1b 100644 --- a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php @@ -72,13 +72,13 @@ class TransferCurrenciesCorrections extends Command { $this->stupidLaravel(); $start = microtime(true); - // @codeCoverageIgnoreStart + if ($this->isExecuted() && true !== $this->option('force')) { $this->warn('This command has already been executed.'); return 0; } - // @codeCoverageIgnoreEnd + $this->startUpdateRoutine(); $this->markAsExecuted(); @@ -140,7 +140,7 @@ class TransferCurrenciesCorrections extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } /** @@ -167,27 +167,27 @@ class TransferCurrenciesCorrections extends Command { $this->resetInformation(); - // @codeCoverageIgnoreStart + if ($this->isSplitJournal($transfer)) { $this->line(sprintf(sprintf('Transaction journal #%d is a split journal. Cannot continue.', $transfer->id))); return; } - // @codeCoverageIgnoreEnd + $this->getSourceInformation($transfer); $this->getDestinationInformation($transfer); // unexpectedly, either one is null: - // @codeCoverageIgnoreStart + if ($this->isEmptyTransactions()) { $this->error(sprintf('Source or destination information for transaction journal #%d is null. Cannot fix this one.', $transfer->id)); return; } - // @codeCoverageIgnoreEnd + // both accounts must have currency preference: - // @codeCoverageIgnoreStart + if ($this->isNoCurrencyPresent()) { $this->error( sprintf('Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.', $transfer->id) @@ -195,7 +195,7 @@ class TransferCurrenciesCorrections extends Command return; } - // @codeCoverageIgnoreEnd + // fix source transaction having no currency. $this->fixSourceNoCurrency(); @@ -270,18 +270,18 @@ class TransferCurrenciesCorrections extends Command { $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { - return null; // @codeCoverageIgnore + return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { - return $this->accountCurrencies[$accountId]; // @codeCoverageIgnore + return $this->accountCurrencies[$accountId]; } $currency = $this->accountRepos->getAccountCurrency($account); if (null === $currency) { - // @codeCoverageIgnoreStart + $this->accountCurrencies[$accountId] = 0; return null; - // @codeCoverageIgnoreEnd + } $this->accountCurrencies[$accountId] = $currency; diff --git a/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub b/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub index 2ea03dbe8d..34d9ef22f0 100644 --- a/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub +++ b/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub @@ -56,7 +56,7 @@ class UpgradeSkeleton extends Command return (bool)$configVar->data; } - return false; // @codeCoverageIgnore + return false; } diff --git a/app/Console/Commands/UpgradeFireflyInstructions.php b/app/Console/Commands/UpgradeFireflyInstructions.php index b178a1f6ab..5c4903f0d6 100644 --- a/app/Console/Commands/UpgradeFireflyInstructions.php +++ b/app/Console/Commands/UpgradeFireflyInstructions.php @@ -73,7 +73,7 @@ class UpgradeFireflyInstructions extends Command try { app('telemetry')->feature('system.users.count', (string)User::count()); } catch (QueryException $e) { - // ignore error. + // @ignoreException } return 0; diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index b6f527c6e5..5d5940b711 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -27,15 +27,17 @@ declare(strict_types=1); namespace FireflyIII\Exceptions; use ErrorException; -use Exception; use FireflyIII\Jobs\MailError; use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Http\Request; +use Illuminate\Session\TokenMismatchException; use Illuminate\Support\Arr; use Illuminate\Validation\ValidationException as LaravelValidationException; use League\OAuth2\Server\Exception\OAuthServerException; +use Laravel\Passport\Exceptions\OAuthServerException as LaravelOAuthException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Symfony\Component\HttpKernel\Exception\HttpException; use Throwable; /** @@ -52,6 +54,11 @@ class Handler extends ExceptionHandler = [ AuthenticationException::class, LaravelValidationException::class, + NotFoundHttpException::class, + OAuthServerException::class, + LaravelOAuthException::class, + TokenMismatchException::class, + HttpException::class ]; /** diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index e755820b98..e4d3394f34 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -57,12 +57,11 @@ class AccountFactory */ public function __construct() { - $this->canHaveVirtual = [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD]; $this->accountRepository = app(AccountRepositoryInterface::class); - $this->validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; - $this->validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; - $this->validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth']; - + $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); } /** @@ -74,16 +73,26 @@ class AccountFactory */ public function findOrCreate(string $accountName, string $accountType): Account { - Log::debug(sprintf('Searching for "%s" of type "%s"', $accountName, $accountType)); - /** @var AccountType $type */ - $type = AccountType::whereType($accountType)->first(); + Log::debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); + + $type = $this->accountRepository->getAccountTypeByType($accountType); + if (null === $type) { + throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType)); + } $return = $this->user->accounts->where('account_type_id', $type->id)->where('name', $accountName)->first(); if (null === $return) { Log::debug('Found nothing. Will create a new one.'); $return = $this->create( - ['user_id' => $this->user->id, 'name' => $accountName, 'account_type_id' => $type->id, 'account_type' => null, 'virtual_balance' => '0', - 'iban' => null, 'active' => true,] + [ + 'user_id' => $this->user->id, + 'name' => $accountName, + 'account_type_id' => $type->id, + 'account_type_name' => null, + 'virtual_balance' => '0', + 'iban' => null, + 'active' => true, + ] ); } @@ -98,118 +107,51 @@ class AccountFactory */ public function create(array $data): Account { - $type = $this->getAccountType($data['account_type_id'] ?? null, $data['account_type'] ?? null); - if (null === $type) { - throw new FireflyException( - sprintf('AccountFactory::create() was unable to find account type #%d ("%s").', $data['account_type_id'] ?? null, $data['account_type'] ?? null) - ); - } - + $type = $this->getAccountType($data); $data['iban'] = $this->filterIban($data['iban'] ?? null); // account may exist already: - Log::debug('Data array is as follows', $data); $return = $this->find($data['name'], $type->type); if (null === $return) { - $this->accountRepository->resetAccountOrder(); - - // create it: - $databaseData = ['user_id' => $this->user->id, - 'account_type_id' => $type->id, - 'name' => $data['name'], - 'order' => 25000, - 'virtual_balance' => $data['virtual_balance'] ?? null, 'active' => true === $data['active'], 'iban' => $data['iban'],]; - - $currency = $this->getCurrency((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)); - unset($data['currency_code']); - $data['currency_id'] = $currency->id; - - // remove virtual balance when not an asset account or a liability - if (!in_array($type->type, $this->canHaveVirtual, true)) { - $databaseData['virtual_balance'] = null; - } - - // fix virtual balance when it's empty - if ('' === (string)$databaseData['virtual_balance']) { - $databaseData['virtual_balance'] = null; - } - - $return = Account::create($databaseData); - $this->updateMetaData($return, $data); - - // if it can have a virtual balance, it can also have an opening balance. - if (in_array($type->type, $this->canHaveVirtual, true)) { - if ($this->validOBData($data)) { - $this->updateOBGroup($return, $data); - } - if (!$this->validOBData($data)) { - $this->deleteOBGroup($return); - } - } - $this->updateNote($return, $data['notes'] ?? ''); - - // store location - $this->storeNewLocation($return, $data); - - // update order to be correct: - - // set new order: - $maxOrder = $this->accountRepository->maxOrder($type->type); - $order = null; - if (!array_key_exists('order', $data)) { - // take maxOrder + 1 - $order = $maxOrder + 1; - } - if (array_key_exists('order', $data)) { - // limit order - $order = (int)($data['order'] > $maxOrder ? $maxOrder + 1 : $data['order']); - $order = 0 === $order ? $maxOrder + 1 : $order; - } - $updateService = app(AccountUpdateService::class); - $updateService->setUser($return->user); - Log::debug(sprintf('Will set order to %d', $order)); - $return = $updateService->update($return, ['order' => $order]); + $return = $this->createAccount($type, $data); } return $return; } /** - * @param int|null $accountTypeId - * @param null|string $accountType + * @param array $data * * @return AccountType|null */ - protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType + protected function getAccountType(array $data): ?AccountType { - $accountTypeId = (int)$accountTypeId; - $result = null; + $accountTypeId = array_key_exists('account_type_id', $data) ? (int)$data['account_type_id'] : 0; + $accountTypeName = array_key_exists('account_type_name', $data) ? $data['account_type_name'] : null; + $result = null; + // find by name or ID if ($accountTypeId > 0) { $result = AccountType::find($accountTypeId); } + if (null !== $accountTypeName) { + $result = $this->accountRepository->getAccountTypeByType($accountTypeName); + } + + // try with type: if (null === $result) { - Log::debug(sprintf('No account type found by ID, continue search for "%s".', $accountType)); - /** @var array $types */ - $types = config('firefly.accountTypeByIdentifier.' . $accountType) ?? []; + $types = config(sprintf('firefly.accountTypeByIdentifier.%s', $accountTypeName)) ?? []; if (count($types) > 0) { - Log::debug(sprintf('%d accounts in list from config', count($types)), $types); $result = AccountType::whereIn('type', $types)->first(); } - if (null === $result && null !== $accountType) { - // try as full name: - $result = AccountType::whereType($accountType)->first(); - } } if (null === $result) { - Log::warning(sprintf('Found NO account type based on %d and "%s"', $accountTypeId, $accountType)); - } - if (null !== $result) { - Log::debug(sprintf('Found account type based on %d and "%s": "%s"', $accountTypeId, $accountType, $result->type)); + Log::warning(sprintf('Found NO account type based on %d and "%s"', $accountTypeId, $accountTypeName)); + throw new FireflyException(sprintf('AccountFactory::create() was unable to find account type #%d ("%s").', $accountTypeId, $accountTypeName)); } + Log::debug(sprintf('Found account type based on %d and "%s": "%s"', $accountTypeId, $accountTypeName, $result->type)); return $result; - } /** @@ -225,11 +167,168 @@ class AccountFactory return $this->user->accounts()->where('account_type_id', $type->id)->where('name', $accountName)->first(); } + /** + * @param array $data + * + * @return Account + */ + private function createAccount(AccountType $type, array $data): Account + { + $this->accountRepository->resetAccountOrder(); + + // create it: + $virtualBalance = array_key_exists('virtual_balance', $data) ? $data['virtual_balance'] : null; + $active = array_key_exists('active', $data) ? $data['active'] : true; + $databaseData = ['user_id' => $this->user->id, + 'account_type_id' => $type->id, + 'name' => $data['name'], + 'order' => 25000, + 'virtual_balance' => $virtualBalance, + 'active' => $active, + 'iban' => $data['iban'], + ]; + // fix virtual balance when it's empty + if ('' === (string)$databaseData['virtual_balance']) { + $databaseData['virtual_balance'] = null; + } + // remove virtual balance when not an asset account or a liability + if (!in_array($type->type, $this->canHaveVirtual, true)) { + $databaseData['virtual_balance'] = null; + } + // create account! + $account = Account::create($databaseData); + + // update meta data: + $data = $this->cleanMetaDataArray($account, $data); + $this->storeMetaData($account, $data); + + // create opening balance + $this->storeOpeningBalance($account, $data); + + // create notes + $notes = array_key_exists('notes', $data) ? $data['notes'] : ''; + $this->updateNote($account, $notes); + + // create location + $this->storeNewLocation($account, $data); + + // set order + $this->storeOrder($account, $data); + + // refresh and return + $account->refresh(); + + return $account; + } + + /** + * @param Account $account + * @param array $data + * + * @return array + */ + private function cleanMetaDataArray(Account $account, array $data): array + { + $currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0; + $currencyCode = array_key_exists('currency_code', $data) ? (string)$data['currency_code'] : ''; + $accountRole = array_key_exists('account_role', $data) ? (string)$data['account_role'] : null; + $currency = $this->getCurrency($currencyId, $currencyCode); + + // only asset account may have a role: + if ($account->accountType->type !== AccountType::ASSET) { + $accountRole = ''; + } + + $data['account_role'] = $accountRole; + $data['currency_id'] = $currency->id; + + return $data; + } + + /** + * @param Account $account + * @param array $data + */ + private function storeMetaData(Account $account, array $data): void + { + + $fields = $this->validFields; + if ($account->accountType->type === AccountType::ASSET) { + $fields = $this->validAssetFields; + } + if ($account->accountType->type === AccountType::ASSET && 'ccAsset' === $data['account_role']) { + $fields = $this->validCCFields; + } + + /** @var AccountMetaFactory $factory */ + $factory = app(AccountMetaFactory::class); + foreach ($fields as $field) { + // if the field is set but NULL, skip it. + // if the field is set but "", update it. + if (array_key_exists($field, $data) && null !== $data[$field]) { + + // convert boolean value: + if (is_bool($data[$field]) && false === $data[$field]) { + $data[$field] = 0; + } + if (is_bool($data[$field]) && true === $data[$field]) { + $data[$field] = 1; + } + + $factory->crud($account, $field, (string)$data[$field]); + } + } + } + + /** + * @param Account $account + * @param array $data + */ + private function storeOpeningBalance(Account $account, array $data) + { + $accountType = $account->accountType->type; + + // if it can have a virtual balance, it can also have an opening balance. + if (in_array($accountType, $this->canHaveVirtual, true)) { + if ($this->validOBData($data)) { + $this->updateOBGroup($account, $data); + } + if (!$this->validOBData($data)) { + $this->deleteOBGroup($account); + } + } + } + + /** + * @param Account $account + * @param array $data + */ + private function storeOrder(Account $account, array $data): void + { + $accountType = $account->accountType->type; + $maxOrder = $this->accountRepository->maxOrder($accountType); + $order = null; + if (!array_key_exists('order', $data)) { + $order = $maxOrder + 1; + } + if (array_key_exists('order', $data)) { + $order = (int)($data['order'] > $maxOrder ? $maxOrder + 1 : $data['order']); + $order = 0 === $order ? $maxOrder + 1 : $order; + } + + $updateService = app(AccountUpdateService::class); + $updateService->setUser($account->user); + $updateService->update($account, ['order' => $order]); + } + /** * @param User $user */ public function setUser(User $user): void { $this->user = $user; + $this->accountRepository->setUser($user); } + + } diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php index ae74aeefb7..87133621b6 100644 --- a/app/Factory/AccountMetaFactory.php +++ b/app/Factory/AccountMetaFactory.php @@ -67,8 +67,8 @@ class AccountMetaFactory if ('' === $value && null !== $entry) { try { $entry->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::debug(sprintf('Could not delete entry: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + Log::debug(sprintf('Could not delete entry: %s', $e->getMessage())); } return null; diff --git a/app/Factory/AttachmentFactory.php b/app/Factory/AttachmentFactory.php index 53a08866a3..87fb2375d1 100644 --- a/app/Factory/AttachmentFactory.php +++ b/app/Factory/AttachmentFactory.php @@ -54,7 +54,7 @@ class AttachmentFactory /** @var Transaction $transaction */ $transaction = $this->user->transactions()->find((int)$data['attachable_id']); if (null === $transaction) { - throw new FireflyException('Unexpectedly could not find transaction'); // @codeCoverageIgnore + throw new FireflyException('Unexpectedly could not find transaction'); } $data['attachable_id'] = $transaction->transaction_journal_id; $model = TransactionJournal::class; diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index 88c2ad614e..417f72660d 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -76,7 +76,7 @@ class BillFactory } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException('400000: Could not store bill.'); + throw new FireflyException('400000: Could not store bill.', 0, $e); } if (array_key_exists('notes', $data)) { diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php index 2a5dcbe67f..6adc1800a0 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -76,7 +76,7 @@ class CategoryFactory ); } catch (QueryException $e) { Log::error($e->getMessage()); - throw new FireflyException('400003: Could not store new category.'); + throw new FireflyException('400003: Could not store new category.', 0, $e); } } diff --git a/app/Factory/RecurrenceFactory.php b/app/Factory/RecurrenceFactory.php index 8b0c70e2f1..5622cfafcc 100644 --- a/app/Factory/RecurrenceFactory.php +++ b/app/Factory/RecurrenceFactory.php @@ -69,7 +69,7 @@ class RecurrenceFactory Log::error($message); Log::error($e->getTraceAsString()); - throw new FireflyException($message); + throw new FireflyException($message, 0, $e); } $firstDate = null; $repeatUntil = null; @@ -129,17 +129,16 @@ class RecurrenceFactory $this->createRepetitions($recurrence, $data['repetitions'] ?? []); try { $this->createTransactions($recurrence, $data['transactions'] ?? []); - // @codeCoverageIgnoreStart + } catch (FireflyException $e) { Log::error($e->getMessage()); $recurrence->forceDelete(); $message = sprintf('Could not create recurring transaction: %s', $e->getMessage()); $this->errors->add('store', $message); - throw new FireflyException($message); + throw new FireflyException($message, 0, $e); } - // @codeCoverageIgnoreEnd return $recurrence; } @@ -152,4 +151,13 @@ class RecurrenceFactory $this->user = $user; } + /** + * @return MessageBag + */ + public function getErrors(): MessageBag + { + return $this->errors; + } + + } diff --git a/app/Factory/TransactionCurrencyFactory.php b/app/Factory/TransactionCurrencyFactory.php index 86bb2dacd0..ba769f5338 100644 --- a/app/Factory/TransactionCurrencyFactory.php +++ b/app/Factory/TransactionCurrencyFactory.php @@ -59,7 +59,7 @@ class TransactionCurrencyFactory } catch (QueryException $e) { $result = null; Log::error(sprintf('Could not create new currency: %s', $e->getMessage())); - throw new FireflyException('400004: Could not store new currency.'); + throw new FireflyException('400004: Could not store new currency.', 0, $e); } return $result; diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php index 759251a790..a41a871d68 100644 --- a/app/Factory/TransactionFactory.php +++ b/app/Factory/TransactionFactory.php @@ -102,17 +102,17 @@ class TransactionFactory ]; try { $result = Transaction::create($data); - // @codeCoverageIgnoreStart + } catch (QueryException $e) { Log::error(sprintf('Could not create transaction: %s', $e->getMessage()), $data); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException('Query exception when creating transaction.'); + throw new FireflyException('Query exception when creating transaction.', 0, $e); } if (null === $result) { throw new FireflyException('Transaction is NULL.'); } - // @codeCoverageIgnoreEnd + if (null !== $result) { Log::debug( sprintf( diff --git a/app/Factory/TransactionGroupFactory.php b/app/Factory/TransactionGroupFactory.php index 902004855f..8002561b6f 100644 --- a/app/Factory/TransactionGroupFactory.php +++ b/app/Factory/TransactionGroupFactory.php @@ -66,7 +66,7 @@ class TransactionGroupFactory $collection = $this->journalFactory->create($data); } catch (DuplicateTransactionException $e) { Log::warning('GroupFactory::create() caught journalFactory::create() with a duplicate!'); - throw new DuplicateTransactionException($e->getMessage()); + throw new DuplicateTransactionException($e->getMessage(), 0, $e); } $title = $data['group_title'] ?? null; $title = '' === $title ? null : $title; diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index ac981c7984..d9fa71a405 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -128,13 +128,13 @@ class TransactionJournalFactory Log::error($e->getMessage()); Log::error($e->getTraceAsString()); $this->forceDeleteOnError($collection); - throw new DuplicateTransactionException($e->getMessage()); + throw new DuplicateTransactionException($e->getMessage(), 0, $e); } catch (FireflyException $e) { Log::warning('TransactionJournalFactory::create() caught an exception.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); $this->forceDeleteOnError($collection); - throw new FireflyException($e->getMessage()); + throw new FireflyException($e->getMessage(), 0, $e); } return $collection; @@ -161,7 +161,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 = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; - $description = app('steam')->cleanString((string)$row['description']); + $description = (string)$row['description']; /** Manipulate basic fields */ $carbon->setTimezone(config('app.timezone')); @@ -181,7 +181,7 @@ class TransactionJournalFactory /** create or get source and destination accounts */ $sourceInfo = [ - 'id' => (int)$row['source_id'], + 'id' => $row['source_id'], 'name' => $row['source_name'], 'iban' => $row['source_iban'], 'number' => $row['source_number'], @@ -190,7 +190,7 @@ class TransactionJournalFactory ]; $destInfo = [ - 'id' => (int)$row['destination_id'], + 'id' => $row['destination_id'], 'name' => $row['destination_name'], 'iban' => $row['destination_iban'], 'number' => $row['destination_number'], @@ -240,7 +240,7 @@ class TransactionJournalFactory Log::error($e->getMessage()); Log::error($e->getTraceAsString()); $this->forceDeleteOnError(new Collection([$journal])); - throw new FireflyException($e->getMessage()); + throw new FireflyException($e->getMessage(), 0, $e); } // and the destination one: @@ -261,7 +261,7 @@ class TransactionJournalFactory Log::warning('Delete negative transaction.'); $this->forceTrDelete($negative); $this->forceDeleteOnError(new Collection([$journal])); - throw new FireflyException($e->getMessage()); + throw new FireflyException($e->getMessage(), 0, $e); } // verify that journal has two transactions. Otherwise, delete and cancel. $journal->completed = true; @@ -302,10 +302,10 @@ class TransactionJournalFactory unset($dataRow['import_hash_v2'], $dataRow['original_source']); $json = json_encode($dataRow, JSON_THROW_ON_ERROR, 512); if (false === $json) { - // @codeCoverageIgnoreStart + $json = json_encode((string)microtime(), JSON_THROW_ON_ERROR, 512); Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow); - // @codeCoverageIgnoreEnd + } $hash = hash('sha256', $json); Log::debug(sprintf('The hash is: %s', $hash), $dataRow); @@ -347,6 +347,7 @@ class TransactionJournalFactory */ private function validateAccounts(NullArrayObject $data): void { + Log::debug(sprintf('Now in %s', __METHOD__)); $transactionType = $data['type'] ?? 'invalid'; $this->accountValidator->setUser($this->user); $this->accountValidator->setTransactionType($transactionType); @@ -358,7 +359,7 @@ class TransactionJournalFactory // do something with result: if (false === $validSource) { - throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError)); } Log::debug('Source seems valid.'); // validate destination account @@ -367,7 +368,7 @@ class TransactionJournalFactory $validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName, null); // do something with result: if (false === $validDestination) { - throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError)); } } @@ -485,7 +486,7 @@ class TransactionJournalFactory { try { $transaction->delete(); - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); Log::error($e->getTraceAsString()); Log::error('Could not delete negative transaction.'); diff --git a/app/Factory/TransactionJournalMetaFactory.php b/app/Factory/TransactionJournalMetaFactory.php index d3adb5777b..feff846ff9 100644 --- a/app/Factory/TransactionJournalMetaFactory.php +++ b/app/Factory/TransactionJournalMetaFactory.php @@ -49,8 +49,8 @@ class TransactionJournalMetaFactory Log::debug('Value is empty, delete meta value.'); try { $entry->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete transaction journal meta: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + Log::error(sprintf('Could not delete transaction journal meta: %s', $e->getMessage())); } return null; @@ -67,8 +67,8 @@ class TransactionJournalMetaFactory Log::debug('Will not store empty strings, delete meta value'); try { $entry->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete transaction journal meta: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + Log::error(sprintf('Could not delete transaction journal meta: %s', $e->getMessage())); } } diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index 76ba7b89d9..e55ca69b50 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -56,7 +56,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('start', $this->start)->with('end', $this->end) ->with('doubles', $this->expense) ->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); $result = sprintf('Could not render report view: %s', $e->getMessage()); } diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index 754485d02f..009d8d0396 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -82,7 +82,7 @@ class MonthReportGenerator implements ReportGeneratorInterface $result = prefixView('reports.audit.report', compact('reportType', 'accountIds', 'auditData', 'hideable', 'defaultShow')) ->with('start', $this->start)->with('end', $this->end)->with('accounts', $this->accounts) ->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); $result = sprintf('Could not render report view: %s', $e->getMessage()); @@ -254,7 +254,7 @@ class MonthReportGenerator implements ReportGeneratorInterface return [ 'journals' => $journals, 'currency' => $currency, - 'exists' => !empty($journals), + 'exists' => 0!==count($journals), 'end' => $this->end->formatLocalized((string)trans('config.month_and_day', [], $locale)), 'endBalance' => app('steam')->balance($account, $this->end), 'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day', [], $locale)), diff --git a/app/Generator/Report/Budget/MonthReportGenerator.php b/app/Generator/Report/Budget/MonthReportGenerator.php index 9e4bc6bcbd..f6c9af7e0c 100644 --- a/app/Generator/Report/Budget/MonthReportGenerator.php +++ b/app/Generator/Report/Budget/MonthReportGenerator.php @@ -73,7 +73,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('budgets', $this->budgets) ->with('accounts', $this->accounts) ->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); $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 df2bc0df4d..bfc91dbde4 100644 --- a/app/Generator/Report/Category/MonthReportGenerator.php +++ b/app/Generator/Report/Category/MonthReportGenerator.php @@ -81,7 +81,7 @@ class MonthReportGenerator implements ReportGeneratorInterface ->with('categories', $this->categories) ->with('accounts', $this->accounts) ->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.category.month: %s', $e->getMessage())); $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 4071de53aa..1b7caea103 100644 --- a/app/Generator/Report/Standard/MonthReportGenerator.php +++ b/app/Generator/Report/Standard/MonthReportGenerator.php @@ -54,7 +54,7 @@ class MonthReportGenerator implements ReportGeneratorInterface try { return prefixView('reports.default.month', compact('accountIds', 'reportType'))->with('start', $this->start)->with('end', $this->end)->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.default.month: %s', $e->getMessage())); $result = 'Could not render report view.'; } diff --git a/app/Generator/Report/Standard/MultiYearReportGenerator.php b/app/Generator/Report/Standard/MultiYearReportGenerator.php index b535f7a105..1a8025b68d 100644 --- a/app/Generator/Report/Standard/MultiYearReportGenerator.php +++ b/app/Generator/Report/Standard/MultiYearReportGenerator.php @@ -58,7 +58,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) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.default.multi-year: %s', $e->getMessage())); $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 7b0f7ec6c2..8da980de7f 100644 --- a/app/Generator/Report/Standard/YearReportGenerator.php +++ b/app/Generator/Report/Standard/YearReportGenerator.php @@ -58,7 +58,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) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); $result = 'Could not render report view.'; } diff --git a/app/Generator/Report/Tag/MonthReportGenerator.php b/app/Generator/Report/Tag/MonthReportGenerator.php index a6d6c67b9f..008b9e27eb 100644 --- a/app/Generator/Report/Tag/MonthReportGenerator.php +++ b/app/Generator/Report/Tag/MonthReportGenerator.php @@ -79,7 +79,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) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage())); $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 1e9542f6d2..bb944b84fe 100644 --- a/app/Handlers/Events/APIEventHandler.php +++ b/app/Handlers/Events/APIEventHandler.php @@ -69,14 +69,14 @@ class APIEventHandler try { Log::debug('Trying to send message...'); Mail::to($email)->send(new AccessTokenCreatedMail($email, $ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); Session::flash('error', 'Possible email error: ' . $e->getMessage()); } - // @codeCoverageIgnoreEnd + Log::debug('If no error above this line, message was sent.'); } diff --git a/app/Handlers/Events/AdminEventHandler.php b/app/Handlers/Events/AdminEventHandler.php index 1b16371383..01bc3b9be4 100644 --- a/app/Handlers/Events/AdminEventHandler.php +++ b/app/Handlers/Events/AdminEventHandler.php @@ -67,15 +67,15 @@ class AdminEventHandler try { Log::debug('Trying to send message...'); Mail::to($email)->send(new AdminTestMail($email, $ipAddress)); - // @codeCoverageIgnoreStart + // Laravel cannot pretend this process failed during testing. - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); Session::flash('error', 'Possible email error: ' . $e->getMessage()); } - // @codeCoverageIgnoreEnd + Log::debug('If no error above this line, message was sent.'); } diff --git a/app/Handlers/Events/AutomationHandler.php b/app/Handlers/Events/AutomationHandler.php index e65abbb55d..6939b01009 100644 --- a/app/Handlers/Events/AutomationHandler.php +++ b/app/Handlers/Events/AutomationHandler.php @@ -48,7 +48,7 @@ class AutomationHandler $sendReport = config('firefly.send_report_journals'); if (false === $sendReport) { - return true; // @codeCoverageIgnore + return true; } Log::debug('In reportJournals.'); @@ -73,13 +73,13 @@ class AutomationHandler try { Log::debug('Trying to mail...'); Mail::to($user->email)->send(new ReportNewJournalsMail($email, '127.0.0.1', $event->groups)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); } - // @codeCoverageIgnoreEnd + Log::debug('Done!'); } diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 095ca2f773..9d6c55cf00 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -154,8 +154,8 @@ class UserEventHandler if (false === $entry['notified']) { try { Mail::to($email)->send(new NewIPAddressWarningMail($ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } } @@ -182,13 +182,10 @@ class UserEventHandler $uri = route('profile.confirm-email-change', [$token->data]); try { Mail::to($newEmail)->send(new ConfirmEmailChangeMail($newEmail, $oldEmail, $uri, $ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } - - // @codeCoverageIgnoreEnd - return true; } @@ -210,13 +207,10 @@ class UserEventHandler $uri = route('profile.undo-email-change', [$token->data, $hashed]); try { Mail::to($oldEmail)->send(new UndoEmailChangeMail($newEmail, $oldEmail, $uri, $ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } - - // @codeCoverageIgnoreEnd - return true; } @@ -238,13 +232,10 @@ class UserEventHandler // send email. try { Mail::to($email)->send(new RequestedNewPasswordMail($url, $ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } - - // @codeCoverageIgnoreEnd - return true; } @@ -274,11 +265,11 @@ class UserEventHandler // send email. try { Mail::to($email)->send(new RegisteredUserMail($uri, $ipAddress)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } - // @codeCoverageIgnoreEnd + } return true; diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index f5ac7b738d..eca3f3fa3a 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -42,16 +42,11 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; */ class AttachmentHelper implements AttachmentHelperInterface { - /** @var Collection All attachments */ - public $attachments; - /** @var MessageBag All errors */ - public $errors; - /** @var MessageBag All messages */ - public $messages; - /** @var array Allowed mimes */ - protected $allowedMimes = []; - /** @var int Max upload size. */ - protected $maxUploadSize = 0; + public Collection $attachments; + public MessageBag $errors; + public MessageBag $messages; + protected array $allowedMimes = []; + protected int $maxUploadSize = 0; /** @var Filesystem The disk where attachments are stored. */ protected $uploadDisk; @@ -156,11 +151,11 @@ class AttachmentHelper implements AttachmentHelperInterface { $resource = tmpfile(); if (false === $resource) { - // @codeCoverageIgnoreStart + Log::error('Cannot create temp-file for file upload.'); return false; - // @codeCoverageIgnoreEnd + } if ('' === $content) { @@ -204,7 +199,7 @@ class AttachmentHelper implements AttachmentHelperInterface public function saveAttachmentsForModel(object $model, ?array $files): bool { if (!($model instanceof Model)) { - return false; // @codeCoverageIgnore + return false; } Log::debug(sprintf('Now in saveAttachmentsForModel for model %s', get_class($model))); @@ -218,7 +213,7 @@ class AttachmentHelper implements AttachmentHelperInterface } Log::debug('Done processing uploads.'); } - if (!is_array($files) || empty($files)) { + if (!is_array($files)) { Log::debug('Array of files is not an array. Probably nothing uploaded. Will not store attachments.'); } @@ -263,7 +258,7 @@ class AttachmentHelper implements AttachmentHelperInterface $fileObject->rewind(); if (0 === $file->getSize()) { - throw new FireflyException('Cannot upload empty or non-existent file.'); // @codeCoverageIgnore + throw new FireflyException('Cannot upload empty or non-existent file.'); } $content = $fileObject->fread($file->getSize()); @@ -303,12 +298,12 @@ class AttachmentHelper implements AttachmentHelperInterface $result = false; } - // @codeCoverageIgnoreStart + // can't seem to reach this point. if (true === $result && !$this->validSize($file)) { $result = false; } - // @codeCoverageIgnoreEnd + if (true === $result && $this->hasFile($file, $model)) { $result = false; } diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 6db7a7bfd8..b6ef342f54 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -338,7 +338,7 @@ class GroupCollector implements GroupCollectorInterface */ public function setJournalIds(array $journalIds): GroupCollectorInterface { - if (!empty($journalIds)) { + if (0!==count($journalIds)) { $this->query->whereIn('transaction_journals.id', $journalIds); } @@ -691,7 +691,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) { + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); } @@ -699,7 +699,7 @@ class GroupCollector implements GroupCollectorInterface $result = $this->convertToInteger($result); $result['reconciled'] = 1 === (int)$result['reconciled']; - if (isset($augumentedJournal['tag_id'])) { // assume the other fields are present as well. + if (array_key_exists('tag_id', $result)) { // assume the other fields are present as well. $tagId = (int)$augumentedJournal['tag_id']; $tagDate = null; try { @@ -717,7 +717,7 @@ class GroupCollector implements GroupCollectorInterface } // also merge attachments: - if (isset($augumentedJournal['attachment_id'])) { + if (array_key_exists('attachment_id', $result)) { $attachmentId = (int)$augumentedJournal['attachment_id']; $result['attachments'][$attachmentId] = [ 'id' => $attachmentId, @@ -744,7 +744,7 @@ class GroupCollector implements GroupCollectorInterface $currencyId = (int)$transaction['currency_id']; // set default: - if (!isset($groups[$groudId]['sums'][$currencyId])) { + if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; @@ -757,7 +757,7 @@ class GroupCollector implements GroupCollectorInterface $currencyId = (int)$transaction['foreign_currency_id']; // set default: - if (!isset($groups[$groudId]['sums'][$currencyId])) { + if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; diff --git a/app/Helpers/Help/Help.php b/app/Helpers/Help/Help.php index f7fc1415b1..a76ef6df23 100644 --- a/app/Helpers/Help/Help.php +++ b/app/Helpers/Help/Help.php @@ -84,7 +84,7 @@ class Help implements HelpInterface $res = $client->request('GET', $uri, $opt); $statusCode = $res->getStatusCode(); $content = trim($res->getBody()->getContents()); - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::info($e->getMessage()); Log::info($e->getTraceAsString()); } diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php index 01303273f9..45986cf22b 100644 --- a/app/Helpers/Report/NetWorth.php +++ b/app/Helpers/Report/NetWorth.php @@ -72,7 +72,7 @@ class NetWorth implements NetWorthInterface $cache->addProperty('net-worth-by-currency'); $cache->addProperty(implode(',', $accounts->pluck('id')->toArray())); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $netWorth = []; diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 9221359b0a..5deebb3292 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -128,7 +128,7 @@ class ReportHelper implements ReportHelperInterface while ($start <= $end) { $year = $fiscalHelper->endOfFiscalYear($start)->year; // current year - if (!isset($months[$year])) { + if (!array_key_exists($year, $months)) { $months[$year] = [ 'fiscal_start' => $fiscalHelper->startOfFiscalYear($start)->format('Y-m-d'), 'fiscal_end' => $fiscalHelper->endOfFiscalYear($start)->format('Y-m-d'), diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php index d426f13fe7..392e03cb2b 100644 --- a/app/Http/Controllers/Account/CreateController.php +++ b/app/Http/Controllers/Account/CreateController.php @@ -156,7 +156,7 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } // redirect to previous URL. diff --git a/app/Http/Controllers/Account/DeleteController.php b/app/Http/Controllers/Account/DeleteController.php index 41a5cc1f59..7e49118d40 100644 --- a/app/Http/Controllers/Account/DeleteController.php +++ b/app/Http/Controllers/Account/DeleteController.php @@ -26,7 +26,6 @@ namespace FireflyIII\Http\Controllers\Account; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -38,8 +37,6 @@ use Illuminate\View\View; */ class DeleteController extends Controller { - use UserNavigation; - /** @var AccountRepositoryInterface The account repository */ private $repository; @@ -75,7 +72,7 @@ class DeleteController extends Controller public function delete(Account $account) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); @@ -101,7 +98,7 @@ class DeleteController extends Controller public function destroy(Request $request, Account $account) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $type = $account->accountType->type; diff --git a/app/Http/Controllers/Account/EditController.php b/app/Http/Controllers/Account/EditController.php index afa92d88eb..be6a0e1da8 100644 --- a/app/Http/Controllers/Account/EditController.php +++ b/app/Http/Controllers/Account/EditController.php @@ -30,7 +30,6 @@ use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\Http\Controllers\ModelInformation; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -43,7 +42,7 @@ use Illuminate\View\View; */ class EditController extends Controller { - use ModelInformation, UserNavigation; + use ModelInformation; private AttachmentHelperInterface $attachments; /** @var CurrencyRepositoryInterface The currency repository */ @@ -85,7 +84,7 @@ class EditController extends Controller public function edit(Request $request, Account $account, AccountRepositoryInterface $repository) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; @@ -178,7 +177,7 @@ class EditController extends Controller public function update(AccountFormRequest $request, Account $account) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $data = $request->getAccountData(); @@ -196,7 +195,7 @@ class EditController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } // redirect diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php index 112273fef4..4232e35712 100644 --- a/app/Http/Controllers/Account/ReconcileController.php +++ b/app/Http/Controllers/Account/ReconcileController.php @@ -36,7 +36,6 @@ use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use FireflyIII\Support\Http\Controllers\UserNavigation; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -49,8 +48,6 @@ use Log; */ class ReconcileController extends Controller { - use UserNavigation; - /** @var AccountRepositoryInterface The account repository */ private $accountRepos; /** @var CurrencyRepositoryInterface The currency repository */ @@ -94,14 +91,14 @@ class ReconcileController extends Controller public function reconcile(Account $account, Carbon $start = null, Carbon $end = null) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } if (AccountType::ASSET !== $account->accountType->type) { - // @codeCoverageIgnoreStart + session()->flash('error', (string)trans('firefly.must_be_asset_account')); return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))])); - // @codeCoverageIgnoreEnd + } $currency = $this->accountRepos->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency(); @@ -109,7 +106,7 @@ class ReconcileController extends Controller $range = app('preferences')->get('viewRange', '1M')->data; // get start and end - // @codeCoverageIgnoreStart + if (null === $start && null === $end) { /** @var Carbon $start */ @@ -121,7 +118,7 @@ class ReconcileController extends Controller /** @var Carbon $end */ $end = app('navigation')->endOfPeriod($start, $range); } - // @codeCoverageIgnoreEnd + if ($end->lt($start)) { [$start, $end] = [$end, $start]; } @@ -171,7 +168,7 @@ class ReconcileController extends Controller public function submit(ReconciliationStoreRequest $request, Account $account, Carbon $start, Carbon $end) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } Log::debug('In ReconcileController::submit()'); @@ -220,7 +217,7 @@ class ReconcileController extends Controller private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $reconciliation = $this->accountRepos->getReconciliation($account); diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php index 6d25d3bb49..4b7274227e 100644 --- a/app/Http/Controllers/Account/ShowController.php +++ b/app/Http/Controllers/Account/ShowController.php @@ -31,7 +31,6 @@ use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\Http\Controllers\PeriodOverview; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -45,7 +44,7 @@ use Illuminate\View\View; */ class ShowController extends Controller { - use UserNavigation, PeriodOverview; + use PeriodOverview; private CurrencyRepositoryInterface $currencyRepos; private AccountRepositoryInterface $repository; @@ -92,7 +91,7 @@ class ShowController extends Controller $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } /** @var Carbon $start */ @@ -101,7 +100,7 @@ class ShowController extends Controller $end = $end ?? session('end'); if ($end < $start) { - [$start, $end] = [$end, $start]; // @codeCoverageIgnore + [$start, $end] = [$end, $start]; } $location = $this->repository->getLocation($account); $attachments = $this->repository->getAttachments($account); @@ -165,7 +164,7 @@ class ShowController extends Controller public function showAll(Request $request, Account $account) { if (!$this->isEditableAccount($account)) { - return $this->redirectAccountToAccount($account); // @codeCoverageIgnore + return $this->redirectAccountToAccount($account); } $location = $this->repository->getLocation($account); $isLiability = $this->repository->isLiability($account); diff --git a/app/Http/Controllers/Admin/LinkController.php b/app/Http/Controllers/Admin/LinkController.php index 68256d93d6..8b78623e9d 100644 --- a/app/Http/Controllers/Admin/LinkController.php +++ b/app/Http/Controllers/Admin/LinkController.php @@ -163,7 +163,7 @@ class LinkController extends Controller // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('link-types.edit.fromUpdate')) { - $this->rememberPreviousUri('link-types.edit.uri'); // @codeCoverageIgnore + $this->rememberPreviousUri('link-types.edit.uri'); } $request->session()->forget('link-types.edit.fromUpdate'); diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index d898fdc448..06608a4df9 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -219,11 +219,11 @@ class UserController extends Controller app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('users.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('users.edit.fromUpdate', true); $redirect = redirect(route('admin.users.edit', [$user->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } // redirect to previous URL. diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php index e8fb8a4b97..4bb4af6bc1 100644 --- a/app/Http/Controllers/AttachmentController.php +++ b/app/Http/Controllers/AttachmentController.php @@ -39,6 +39,7 @@ use Illuminate\View\View; */ class AttachmentController extends Controller { + /** @var AttachmentRepositoryInterface Attachment repository */ private $repository; @@ -196,11 +197,11 @@ class AttachmentController extends Controller $redirect = redirect($this->getPreviousUri('attachments.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + $request->session()->put('attachments.edit.fromUpdate', true); $redirect = redirect(route('attachments.edit', [$attachment->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } // redirect to previous URL. diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index b17e8652a7..01372e02ef 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -72,14 +72,14 @@ class ForgotPasswordController extends Controller { Log::info('Start of sendResetLinkEmail()'); $loginProvider = config('firefly.login_provider'); - // @codeCoverageIgnoreStart + if ('eloquent' !== $loginProvider) { $message = sprintf('Cannot reset password when authenticating over "%s".', $loginProvider); Log::error($message); return prefixView('error', compact('message')); } - // @codeCoverageIgnoreEnd + $this->validateEmail($request); @@ -102,7 +102,7 @@ class ForgotPasswordController extends Controller return back()->with('status', trans($response)); } - return back()->withErrors(['email' => trans($response)]); // @codeCoverageIgnore + return back()->withErrors(['email' => trans($response)]); } /** diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index e64eb3e487..0295bc0388 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -83,7 +83,7 @@ class LoginController extends Controller Log::info(sprintf('User is trying to login.')); if ('ldap' === config('auth.providers.users.driver')) { /** @var Adldap\Connections\Provider $provider */ - Adldap::getProvider('default'); + Adldap::getProvider('default'); // @phpstan-ignore-line } $this->validateLogin($request); @@ -96,7 +96,7 @@ class LoginController extends Controller Log::channel('audit')->info(sprintf('Login for user "%s" was locked out.', $request->get('email'))); $this->fireLockoutEvent($request); - return $this->sendLockoutResponse($request); + $this->sendLockoutResponse($request); } /** Copied directly from AuthenticatesUsers, but with logging added: */ @@ -190,7 +190,7 @@ class LoginController extends Controller $loginProvider = config('firefly.login_provider'); $title = (string)trans('firefly.login_page_title'); if (0 === $count && 'eloquent' === $loginProvider) { - return redirect(route('register')); // @codeCoverageIgnore + return redirect(route('register')); } // is allowed to? diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 4f669d4c7b..9a0f946d97 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -27,7 +27,6 @@ use FireflyIII\Events\RegisteredUser; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\Http\Controllers\CreateStuff; -use FireflyIII\Support\Http\Controllers\RequestInformation; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Foundation\Auth\RegistersUsers; @@ -48,7 +47,7 @@ use Log; */ class RegisterController extends Controller { - use RegistersUsers, RequestInformation, CreateStuff; + use RegistersUsers, CreateStuff; /** * Where to redirect users after registration. diff --git a/app/Http/Controllers/Bill/CreateController.php b/app/Http/Controllers/Bill/CreateController.php index 41b69d5c17..8efdbc45b5 100644 --- a/app/Http/Controllers/Bill/CreateController.php +++ b/app/Http/Controllers/Bill/CreateController.php @@ -34,6 +34,7 @@ use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\View\View; +use Log; /** * Class CreateController @@ -124,7 +125,7 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } return redirect(route('rules.create-from-bill', [$bill->id])); diff --git a/app/Http/Controllers/Bill/EditController.php b/app/Http/Controllers/Bill/EditController.php index 690d9b4faa..108e5bcf49 100644 --- a/app/Http/Controllers/Bill/EditController.php +++ b/app/Http/Controllers/Bill/EditController.php @@ -138,16 +138,16 @@ class EditController extends Controller // flash messages if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('bills.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + $request->session()->put('bills.edit.fromUpdate', true); $redirect = redirect(route('bills.edit', [$bill->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Bill/ShowController.php b/app/Http/Controllers/Bill/ShowController.php index d597d1dce4..0c3f0ffe07 100644 --- a/app/Http/Controllers/Bill/ShowController.php +++ b/app/Http/Controllers/Bill/ShowController.php @@ -168,7 +168,7 @@ class ShowController extends Controller $collection = $this->repository->getAttachments($bill); $attachments = new Collection; - // @codeCoverageIgnoreStart + if ($collection->count() > 0) { /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); @@ -179,7 +179,7 @@ class ShowController extends Controller ); } - // @codeCoverageIgnoreEnd + return prefixView('bills.show', compact('attachments', 'groups', 'rules', 'yearAverage', 'overallAverage', 'year', 'object', 'bill', 'subTitle')); } diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php index d7aca5491b..32ced8a890 100644 --- a/app/Http/Controllers/Budget/CreateController.php +++ b/app/Http/Controllers/Budget/CreateController.php @@ -131,17 +131,17 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('budgets.create.uri')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + $request->session()->put('budgets.create.fromStore', true); $redirect = redirect(route('budgets.create'))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Budget/EditController.php b/app/Http/Controllers/Budget/EditController.php index 1205a19a67..8422595a05 100644 --- a/app/Http/Controllers/Budget/EditController.php +++ b/app/Http/Controllers/Budget/EditController.php @@ -144,15 +144,15 @@ class EditController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + $request->session()->put('budgets.edit.fromUpdate', true); $redirect = redirect(route('budgets.edit', [$budget->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php index d796956cb4..1c91ed2b44 100644 --- a/app/Http/Controllers/Budget/IndexController.php +++ b/app/Http/Controllers/Budget/IndexController.php @@ -219,7 +219,7 @@ class IndexController extends Controller /** @var TransactionCurrency $currency */ foreach ($currencies as $currency) { $spentArr = $this->opsRepository->sumExpenses($start, $end, null, new Collection([$current]), $currency); - if (isset($spentArr[$currency->id]['sum'])) { + if (array_key_exists($currency->id, $spentArr) && array_key_exists('sum', $spentArr[$currency->id])) { $array['spent'][$currency->id]['spent'] = $spentArr[$currency->id]['sum']; $array['spent'][$currency->id]['currency_id'] = $currency->id; $array['spent'][$currency->id]['currency_symbol'] = $currency->symbol; diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php index a146dc199c..b16e8142d5 100644 --- a/app/Http/Controllers/Budget/ShowController.php +++ b/app/Http/Controllers/Budget/ShowController.php @@ -46,7 +46,7 @@ class ShowController extends Controller { use PeriodOverview, AugumentData; - private JournalRepositoryInterface $journalRepos; + protected JournalRepositoryInterface $journalRepos; private BudgetRepositoryInterface $repository; /** @@ -180,7 +180,7 @@ class ShowController extends Controller public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit) { if ($budgetLimit->budget->id !== $budget->id) { - throw new FireflyException('This budget limit is not part of this budget.'); // @codeCoverageIgnore + throw new FireflyException('This budget limit is not part of this budget.'); } $page = (int)$request->get('page'); diff --git a/app/Http/Controllers/Category/CreateController.php b/app/Http/Controllers/Category/CreateController.php index c35c44ce94..024d71dc06 100644 --- a/app/Http/Controllers/Category/CreateController.php +++ b/app/Http/Controllers/Category/CreateController.php @@ -105,16 +105,16 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect(route('categories.index')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + $request->session()->put('categories.create.fromStore', true); $redirect = redirect(route('categories.create'))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Category/EditController.php b/app/Http/Controllers/Category/EditController.php index 16940cfb70..02355d2cc6 100644 --- a/app/Http/Controllers/Category/EditController.php +++ b/app/Http/Controllers/Category/EditController.php @@ -115,16 +115,16 @@ class EditController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('categories.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + $request->session()->put('categories.edit.fromUpdate', true); $redirect = redirect(route('categories.edit', [$category->id])); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Category/NoCategoryController.php b/app/Http/Controllers/Category/NoCategoryController.php index 5360245aba..9ae41cebb2 100644 --- a/app/Http/Controllers/Category/NoCategoryController.php +++ b/app/Http/Controllers/Category/NoCategoryController.php @@ -43,8 +43,7 @@ class NoCategoryController extends Controller { use PeriodOverview; - /** @var JournalRepositoryInterface Journals and transactions overview */ - private $journalRepos; + protected JournalRepositoryInterface $journalRepos; /** * CategoryController constructor. diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index 75894437eb..91d9ec0266 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -95,7 +95,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty('chart.account.expense-accounts'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $start->subDay(); @@ -203,7 +203,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty('chart.account.expense-budget'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -217,7 +217,7 @@ class AccountController extends Controller $budgetId = (int)$journal['budget_id']; $key = sprintf('%d-%d', $budgetId, $journal['currency_id']); $budgetIds[] = $budgetId; - if (!isset($result[$key])) { + if (!array_key_exists($key, $result)) { $result[$key] = [ 'total' => '0', 'budget_id' => $budgetId, @@ -277,7 +277,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty('chart.account.expense-category'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ @@ -290,7 +290,7 @@ class AccountController extends Controller /** @var array $journal */ foreach ($journals as $journal) { $key = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']); - if (!isset($result[$key])) { + if (!array_key_exists($key, $result)) { $result[$key] = [ 'total' => '0', 'category_id' => (int)$journal['category_id'], @@ -373,7 +373,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty('chart.account.income-category'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } // grab all journals: @@ -387,7 +387,7 @@ class AccountController extends Controller /** @var array $journal */ foreach ($journals as $journal) { $key = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']); - if (!isset($result[$key])) { + if (!array_key_exists($key, $result)) { $result[$key] = [ 'total' => '0', 'category_id' => $journal['category_id'], @@ -431,7 +431,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty($account->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $currencies = $this->accountRepository->getUsedCurrencies($account); @@ -488,7 +488,7 @@ class AccountController extends Controller $current->addDay(); } break; - // @codeCoverageIgnoreStart + case '1W': case '1M': case '1Y': @@ -499,7 +499,7 @@ class AccountController extends Controller $current = app('navigation')->addPeriod($current, $step, 0); } break; - // @codeCoverageIgnoreEnd + } $result['entries'] = $entries; @@ -540,7 +540,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty('chart.account.revenue-accounts'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $start->subDay(); diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php index de009a6f45..f92c40f28a 100644 --- a/app/Http/Controllers/Chart/BillController.php +++ b/app/Http/Controllers/Chart/BillController.php @@ -67,7 +67,7 @@ class BillController extends Controller $cache->addProperty($end); $cache->addProperty('chart.bill.frontpage'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var CurrencyRepositoryInterface $currencyRepository */ $currencyRepository = app(CurrencyRepositoryInterface::class); @@ -109,7 +109,7 @@ class BillController extends Controller $cache->addProperty('chart.bill.single'); $cache->addProperty($bill->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $locale = app('steam')->getLocale(); @@ -147,7 +147,7 @@ class BillController extends Controller $chartData[1]['entries'][$date] = $bill->amount_max; // maximum amount of bill // append amount because there are more than one per moment: - if (!isset($chartData[2]['entries'][$date])) { + if (!array_key_exists($date, $chartData[2]['entries'])) { $chartData[2]['entries'][$date] = '0'; } $amount = bcmul($journal['amount'], '-1'); diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 1cca259abf..a0afd439dc 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -98,7 +98,7 @@ class BudgetController extends Controller $cache->addProperty($budget->id); if ($cache->has()) { - //return response()->json($cache->get()); // @codeCoverageIgnore + //return response()->json($cache->get()); } $step = $this->calculateStep($start, $end); // depending on diff, do something with range of chart. $collection = new Collection([$budget]); @@ -169,7 +169,7 @@ class BudgetController extends Controller $cache->addProperty($budget->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $locale = app('steam')->getLocale(); $entries = []; @@ -224,7 +224,7 @@ class BudgetController extends Controller $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $collector->setRange($start, $end); $collector->setBudget($budget); @@ -291,7 +291,7 @@ class BudgetController extends Controller $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $collector->setRange($start, $end); $collector->setBudget($budget)->withCategoryInformation(); @@ -304,7 +304,6 @@ class BudgetController extends Controller 'amount' => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_symbol' => $journal['currency_symbol'], 'currency_name' => $journal['currency_name'], ]; $result[$key]['amount'] = bcadd($journal['amount'], $result[$key]['amount']); @@ -356,7 +355,7 @@ class BudgetController extends Controller $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $collector->setRange($start, $end); $collector->setTypes([TransactionType::WITHDRAWAL])->setBudget($budget)->withAccountInformation(); @@ -411,7 +410,7 @@ class BudgetController extends Controller $cache->addProperty($end); $cache->addProperty('chart.budget.frontpage'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $chartGenerator = app(FrontpageChartGenerator::class); @@ -448,7 +447,7 @@ class BudgetController extends Controller $cache->addProperty($currency->id); $cache->addProperty('chart.budget.period'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $titleFormat = app('navigation')->preferredCarbonLocalizedFormat($start, $end); $preferredRange = app('navigation')->preferredRangeFormat($start, $end); @@ -522,7 +521,7 @@ class BudgetController extends Controller $cache->addProperty($currency->id); $cache->addProperty('chart.budget.no-budget'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } // the expenses: diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index bcf58c25c6..de6a3a5ab5 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -76,7 +76,7 @@ class CategoryController extends Controller $cache->addProperty('chart.category.all'); $cache->addProperty($category->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var CategoryRepositoryInterface $repository */ $repository = app(CategoryRepositoryInterface::class); @@ -102,8 +102,8 @@ class CategoryController extends Controller $carbon = null; try { $carbon = today(config('app.timezone')); - } catch (Exception $e) { - $e->getMessage(); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } return $carbon; @@ -125,7 +125,7 @@ class CategoryController extends Controller $cache->addProperty($end); $cache->addProperty('chart.category.frontpage'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $frontPageGenerator = new FrontpageChartGenerator($start, $end); @@ -156,7 +156,7 @@ class CategoryController extends Controller $cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($category); if ($cache->has()) { - return response()->json($cache->get());// @codeCoverageIgnore + return response()->json($cache->get()); } $data = $this->reportPeriodChart($accounts, $start, $end, $category); @@ -270,7 +270,7 @@ class CategoryController extends Controller $cache->addProperty('chart.category.period.no-cat'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $data = $this->reportPeriodChart($accounts, $start, $end, null); @@ -294,7 +294,7 @@ class CategoryController extends Controller $start = app('navigation')->startOfPeriod($date, $range); $end = session()->get('end'); if ($end < $start) { - [$end, $start] = [$start, $end]; // @codeCoverageIgnore + [$end, $start] = [$start, $end]; } $cache = new CacheProperties; @@ -303,7 +303,7 @@ class CategoryController extends Controller $cache->addProperty($category->id); $cache->addProperty('chart.category.period-chart'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var WholePeriodChartGenerator $chartGenerator */ diff --git a/app/Http/Controllers/Chart/ExpenseReportController.php b/app/Http/Controllers/Chart/ExpenseReportController.php index bfda695e27..b4041c0c2f 100644 --- a/app/Http/Controllers/Chart/ExpenseReportController.php +++ b/app/Http/Controllers/Chart/ExpenseReportController.php @@ -88,7 +88,7 @@ class ExpenseReportController extends Controller $cache->addProperty($start); $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $format = app('navigation')->preferredCarbonLocalizedFormat($start, $end); @@ -184,11 +184,11 @@ class ExpenseReportController extends Controller $newSet = []; foreach ($chartData as $key => $entry) { if (0 === !array_sum($entry['entries'])) { - $newSet[$key] = $chartData[$key]; // @codeCoverageIgnore + $newSet[$key] = $chartData[$key]; } } - if (empty($newSet)) { - $newSet = $chartData; // @codeCoverageIgnore + if (0===count($newSet)) { + $newSet = $chartData; } $data = $this->generator->multiSet($newSet); $cache->store($data); diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php index 96d7287638..c0c451ed0a 100644 --- a/app/Http/Controllers/Chart/PiggyBankController.php +++ b/app/Http/Controllers/Chart/PiggyBankController.php @@ -73,7 +73,7 @@ class PiggyBankController extends Controller $cache->addProperty('chart.piggy-bank.history'); $cache->addProperty($piggyBank->id); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $set = $repository->getEvents($piggyBank); $set = $set->reverse(); diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index 9e736e5ea9..4f7b7f91e5 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -78,7 +78,7 @@ class ReportController extends Controller $cache->addProperty(implode(',', $accounts->pluck('id')->toArray())); $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $locale = app('steam')->getLocale(); $current = clone $start; @@ -113,7 +113,7 @@ class ReportController extends Controller foreach ($result as $netWorthItem) { $currencyId = $netWorthItem['currency']->id; $label = $current->formatLocalized((string)trans('config.month_and_day', [], $locale)); - if (!isset($chartData[$currencyId])) { + if (!array_key_exists($currencyId, $chartData)) { $chartData[$currencyId] = [ 'label' => 'Net worth in ' . $netWorthItem['currency']->name, 'type' => 'line', @@ -152,7 +152,7 @@ class ReportController extends Controller $cache->addProperty($accounts); $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } Log::debug('Going to do operations for accounts ', $accounts->pluck('id')->toArray()); $format = app('navigation')->preferredCarbonFormat($start, $end); diff --git a/app/Http/Controllers/Chart/TransactionController.php b/app/Http/Controllers/Chart/TransactionController.php index f6d1aca390..76b8cc1fb8 100644 --- a/app/Http/Controllers/Chart/TransactionController.php +++ b/app/Http/Controllers/Chart/TransactionController.php @@ -66,7 +66,7 @@ class TransactionController extends Controller $cache->addProperty($end); $cache->addProperty('chart.transactions.budgets'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -111,7 +111,7 @@ class TransactionController extends Controller $cache->addProperty($objectType); $cache->addProperty('chart.transactions.categories'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -169,7 +169,7 @@ class TransactionController extends Controller $cache->addProperty($objectType); $cache->addProperty('chart.transactions.destinations'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -226,7 +226,7 @@ class TransactionController extends Controller $cache->addProperty($objectType); $cache->addProperty('chart.transactions.sources'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 6d3bbedf34..e581bdcc1c 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -36,15 +36,11 @@ use Route; */ abstract class Controller extends BaseController { - use AuthorizesRequests, DispatchesJobs, ValidatesRequests, UserNavigation, RequestInformation; + use AuthorizesRequests, DispatchesJobs, ValidatesRequests, RequestInformation, UserNavigation; - /** @var string Format for date and time. */ protected string $dateTimeFormat; - /** @var string Format for "23 Feb, 2016". */ protected string $monthAndDayFormat; - /** @var string Format for "March 2018" */ protected string $monthFormat; - /** @var string Redirect user */ protected string $redirectUri = '/'; /** diff --git a/app/Http/Controllers/CurrencyController.php b/app/Http/Controllers/CurrencyController.php index 1f950ed0b0..695b6d4739 100644 --- a/app/Http/Controllers/CurrencyController.php +++ b/app/Http/Controllers/CurrencyController.php @@ -130,12 +130,12 @@ class CurrencyController extends Controller /** @var User $user */ $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); - // @codeCoverageIgnoreEnd + } if ($this->repository->currencyInUse($currency)) { @@ -168,12 +168,12 @@ class CurrencyController extends Controller /** @var User $user */ $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to delete currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); - // @codeCoverageIgnoreEnd + } if ($this->repository->currencyInUse($currency)) { @@ -212,12 +212,12 @@ class CurrencyController extends Controller /** @var User $user */ $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to disable currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); - // @codeCoverageIgnoreEnd + } if ($this->repository->currencyInUse($currency)) { @@ -268,12 +268,12 @@ class CurrencyController extends Controller /** @var User $user */ $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code)); return redirect(route('currencies.index')); - // @codeCoverageIgnoreEnd + } $subTitleIcon = 'fa-pencil'; @@ -355,12 +355,12 @@ class CurrencyController extends Controller $user = auth()->user(); $data = $request->getCurrencyData(); if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.'); Log::channel('audit')->info('Tried to create (POST) currency without admin rights.', $data); return redirect($this->getPreviousUri('currencies.create.uri')); - // @codeCoverageIgnoreEnd + } $data['enabled'] = true; @@ -378,11 +378,11 @@ class CurrencyController extends Controller $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name])); Log::channel('audit')->info('Created (POST) currency.', $data); if (1 === (int) $request->get('create_another')) { - // @codeCoverageIgnoreStart + $request->session()->put('currencies.create.fromStore', true); $redirect = redirect(route('currencies.create'))->withInput(); - // @codeCoverageIgnoreEnd + } } @@ -406,12 +406,12 @@ class CurrencyController extends Controller $data['enabled'] = true; } if (!$this->userRepository->hasRole($user, 'owner')) { - // @codeCoverageIgnoreStart + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data); return redirect(route('currencies.index')); - // @codeCoverageIgnoreEnd + } $currency = $this->repository->update($currency, $data); Log::channel('audit')->info('Updated (POST) currency.', $data); @@ -419,11 +419,11 @@ class CurrencyController extends Controller app('preferences')->mark(); if (1 === (int) $request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + $request->session()->put('currencies.edit.fromUpdate', true); return redirect(route('currencies.edit', [$currency->id])); - // @codeCoverageIgnoreEnd + } return redirect($this->getPreviousUri('currencies.edit.uri')); diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index ae37a40589..fca31fc302 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -98,12 +98,11 @@ class DebugController extends Controller Log::debug('Call twig:clean...'); try { Artisan::call('twig:clean'); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - // don't care - Log::debug(sprintf('Called twig:clean: %s', $e->getMessage())); + + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } - // @codeCoverageIgnoreEnd + Log::debug('Call view:clear...'); Artisan::call('view:clear'); Log::debug('Done! Redirecting...'); @@ -179,12 +178,11 @@ class DebugController extends Controller if (null !== $logFile) { try { $logContent = file_get_contents($logFile); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - // don't care - Log::debug(sprintf('Could not read log file. %s', $e->getMessage())); + + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } - // @codeCoverageIgnoreEnd + } } } @@ -193,7 +191,7 @@ class DebugController extends Controller $logContent = 'Truncated from this point <----|' . substr($logContent, -8192); } - return prefixView( + return view( 'debug', compact( 'phpVersion', diff --git a/app/Http/Controllers/HelpController.php b/app/Http/Controllers/HelpController.php index f219ade592..1d3b6bdedb 100644 --- a/app/Http/Controllers/HelpController.php +++ b/app/Http/Controllers/HelpController.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Http\Controllers\RequestInformation; use Illuminate\Http\JsonResponse; /** @@ -30,8 +29,6 @@ use Illuminate\Http\JsonResponse; */ class HelpController extends Controller { - use RequestInformation; - /** * Show help for a route. * diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 4d981a1ffd..7f436b37e8 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -107,9 +107,8 @@ class HomeController extends Controller */ public function index(AccountRepositoryInterface $repository) { - $result = version_compare(phpversion(), '8.0'); - $types = config('firefly.accountTypesByIdentifier.asset'); - $count = $repository->count($types); + $types = config('firefly.accountTypesByIdentifier.asset'); + $count = $repository->count($types); Log::channel('audit')->info('User visits homepage.'); if (0 === $count) { diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index 5de2c2d2a2..31bfea6235 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -36,7 +36,6 @@ use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\CacheProperties; -use FireflyIII\Support\Http\Controllers\RequestInformation; use Illuminate\Http\JsonResponse; use Log; @@ -45,8 +44,6 @@ use Log; */ class BoxController extends Controller { - use RequestInformation; - /** * This box has three types of info to display: * 0) If the user has available amount this period and has overspent: overspent box. @@ -75,7 +72,7 @@ class BoxController extends Controller $cache->addProperty($today); $cache->addProperty('box-available'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } $leftPerDayAmount = '0'; $leftToSpendAmount = '0'; @@ -145,7 +142,7 @@ class BoxController extends Controller $cache->addProperty($end); $cache->addProperty('box-balance'); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); } // prep some arrays: $incomes = []; @@ -192,7 +189,7 @@ class BoxController extends Controller $incomes[$currencyId] = app('amount')->formatAnything($currency, $incomes[$currencyId] ?? '0', false); $expenses[$currencyId] = app('amount')->formatAnything($currency, $expenses[$currencyId] ?? '0', false); } - if (empty($sums)) { + if (0===count($sums)) { $currency = app('amount')->getDefaultCurrency(); $sums[$currency->id] = app('amount')->formatAnything($currency, '0', false); $incomes[$currency->id] = app('amount')->formatAnything($currency, '0', false); diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index bb79b73df8..110c5ec743 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -64,15 +64,15 @@ class FrontpageController extends Controller } } $html = ''; - if (!empty($info)) { + if (0!==count($info)) { try { $html = prefixView('json.piggy-banks', compact('info'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render json.piggy-banks: %s', $e->getMessage())); $html = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + } return response()->json(['html' => $html]); diff --git a/app/Http/Controllers/Json/IntroController.php b/app/Http/Controllers/Json/IntroController.php index 1f28f3a82a..2f703d31bd 100644 --- a/app/Http/Controllers/Json/IntroController.php +++ b/app/Http/Controllers/Json/IntroController.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; +use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Http\JsonResponse; use Log; @@ -29,7 +30,7 @@ use Log; /** * Class IntroController. */ -class IntroController +class IntroController extends Controller { use GetConfigurationData; @@ -53,7 +54,7 @@ class IntroController return response()->json($steps); } if ($this->hasOutroStep($route)) { - // @codeCoverageIgnoreStart + // save last step: $lastStep = $steps[count($steps) - 1]; // remove last step: @@ -61,7 +62,7 @@ class IntroController // merge arrays and add last step again $steps = array_merge($steps, $specificSteps); $steps[] = $lastStep; - // @codeCoverageIgnoreEnd + } if (!$this->hasOutroStep($route)) { $steps = array_merge($steps, $specificSteps); diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index 1aabc1a206..598def4f96 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -32,7 +32,6 @@ use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Collection; @@ -45,8 +44,6 @@ use Throwable; */ class ReconcileController extends Controller { - use UserNavigation; - private AccountRepositoryInterface $accountRepos; private CurrencyRepositoryInterface $currencyRepos; private JournalRepositoryInterface $repository; @@ -156,12 +153,12 @@ class ReconcileController extends Controller 'selectedIds' ) )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('View error: %s', $e->getMessage())); $view = sprintf('Could not render accounts.reconcile.overview: %s', $e->getMessage()); } - // @codeCoverageIgnoreEnd + $return = [ 'post_uri' => $route, 'html' => $view, @@ -184,7 +181,7 @@ class ReconcileController extends Controller Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description'])); // not much magic below we need to cover using tests. - // @codeCoverageIgnoreStart + if ($account->id === $journal['source_account_id']) { if ($currency->id === $journal['currency_id']) { $toAdd = $journal['amount']; @@ -201,7 +198,7 @@ class ReconcileController extends Controller $toAdd = bcmul($journal['foreign_amount'], '-1'); } } - // @codeCoverageIgnoreEnd + Log::debug(sprintf('Going to add %s to %s', $toAdd, $amount)); $amount = bcadd($amount, $toAdd); @@ -253,14 +250,11 @@ class ReconcileController extends Controller 'accounts.reconcile.transactions', compact('account', 'journals', 'currency', 'start', 'end', 'selectionStart', 'selectionEnd') )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render: %s', $e->getMessage())); $html = sprintf('Could not render accounts.reconcile.transactions: %s', $e->getMessage()); } - - // @codeCoverageIgnoreEnd - return response()->json(['html' => $html, 'startBalance' => $startBalance, 'endBalance' => $endBalance]); } @@ -278,7 +272,7 @@ class ReconcileController extends Controller /** @var array $journal */ foreach ($array as $journal) { $inverse = false; - // @codeCoverageIgnoreStart + if (TransactionType::DEPOSIT === $journal['transaction_type_type']) { $inverse = true; } @@ -299,7 +293,7 @@ class ReconcileController extends Controller $journal['foreign_amount'] = app('steam')->positive($journal['foreign_amount']); } } - // @codeCoverageIgnoreEnd + $journals[] = $journal; } diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index 9fe3d32b02..5e5111a427 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -51,14 +51,11 @@ class RuleController extends Controller } try { $view = prefixView('rules.partials.action', compact('actions', 'count'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render rules.partials.action: %s', $e->getMessage())); $view = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return response()->json(['html' => $view]); } @@ -84,7 +81,7 @@ class RuleController extends Controller try { $view = prefixView('rules.partials.trigger', compact('triggers', 'count'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render rules.partials.trigger: %s', $e->getMessage())); $view = 'Could not render view.'; } diff --git a/app/Http/Controllers/ObjectGroup/EditController.php b/app/Http/Controllers/ObjectGroup/EditController.php index e2d966afb7..f83b75541d 100644 --- a/app/Http/Controllers/ObjectGroup/EditController.php +++ b/app/Http/Controllers/ObjectGroup/EditController.php @@ -92,11 +92,11 @@ class EditController extends Controller $redirect = redirect($this->getPreviousUri('object-groups.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('object-groups.edit.fromUpdate', true); $redirect = redirect(route('object-groups.edit', [$piggyBank->id])); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/PiggyBank/CreateController.php b/app/Http/Controllers/PiggyBank/CreateController.php index 6ad6f2b4b7..daf969a5ce 100644 --- a/app/Http/Controllers/PiggyBank/CreateController.php +++ b/app/Http/Controllers/PiggyBank/CreateController.php @@ -111,16 +111,16 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('piggy-banks.create.uri')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + session()->put('piggy-banks.create.fromStore', true); $redirect = redirect(route('piggy-banks.create'))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php index 694f1c787d..783a6b1b78 100644 --- a/app/Http/Controllers/PiggyBank/EditController.php +++ b/app/Http/Controllers/PiggyBank/EditController.php @@ -132,16 +132,16 @@ class EditController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('piggy-banks.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('piggy-banks.edit.fromUpdate', true); $redirect = redirect(route('piggy-banks.edit', [$piggyBank->id])); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php index c14bac0b50..571c79c4bb 100644 --- a/app/Http/Controllers/PiggyBank/IndexController.php +++ b/app/Http/Controllers/PiggyBank/IndexController.php @@ -112,7 +112,7 @@ class IndexController extends Controller $account = $accountTransformer->transform($piggy->account); $accountId = (int)$account['id']; $array['attachments'] = $this->piggyRepos->getAttachments($piggy); - if (!isset($accounts[$accountId])) { + if (!array_key_exists($accountId, $accounts)) { // create new: $accounts[$accountId] = $account; diff --git a/app/Http/Controllers/Popup/ReportController.php b/app/Http/Controllers/Popup/ReportController.php index 9cb593ce9b..b6089d1976 100644 --- a/app/Http/Controllers/Popup/ReportController.php +++ b/app/Http/Controllers/Popup/ReportController.php @@ -24,7 +24,6 @@ namespace FireflyIII\Http\Controllers\Popup; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\Http\Controllers\RenderPartialViews; -use FireflyIII\Support\Http\Controllers\RequestInformation; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; @@ -34,7 +33,7 @@ use Illuminate\Http\Request; */ class ReportController extends Controller { - use RequestInformation, RenderPartialViews; + use RenderPartialViews; /** * Generate popup view. diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index ec39081f30..e61be26c82 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -32,6 +32,7 @@ use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\View\View; use JsonException; +use Log; /** * Class PreferencesController. @@ -196,20 +197,20 @@ class PreferencesController extends Controller } // optional fields for transactions: - $setOptions = $request->get('tj'); + $setOptions = $request->get('tj') ?? []; $optionalTj = [ - 'interest_date' => isset($setOptions['interest_date']), - 'book_date' => isset($setOptions['book_date']), - 'process_date' => isset($setOptions['process_date']), - 'due_date' => isset($setOptions['due_date']), - 'payment_date' => isset($setOptions['payment_date']), - 'invoice_date' => isset($setOptions['invoice_date']), - 'internal_reference' => isset($setOptions['internal_reference']), - 'notes' => isset($setOptions['notes']), - 'attachments' => isset($setOptions['attachments']), - 'external_uri' => isset($setOptions['external_uri']), - 'location' => isset($setOptions['location']), - 'links' => isset($setOptions['links']), + 'interest_date' => array_key_exists('interest_date', $setOptions), + 'book_date' => array_key_exists('book_date', $setOptions), + 'process_date' => array_key_exists('process_date', $setOptions), + 'due_date' => array_key_exists('due_date', $setOptions), + 'payment_date' => array_key_exists('payment_date', $setOptions), + 'invoice_date' => array_key_exists('invoice_date', $setOptions), + 'internal_reference' => array_key_exists('internal_reference', $setOptions), + 'notes' => array_key_exists('notes', $setOptions), + 'attachments' => array_key_exists('attachments', $setOptions), + 'external_uri' => array_key_exists('external_uri', $setOptions), + 'location' => array_key_exists('location', $setOptions), + 'links' => array_key_exists('links', $setOptions), ]; app('preferences')->set('transaction_journal_optional_fields', $optionalTj); diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index b38955156b..5163730398 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -35,7 +35,6 @@ use FireflyIII\Http\Requests\TokenFormRequest; use FireflyIII\Models\Preference; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Support\Http\Controllers\CreateStuff; -use FireflyIII\Support\Http\Controllers\RequestInformation; use FireflyIII\User; use Google2FA; use Hash; @@ -58,7 +57,7 @@ use PragmaRX\Recovery\Recovery; */ class ProfileController extends Controller { - use RequestInformation, CreateStuff; + use CreateStuff; protected bool $internalAuth; protected bool $internalIdentity; @@ -74,7 +73,7 @@ class ProfileController extends Controller $this->middleware( static function ($request, $next) { - app('view')->share('title', (string) trans('firefly.profile')); + app('view')->share('title', (string)trans('firefly.profile')); app('view')->share('mainTitleIcon', 'fa-user'); return $next($request); @@ -95,9 +94,11 @@ class ProfileController extends Controller public function logoutOtherSessions() { if (!$this->internalAuth) { - session()->flash('info', (string) trans('firefly.external_auth_disabled')); + session()->flash('info', (string)trans('firefly.external_auth_disabled')); + return redirect(route('profile.index')); } + return prefixView('profile.logout-other-sessions'); } @@ -109,7 +110,8 @@ class ProfileController extends Controller public function postLogoutOtherSessions(Request $request) { if (!$this->internalAuth) { - session()->flash('info', (string) trans('firefly.external_auth_disabled')); + session()->flash('info', (string)trans('firefly.external_auth_disabled')); + return redirect(route('profile.index')); } $creds = [ @@ -118,11 +120,11 @@ class ProfileController extends Controller ]; if (Auth::once($creds)) { Auth::logoutOtherDevices($request->get('password')); - session()->flash('info', (string) trans('firefly.other_sessions_logged_out')); + session()->flash('info', (string)trans('firefly.other_sessions_logged_out')); return redirect(route('profile.index')); } - session()->flash('error', (string) trans('auth.failed')); + session()->flash('error', (string)trans('auth.failed')); return redirect(route('profile.index')); @@ -145,7 +147,7 @@ class ProfileController extends Controller $title = auth()->user()->email; $email = auth()->user()->email; - $subTitle = (string) trans('firefly.change_your_email'); + $subTitle = (string)trans('firefly.change_your_email'); $subTitleIcon = 'fa-envelope'; return prefixView('profile.change-email', compact('title', 'subTitle', 'subTitleIcon', 'email')); @@ -167,7 +169,7 @@ class ProfileController extends Controller } $title = auth()->user()->email; - $subTitle = (string) trans('firefly.change_your_password'); + $subTitle = (string)trans('firefly.change_your_password'); $subTitleIcon = 'fa-key'; return prefixView('profile.change-password', compact('title', 'subTitle', 'subTitleIcon')); @@ -205,6 +207,7 @@ class ProfileController extends Controller } // generate codes if not in session: + $recoveryCodes = ''; if (!session()->has('temp-mfa-codes')) { // generate codes + store + flash: $recovery = app(Recovery::class); @@ -239,9 +242,9 @@ class ProfileController extends Controller public function confirmEmailChange(UserRepositoryInterface $repository, string $token) { if (!$this->internalAuth || !$this->internalIdentity) { - // @codeCoverageIgnoreStart + throw new FireflyException(trans('firefly.external_user_mgt_disabled')); - // @codeCoverageIgnoreEnd + } // find preference with this token value. /** @var Collection $set */ @@ -260,7 +263,7 @@ class ProfileController extends Controller $repository->unblockUser($user); // return to login. - session()->flash('success', (string) trans('firefly.login_with_new_email')); + session()->flash('success', (string)trans('firefly.login_with_new_email')); return redirect(route('login')); } @@ -280,7 +283,7 @@ class ProfileController extends Controller return redirect(route('profile.index')); } $title = auth()->user()->email; - $subTitle = (string) trans('firefly.delete_account'); + $subTitle = (string)trans('firefly.delete_account'); $subTitleIcon = 'fa-trash'; return prefixView('profile.delete-account', compact('title', 'subTitle', 'subTitleIcon')); @@ -305,8 +308,8 @@ class ProfileController extends Controller $user = auth()->user(); $repository->setMFACode($user, null); - session()->flash('success', (string) trans('firefly.pref_two_factor_auth_disabled')); - session()->flash('info', (string) trans('firefly.pref_two_factor_auth_remove_it')); + session()->flash('success', (string)trans('firefly.pref_two_factor_auth_disabled')); + session()->flash('info', (string)trans('firefly.pref_two_factor_auth_remove_it')); return redirect(route('profile.index')); } @@ -335,7 +338,7 @@ class ProfileController extends Controller // If FF3 already has a secret, just set the two factor auth enabled to 1, // and let the user continue with the existing secret. - session()->flash('info', (string) trans('firefly.2fa_already_enabled')); + session()->flash('info', (string)trans('firefly.2fa_already_enabled')); return redirect(route('profile.index')); } @@ -370,7 +373,9 @@ class ProfileController extends Controller $accessToken = app('preferences')->set('access_token', $token); } - return prefixView('profile.index', compact('subTitle', 'mfaBackupCount', 'userId', 'accessToken', 'enabled2FA', 'isInternalAuth','isInternalIdentity')); + return prefixView( + 'profile.index', compact('subTitle', 'mfaBackupCount', 'userId', 'accessToken', 'enabled2FA', 'isInternalAuth', 'isInternalIdentity') + ); } /** @@ -420,7 +425,7 @@ class ProfileController extends Controller $newEmail = $request->string('email'); $oldEmail = $user->email; if ($newEmail === $user->email) { - session()->flash('error', (string) trans('firefly.email_not_changed')); + session()->flash('error', (string)trans('firefly.email_not_changed')); return redirect(route('profile.change-email'))->withInput(); } @@ -430,7 +435,7 @@ class ProfileController extends Controller Auth::guard()->logout(); $request->session()->invalidate(); - session()->flash('success', (string) trans('firefly.email_changed')); + session()->flash('success', (string)trans('firefly.email_changed')); return redirect(route('index')); } @@ -445,7 +450,7 @@ class ProfileController extends Controller // force user logout. Auth::guard()->logout(); $request->session()->invalidate(); - session()->flash('success', (string) trans('firefly.email_changed')); + session()->flash('success', (string)trans('firefly.email_changed')); return redirect(route('index')); } @@ -480,7 +485,7 @@ class ProfileController extends Controller } $repository->changePassword($user, $request->get('new_password')); - session()->flash('success', (string) trans('firefly.password_changed')); + session()->flash('success', (string)trans('firefly.password_changed')); return redirect(route('profile.index')); } @@ -509,7 +514,7 @@ class ProfileController extends Controller $secret = session()->get('two-factor-secret'); $repository->setMFACode($user, $secret); - session()->flash('success', (string) trans('firefly.saved_preferences')); + session()->flash('success', (string)trans('firefly.saved_preferences')); app('preferences')->mark(); // also save the code so replay attack is prevented. @@ -547,7 +552,7 @@ class ProfileController extends Controller } if (!Hash::check($request->get('password'), auth()->user()->password)) { - session()->flash('error', (string) trans('firefly.invalid_password')); + session()->flash('error', (string)trans('firefly.invalid_password')); return redirect(route('profile.delete-account')); } @@ -579,7 +584,7 @@ class ProfileController extends Controller $user = auth()->user(); $token = $user->generateAccessToken(); app('preferences')->set('access_token', $token); - session()->flash('success', (string) trans('firefly.token_regenerated')); + session()->flash('success', (string)trans('firefly.token_regenerated')); return redirect(route('profile.index')); } @@ -619,7 +624,7 @@ class ProfileController extends Controller /** @var string $match */ $match = null; foreach ($set as $entry) { - $hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $entry->data)); + $hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $entry->data)); if ($hashed === $hash) { $match = $entry->data; break; @@ -634,7 +639,7 @@ class ProfileController extends Controller $repository->unblockUser($user); // return to login. - session()->flash('success', (string) trans('firefly.login_with_old_email')); + session()->flash('success', (string)trans('firefly.login_with_old_email')); return redirect(route('login')); } diff --git a/app/Http/Controllers/Recurring/CreateController.php b/app/Http/Controllers/Recurring/CreateController.php index 1f19e1bfd7..fcc81e3a7b 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -240,7 +240,7 @@ class CreateController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('recurring.create.uri')); diff --git a/app/Http/Controllers/Recurring/EditController.php b/app/Http/Controllers/Recurring/EditController.php index 765120fb10..6610053912 100644 --- a/app/Http/Controllers/Recurring/EditController.php +++ b/app/Http/Controllers/Recurring/EditController.php @@ -103,7 +103,7 @@ class EditController extends Controller $repetition = $recurrence->recurrenceRepetitions()->first(); $currentRepType = $repetition->repetition_type; if ('' !== $repetition->repetition_moment) { - $currentRepType .= ',' . $repetition->repetition_moment; // @codeCoverageIgnore + $currentRepType .= ',' . $repetition->repetition_moment; } // put previous url in session if not redirect from store (not "return_to_edit"). @@ -119,10 +119,10 @@ class EditController extends Controller 'times' => (string)trans('firefly.repeat_times'), ]; if (null !== $recurrence->repeat_until) { - $repetitionEnd = 'until_date'; // @codeCoverageIgnore + $repetitionEnd = 'until_date'; } if ($recurrence->repetitions > 0) { - $repetitionEnd = 'times'; // @codeCoverageIgnore + $repetitionEnd = 'times'; } $weekendResponses = [ @@ -140,7 +140,8 @@ class EditController extends Controller 'deposit_source_id' => $array['transactions'][0]['source_id'], 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'], ]; - $array['first_date'] = substr($array['first_date'], 0, 10); + $array['first_date'] = substr((string)$array['first_date'], 0, 10); + $array['repeat_until'] = substr((string)$array['repeat_until'], 0, 10); $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); return prefixView( @@ -176,7 +177,7 @@ class EditController extends Controller } if (count($this->attachments->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('recurrences.edit.uri')); diff --git a/app/Http/Controllers/Recurring/IndexController.php b/app/Http/Controllers/Recurring/IndexController.php index 63a0e49dd2..c385b8ec22 100644 --- a/app/Http/Controllers/Recurring/IndexController.php +++ b/app/Http/Controllers/Recurring/IndexController.php @@ -122,6 +122,7 @@ class IndexController extends Controller } $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); $paginator->setPath(route('recurring.index')); + $today = today(config('app.timezone')); $this->verifyRecurringCronJob(); diff --git a/app/Http/Controllers/Report/AccountController.php b/app/Http/Controllers/Report/AccountController.php index 1fba3e855f..2bd37602a3 100644 --- a/app/Http/Controllers/Report/AccountController.php +++ b/app/Http/Controllers/Report/AccountController.php @@ -55,7 +55,7 @@ class AccountController extends Controller $cache->addProperty('account-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var AccountTaskerInterface $accountTasker */ @@ -63,12 +63,12 @@ class AccountController extends Controller $accountReport = $accountTasker->getAccountReport($accounts, $start, $end); try { $result = prefixView('reports.partials.accounts', compact('accountReport'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.accounts: %s', $e->getMessage())); $result = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + $cache->store($result); return $result; diff --git a/app/Http/Controllers/Report/BalanceController.php b/app/Http/Controllers/Report/BalanceController.php index 4613e1c506..88f79205e7 100644 --- a/app/Http/Controllers/Report/BalanceController.php +++ b/app/Http/Controllers/Report/BalanceController.php @@ -137,8 +137,8 @@ class BalanceController extends Controller } try { $result = prefixView('reports.partials.balance', compact('report'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.balance: %s', $e->getMessage())); $result = 'Could not render view.'; } diff --git a/app/Http/Controllers/Report/BillController.php b/app/Http/Controllers/Report/BillController.php index 4f92954c24..0c14c605ac 100644 --- a/app/Http/Controllers/Report/BillController.php +++ b/app/Http/Controllers/Report/BillController.php @@ -49,19 +49,19 @@ class BillController extends Controller $cache->addProperty('bill-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var ReportHelperInterface $helper */ $helper = app(ReportHelperInterface::class); $report = $helper->getBillReport($accounts, $start, $end); try { $result = prefixView('reports.partials.bills', compact('report'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budgets: %s', $e->getMessage())); $result = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + $cache->store($result); return $result; diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index d455ba5e3d..31efb8aee7 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -197,8 +197,8 @@ class BudgetController extends Controller try { $result = prefixView('reports.budget.partials.avg-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -316,7 +316,7 @@ class BudgetController extends Controller $cache->addProperty('budget-period-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $periods = app('navigation')->listOfPeriods($start, $end); @@ -352,12 +352,12 @@ class BudgetController extends Controller } try { $result = prefixView('reports.partials.budget-period', compact('report', 'periods'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + $cache->store($result); return $result; @@ -404,8 +404,8 @@ class BudgetController extends Controller try { $result = prefixView('reports.budget.partials.top-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line 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/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index 15561046e8..6fb33635bc 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -311,8 +311,8 @@ class CategoryController extends Controller try { $result = prefixView('reports.category.partials.avg-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -363,8 +363,8 @@ class CategoryController extends Controller try { $result = prefixView('reports.category.partials.avg-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -497,7 +497,7 @@ class CategoryController extends Controller $cache->addProperty('category-period-expenses-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // depending on the carbon format (a reliable way to determine the general date difference) @@ -547,12 +547,12 @@ class CategoryController extends Controller try { $result = prefixView('reports.partials.category-period', compact('report', 'periods'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); } - // @codeCoverageIgnoreEnd + $cache->store($result); @@ -577,7 +577,7 @@ class CategoryController extends Controller $cache->addProperty('category-period-income-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // depending on the carbon format (a reliable way to determine the general date difference) @@ -626,12 +626,12 @@ class CategoryController extends Controller try { $result = prefixView('reports.partials.category-period', compact('report', 'periods'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); } - // @codeCoverageIgnoreEnd + $cache->store($result); @@ -657,7 +657,7 @@ class CategoryController extends Controller $cache->addProperty('category-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var CategoryReportGenerator $generator */ @@ -668,17 +668,14 @@ class CategoryController extends Controller $generator->operations(); $report = $generator->getReport(); - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.partials.categories', compact('report'))->render(); $cache->store($result); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); } - - // @codeCoverageIgnoreEnd - return $result; } @@ -723,8 +720,8 @@ class CategoryController extends Controller try { $result = prefixView('reports.category.partials.top-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -773,8 +770,8 @@ class CategoryController extends Controller try { $result = prefixView('reports.category.partials.top-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line 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 0cd1bf0bc5..4436c6f3a6 100644 --- a/app/Http/Controllers/Report/DoubleController.php +++ b/app/Http/Controllers/Report/DoubleController.php @@ -111,8 +111,8 @@ class DoubleController extends Controller try { $result = prefixView('reports.double.partials.avg-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -163,8 +163,8 @@ class DoubleController extends Controller try { $result = prefixView('reports.double.partials.avg-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -457,8 +457,8 @@ class DoubleController extends Controller try { $result = prefixView('reports.double.partials.top-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -507,8 +507,8 @@ class DoubleController extends Controller try { $result = prefixView('reports.double.partials.top-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line 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/OperationsController.php b/app/Http/Controllers/Report/OperationsController.php index 0dc06329eb..2863f049df 100644 --- a/app/Http/Controllers/Report/OperationsController.php +++ b/app/Http/Controllers/Report/OperationsController.php @@ -76,18 +76,18 @@ class OperationsController extends Controller $cache->addProperty('expense-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $report = $this->tasker->getExpenseReport($start, $end, $accounts); $type = 'expense-entry'; try { $result = prefixView('reports.partials.income-expenses', compact('report', 'type'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.income-expense: %s', $e->getMessage())); $result = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + $cache->store($result); return $result; @@ -111,18 +111,18 @@ class OperationsController extends Controller $cache->addProperty('income-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $report = $this->tasker->getIncomeReport($start, $end, $accounts); $type = 'income-entry'; try { $result = prefixView('reports.partials.income-expenses', compact('report', 'type'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.income-expenses: %s', $e->getMessage())); $result = 'Could not render view.'; } - // @codeCoverageIgnoreEnd + $cache->store($result); return $result; @@ -146,7 +146,7 @@ class OperationsController extends Controller $cache->addProperty('inc-exp-report'); $cache->addProperty($accounts->pluck('id')->toArray()); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $incomes = $this->tasker->getIncomeReport($start, $end, $accounts); @@ -172,7 +172,7 @@ class OperationsController extends Controller try { $result = prefixView('reports.partials.operations', compact('sums'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.operations: %s', $e->getMessage())); $result = 'Could not render view.'; } diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index 48a506d581..d5c980ad91 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -305,8 +305,8 @@ class TagController extends Controller try { $result = prefixView('reports.tag.partials.avg-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -357,8 +357,8 @@ class TagController extends Controller try { $result = prefixView('reports.tag.partials.avg-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -515,8 +515,8 @@ class TagController extends Controller try { $result = prefixView('reports.tag.partials.top-expenses', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); $result = sprintf('Could not render view: %s', $e->getMessage()); } @@ -565,8 +565,8 @@ class TagController extends Controller try { $result = prefixView('reports.tag.partials.top-income', compact('result'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line 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/ReportController.php b/app/Http/Controllers/ReportController.php index d4e5c9f2a7..6fe28b026b 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -88,7 +88,7 @@ class ReportController extends Controller public function auditReport(Collection $accounts, Carbon $start, Carbon $end) { if ($end < $start) { - return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -124,7 +124,7 @@ class ReportController extends Controller public function budgetReport(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { if ($end < $start) { - return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -161,7 +161,7 @@ class ReportController extends Controller public function categoryReport(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { if ($end < $start) { - return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -421,7 +421,7 @@ class ReportController extends Controller public function tagReport(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { if ($end < $start) { - return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return prefixView('error')->with('message', (string)trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); diff --git a/app/Http/Controllers/Rule/CreateController.php b/app/Http/Controllers/Rule/CreateController.php index d993936df4..d0ed539094 100644 --- a/app/Http/Controllers/Rule/CreateController.php +++ b/app/Http/Controllers/Rule/CreateController.php @@ -192,7 +192,7 @@ class CreateController extends Controller */ public function createFromJournal(Request $request, TransactionJournal $journal) { - $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_journal', ['name' => e($journal->name)])); + $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_journal', ['name' => e($journal->description)])); $subTitleIcon = 'fa-clone'; $subTitle = (string)trans('firefly.make_new_rule_no_group'); @@ -267,21 +267,21 @@ class CreateController extends Controller // redirect to show bill. if ('true' === $request->get('return_to_bill') && (int)$request->get('bill_id') > 0) { - return redirect(route('bills.show', [(int)$request->get('bill_id')])); // @codeCoverageIgnore + return redirect(route('bills.show', [(int)$request->get('bill_id')])); } // redirect to new bill creation. if ((int)$request->get('bill_id') > 0) { - return redirect($this->getPreviousUri('bills.create.uri')); // @codeCoverageIgnore + return redirect($this->getPreviousUri('bills.create.uri')); } $redirect = redirect($this->getPreviousUri('rules.create.uri')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + session()->put('rules.create.fromStore', true); $redirect = redirect(route('rules.create', [$data['rule_group_id']]))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php index 8dcec9c785..9ba0f7fd6f 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -168,7 +168,7 @@ class EditController extends Controller 'triggers' => $triggers, ] )->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } @@ -195,11 +195,11 @@ class EditController extends Controller app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('rules.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('rules.edit.fromUpdate', true); $redirect = redirect(route('rules.edit', [$rule->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index 4299fce5e3..e6f1f86893 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -29,7 +29,6 @@ use FireflyIII\Http\Requests\SelectTransactionsRequest; use FireflyIII\Http\Requests\TestRuleFormRequest; use FireflyIII\Models\Rule; use FireflyIII\Models\RuleTrigger; -use FireflyIII\Support\Http\Controllers\RequestInformation; use FireflyIII\Support\Http\Controllers\RuleManagement; use FireflyIII\TransactionRules\Engine\RuleEngineInterface; use FireflyIII\TransactionRules\TransactionMatcher; @@ -48,7 +47,7 @@ use Throwable; */ class SelectController extends Controller { - use RuleManagement, RequestInformation; + use RuleManagement; /** * RuleController constructor. @@ -146,7 +145,7 @@ class SelectController extends Controller // warn if nothing. if (0 === count($textTriggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore + return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); } foreach ($textTriggers as $textTrigger) { @@ -169,22 +168,19 @@ class SelectController extends Controller // Warn the user if only a subset of transactions is returned $warning = ''; if (0 === count($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); // @codeCoverageIgnore + $warning = (string)trans('firefly.warning_no_matching_transactions'); } // Return json response $view = 'ERROR, see logs.'; try { $view = prefixView('list.journals-array-tiny', ['groups' => $collection])->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $exception) { + + } catch (Throwable $exception) { // @phpstan-ignore-line Log::error(sprintf('Could not render view in testTriggers(): %s', $exception->getMessage())); Log::error($exception->getTraceAsString()); $view = sprintf('Could not render list.journals-tiny: %s', $exception->getMessage()); } - - // @codeCoverageIgnoreEnd - return response()->json(['html' => $view, 'warning' => $warning]); } @@ -202,7 +198,7 @@ class SelectController extends Controller $triggers = $rule->ruleTriggers; if (0 === count($triggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore + return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); } // create new rule engine: $newRuleEngine = app(RuleEngineInterface::class); @@ -214,21 +210,18 @@ class SelectController extends Controller $warning = ''; if (0 === count($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); // @codeCoverageIgnore + $warning = (string)trans('firefly.warning_no_matching_transactions'); } // Return json response $view = 'ERROR, see logs.'; try { $view = prefixView('list.journals-array-tiny', ['groups' => $collection])->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $exception) { + + } catch (Throwable $exception) { // @phpstan-ignore-line Log::error(sprintf('Could not render view in testTriggersByRule(): %s', $exception->getMessage())); Log::error($exception->getTraceAsString()); } - - // @codeCoverageIgnoreEnd - return response()->json(['html' => $view, 'warning' => $warning]); } } diff --git a/app/Http/Controllers/RuleGroup/CreateController.php b/app/Http/Controllers/RuleGroup/CreateController.php index 9c4456544e..bf901a11e4 100644 --- a/app/Http/Controllers/RuleGroup/CreateController.php +++ b/app/Http/Controllers/RuleGroup/CreateController.php @@ -96,11 +96,11 @@ class CreateController extends Controller $redirect = redirect($this->getPreviousUri('rule-groups.create.uri')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + session()->put('rule-groups.create.fromStore', true); $redirect = redirect(route('rule-groups.create'))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; diff --git a/app/Http/Controllers/RuleGroup/EditController.php b/app/Http/Controllers/RuleGroup/EditController.php index f7ff347786..0a962da6ee 100644 --- a/app/Http/Controllers/RuleGroup/EditController.php +++ b/app/Http/Controllers/RuleGroup/EditController.php @@ -137,7 +137,7 @@ class EditController extends Controller { $data = [ 'title' => $request->string('title'), - 'description' => $request->nlString('description'), + 'description' => $request->stringWithNewlines('description'), 'active' => 1 === (int)$request->input('active'), ]; @@ -147,11 +147,11 @@ class EditController extends Controller app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('rule-groups.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('rule-groups.edit.fromUpdate', true); $redirect = redirect(route('rule-groups.edit', [$ruleGroup->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } // redirect to previous URL. diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index aa55db88ba..8cc438eaff 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -116,14 +116,11 @@ class SearchController extends Controller try { $html = prefixView('search.search', compact('groups', 'hasPages', 'searchTime'))->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render search.search: %s', $e->getMessage())); $html = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return response()->json(['count' => $groups->count(), 'html' => $html]); } } diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index 5460890474..ad808437e3 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -32,10 +32,10 @@ use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Illuminate\Support\Arr; use Illuminate\View\View; use Laravel\Passport\Passport; use Log; +use phpseclib\Crypt\RSA as LegacyRSA; use phpseclib3\Crypt\RSA; /** @@ -192,7 +192,7 @@ class InstallController extends Controller Artisan::call($command, $args); Log::debug(Artisan::output()); } - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); Log::error($e->getTraceAsString()); if (strpos($e->getMessage(), 'open_basedir restriction in effect')) { @@ -205,7 +205,7 @@ class InstallController extends Controller return false; } // clear cache as well. - Cache::clear(); + Cache::clear(); // @phpstan-ignore-line Preferences::mark(); return true; @@ -217,18 +217,18 @@ class InstallController extends Controller public function keys(): void { // switch on PHP version. - $result = version_compare(phpversion(), '8.0'); - Log::info(sprintf('PHP version is %s', $result)); - if (-1 === $result) { - Log::info('Will run PHP7 code.'); + $keys = []; + // switch on class existence. + Log::info(sprintf('PHP version is %s', phpversion())); + if (class_exists(LegacyRSA::class)) { // PHP 7 - $rsa = new \phpseclib\Crypt\RSA; - $keys = $rsa->createKey(4096); + Log::info('Will run PHP7 code.'); + $keys = (new LegacyRSA)->createKey(4096); } - if ($result >= 0) { - Log::info('Will run PHP8 code.'); + if (!class_exists(LegacyRSA::class)) { // PHP 8 + Log::info('Will run PHP8 code.'); $keys = RSA::createKey(4096); } @@ -241,7 +241,7 @@ class InstallController extends Controller return; } - file_put_contents($publicKey, Arr::get($keys, 'publickey')); - file_put_contents($privateKey, Arr::get($keys, 'privatekey')); + file_put_contents($publicKey, $keys['publickey']); + file_put_contents($privateKey, $keys['privatekey']); } } diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php index 5f32e14a81..e28c06a657 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -327,15 +327,15 @@ class TagController extends Controller } if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('tags.create.uri')); if (1 === (int)$request->get('create_another')) { - // @codeCoverageIgnoreStart + session()->put('tags.create.fromStore', true); $redirect = redirect(route('tags.create'))->withInput(); - // @codeCoverageIgnoreEnd + } return $redirect; @@ -368,15 +368,15 @@ class TagController extends Controller } if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { - $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); // @codeCoverageIgnore + $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('tags.edit.uri')); if (1 === (int)$request->get('return_to_edit')) { - // @codeCoverageIgnoreStart + session()->put('tags.edit.fromUpdate', true); $redirect = redirect(route('tags.edit', [$tag->id]))->withInput(['return_to_edit' => 1]); - // @codeCoverageIgnoreEnd + } // redirect to previous URL. diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index d7ddfbd8f6..8e62d6c105 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -35,7 +35,6 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Services\Internal\Update\JournalUpdateService; use FireflyIII\Support\Http\Controllers\ModelInformation; -use FireflyIII\Support\Http\Controllers\UserNavigation; use FireflyIII\Transformers\TransactionGroupTransformer; use FireflyIII\Validation\AccountValidator; use Illuminate\Contracts\View\Factory; @@ -52,7 +51,7 @@ use Log; */ class ConvertController extends Controller { - use ModelInformation, UserNavigation; + use ModelInformation; private AccountRepositoryInterface $accountRepository; private JournalRepositoryInterface $repository; @@ -92,7 +91,7 @@ class ConvertController extends Controller public function index(TransactionType $destinationType, TransactionGroup $group) { if (!$this->isEditableGroup($group)) { - return $this->redirectGroupToAccount($group); // @codeCoverageIgnore + return $this->redirectGroupToAccount($group); } /** @var TransactionGroupTransformer $transformer */ @@ -160,21 +159,21 @@ class ConvertController extends Controller $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); $name = $account->name; if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore + $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore + $role = 'l_' . $account->accountType->type; } if (AccountType::CASH === $account->accountType->type) { - // @codeCoverageIgnoreStart + $role = 'cash_account'; $name = sprintf('(%s)', trans('firefly.cash')); - // @codeCoverageIgnoreEnd + } if (AccountType::REVENUE === $account->accountType->type) { - $role = 'revenue_account'; // @codeCoverageIgnore + $role = 'revenue_account'; } $key = (string)trans('firefly.opt_group_' . $role); @@ -201,21 +200,21 @@ class ConvertController extends Controller $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); $name = $account->name; if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore + $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore + $role = 'l_' . $account->accountType->type; } if (AccountType::CASH === $account->accountType->type) { - // @codeCoverageIgnoreStart + $role = 'cash_account'; $name = sprintf('(%s)', trans('firefly.cash')); - // @codeCoverageIgnoreEnd + } if (AccountType::EXPENSE === $account->accountType->type) { - $role = 'expense_account'; // @codeCoverageIgnore + $role = 'expense_account'; } $key = (string)trans('firefly.opt_group_' . $role); @@ -265,7 +264,7 @@ class ConvertController extends Controller $currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency; $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore + $role = 'no_account_type'; } $key = (string)trans('firefly.opt_group_' . $role); @@ -289,7 +288,7 @@ class ConvertController extends Controller public function postIndex(Request $request, TransactionType $destinationType, TransactionGroup $group) { if (!$this->isEditableGroup($group)) { - return $this->redirectGroupToAccount($group); // @codeCoverageIgnore + return $this->redirectGroupToAccount($group); } /** @var TransactionJournal $journal */ diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index 4858a8f454..8a38cf7a57 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -77,7 +77,7 @@ class CreateController extends Controller $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; $link = route('transactions.show', [$newGroup->id]); session()->flash('success', trans('firefly.stored_journal', ['description' => $title])); - session()->flash('success_uri', $link); + session()->flash('success_url', $link); return redirect(route('transactions.show', [$newGroup->id])); } @@ -85,9 +85,9 @@ class CreateController extends Controller /** * Create a new transaction group. * - * @param string|null objectType + * @param string|null $objectType * - * @return Factory|View + * @return Factory|\Illuminate\Contracts\View\View */ public function create(?string $objectType) { diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php index 0c8ca3785a..aae5daabf5 100644 --- a/app/Http/Controllers/Transaction/DeleteController.php +++ b/app/Http/Controllers/Transaction/DeleteController.php @@ -26,7 +26,6 @@ namespace FireflyIII\Http\Controllers\Transaction; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Log; @@ -38,10 +37,7 @@ use URL; */ class DeleteController extends Controller { - use UserNavigation; - - /** @var TransactionGroupRepositoryInterface */ - private $repository; + private TransactionGroupRepositoryInterface $repository; /** * IndexController constructor. @@ -70,12 +66,12 @@ class DeleteController extends Controller * * @param TransactionGroup $group * - * @return RedirectResponse|Redirector|View + * @return mixed */ public function delete(TransactionGroup $group) { if (!$this->isEditableGroup($group)) { - return $this->redirectGroupToAccount($group); // @codeCoverageIgnore + return $this->redirectGroupToAccount($group); } Log::debug(sprintf('Start of delete view for group #%d', $group->id)); @@ -104,7 +100,7 @@ class DeleteController extends Controller public function destroy(TransactionGroup $group): RedirectResponse { if (!$this->isEditableGroup($group)) { - return $this->redirectGroupToAccount($group); // @codeCoverageIgnore + return $this->redirectGroupToAccount($group); } $journal = $group->transactionJournals->first(); diff --git a/app/Http/Controllers/Transaction/EditController.php b/app/Http/Controllers/Transaction/EditController.php index 4c5657ed80..ff9f2a9c37 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -26,7 +26,6 @@ namespace FireflyIII\Http\Controllers\Transaction; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; @@ -37,8 +36,6 @@ use Illuminate\View\View; */ class EditController extends Controller { - use UserNavigation; - /** * EditController constructor. * @@ -70,7 +67,7 @@ class EditController extends Controller app('preferences')->mark(); if (!$this->isEditableGroup($transactionGroup)) { - return $this->redirectGroupToAccount($transactionGroup); // @codeCoverageIgnore + return $this->redirectGroupToAccount($transactionGroup); } /** @var AccountRepositoryInterface $repository */ diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index b3a3bb7c28..7a2ade3c32 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -168,7 +168,7 @@ class MassController extends Controller $journalIds = $request->get('journals'); if (!is_array($journalIds)) { // TODO something error. - throw new FireflyException('This is not an array.'); // @codeCoverageIgnore + throw new FireflyException('This is not an array.'); } $count = 0; /** @var string $journalId */ @@ -177,8 +177,8 @@ class MassController extends Controller try { $this->updateJournal($integer, $request); $count++; - } catch (FireflyException $e) { // @codeCoverageIgnore - // do something with error. + } catch (FireflyException $e) { + // @ignoreException } } @@ -199,7 +199,7 @@ class MassController extends Controller { $journal = $this->repository->findNull($journalId); if (null === $journal) { - throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId)); } $service = app(JournalUpdateService::class); // for each field, call the update service. @@ -240,7 +240,7 @@ class MassController extends Controller if (!is_array($value)) { return null; } - if (!isset($value[$journalId])) { + if (!array_key_exists($journalId, $value)) { return null; } try { @@ -268,7 +268,7 @@ class MassController extends Controller if (!is_array($value)) { return null; } - if (!isset($value[$journalId])) { + if (!array_key_exists($journalId, $value)) { return null; } @@ -289,7 +289,7 @@ class MassController extends Controller if (!is_array($value)) { return null; } - if (!isset($value[$journalId])) { + if (!array_key_exists($journalId, $value)) { return null; } diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php index 1b5e3901cf..e6deb0e5c7 100644 --- a/app/Http/Controllers/Transaction/ShowController.php +++ b/app/Http/Controllers/Transaction/ShowController.php @@ -137,7 +137,7 @@ class ShowController extends Controller $amounts = []; foreach ($group['transactions'] as $transaction) { $symbol = $transaction['currency_symbol']; - if (!isset($amounts[$symbol])) { + if (!array_key_exists($symbol, $amounts)) { $amounts[$symbol] = [ 'amount' => '0', 'symbol' => $symbol, @@ -148,7 +148,7 @@ class ShowController extends Controller if (null !== $transaction['foreign_amount']) { // same for foreign currency: $foreignSymbol = $transaction['foreign_currency_symbol']; - if (!isset($amounts[$foreignSymbol])) { + if (!array_key_exists($foreignSymbol, $amounts)) { $amounts[$foreignSymbol] = [ 'amount' => '0', 'symbol' => $foreignSymbol, diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index bfc785315f..2c087122f8 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -26,6 +26,7 @@ namespace FireflyIII\Http\Middleware; use Closure; use FireflyIII\Exceptions\FireflyException; +use FireflyIII\User; use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Database\QueryException; @@ -77,8 +78,8 @@ class Authenticate /** * Determine if the user is logged in to any of the given guards. * - * @param $request - * @param array $guards + * @param mixed $request + * @param array $guards * * @return mixed * @throws FireflyException @@ -87,7 +88,7 @@ class Authenticate protected function authenticate($request, array $guards) { - if (empty($guards)) { + if (0 === count($guards)) { try { // go for default guard: /** @noinspection PhpUndefinedMethodInspection */ @@ -95,6 +96,7 @@ class Authenticate // do an extra check on user object. /** @noinspection PhpUndefinedMethodInspection */ + /** @var User $user */ $user = $this->auth->authenticate(); if (1 === (int)$user->blocked) { $message = (string)trans('firefly.block_account_logout'); @@ -109,29 +111,29 @@ class Authenticate } } } catch (QueryException $e) { - // @codeCoverageIgnoreStart + throw new FireflyException( sprintf( 'It seems the database has not yet been initialized. Did you run the correct upgrade or installation commands? Error: %s', $e->getMessage() - ) + ), 0, $e ); - // @codeCoverageIgnoreEnd + } /** @noinspection PhpUndefinedMethodInspection */ return $this->auth->authenticate(); } - // @codeCoverageIgnoreStart + foreach ($guards as $guard) { if ($this->auth->guard($guard)->check()) { /** @noinspection PhpVoidFunctionResultUsedInspection */ - return $this->auth->shouldUse($guard); + return $this->auth->shouldUse($guard); // @phpstan-ignore-line } } throw new AuthenticationException('Unauthenticated.', $guards); - // @codeCoverageIgnoreEnd + } } diff --git a/app/Http/Middleware/Binder.php b/app/Http/Middleware/Binder.php index 3785604353..ace2cf4bc2 100644 --- a/app/Http/Middleware/Binder.php +++ b/app/Http/Middleware/Binder.php @@ -57,7 +57,6 @@ class Binder $this->auth = $auth; } - /** @noinspection PhpUnusedParameterInspection */ /** * Handle an incoming request. * @@ -70,7 +69,7 @@ class Binder public function handle($request, Closure $next) { foreach ($request->route()->parameters() as $key => $value) { - if (isset($this->binders[$key])) { + if (array_key_exists($key, $this->binders)) { $boundObject = $this->performBinding($key, $value, $request->route()); $request->route()->setParameter($key, $boundObject); } @@ -82,9 +81,9 @@ class Binder /** * Do the binding. * - * @param $key - * @param $value - * @param $route + * @param string $key + * @param string $value + * @param Route $route * * @return mixed */ diff --git a/app/Http/Middleware/Installer.php b/app/Http/Middleware/Installer.php index cb728680f9..465b5f51fb 100644 --- a/app/Http/Middleware/Installer.php +++ b/app/Http/Middleware/Installer.php @@ -95,7 +95,9 @@ class Installer $message = $e->getMessage(); Log::error(sprintf('Error message trying to access users-table: %s', $message)); if ($this->isAccessDenied($message)) { - throw new FireflyException('It seems your database configuration is not correct. Please verify the username and password in your .env file.'); + throw new FireflyException( + 'It seems your database configuration is not correct. Please verify the username and password in your .env file.', 0, $e + ); } if ($this->noTablesExist($message)) { // redirect to UpdateController @@ -103,7 +105,7 @@ class Installer return true; } - throw new FireflyException(sprintf('Could not access the database: %s', $message)); + throw new FireflyException(sprintf('Could not access the database: %s', $message), 0, $e); } Log::debug('Everything seems OK with the tables.'); diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index c2e729c3e3..0d199782dc 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\TransactionGroup; use FireflyIII\Models\TransactionJournal; use Illuminate\Http\Request; @@ -53,6 +54,10 @@ class InterestingMessage Preferences::mark(); $this->handleGroupMessage($request); } + if ($this->accountMessage($request)) { + Preferences::mark(); + $this->handleAccountMessage($request); + } return $next($request); } @@ -80,6 +85,28 @@ class InterestingMessage return null !== $transactionGroupId && null !== $message; } + /** + * @param Request $request + */ + private function handleAccountMessage(Request $request): void { + + // get parameters from request. + $accountId = $request->get('account_id'); + $message = $request->get('message'); + + /** @var Account $account */ + $account = auth()->user()->accounts()->withTrashed()->find($accountId); + + if (null === $account) { + return; + } + if ('deleted' === $message) { + session()->flash('success', (string)trans('firefly.account_deleted', ['name' => $account->name])); + } + if('created' === $message) { + session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name])); + } + } /** * @param Request $request */ @@ -107,18 +134,32 @@ class InterestingMessage } $title = $count > 1 ? $group->title : $journal->description; if ('created' === $message) { - session()->flash('success_uri', route('transactions.show', [$transactionGroupId])); + session()->flash('success_url', route('transactions.show', [$transactionGroupId])); session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $title])); } if ('updated' === $message) { $type = strtolower($journal->transactionType->type); - session()->flash('success_uri', route('transactions.show', [$transactionGroupId])); + session()->flash('success_url', route('transactions.show', [$transactionGroupId])); session()->flash('success', (string)trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); } if ('no_change' === $message) { $type = strtolower($journal->transactionType->type); - session()->flash('warning_uri', route('transactions.show', [$transactionGroupId])); + session()->flash('warning_url', route('transactions.show', [$transactionGroupId])); session()->flash('warning', (string)trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title])); } } + + /** + * @param Request $request + * + * @return bool + */ + private function accountMessage(Request $request): bool + { + // get parameters from request. + $accountId = $request->get('account_id'); + $message = $request->get('message'); + + return null !== $accountId && null !== $message; + } } diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index 1ee13d555b..04e5457db0 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -60,7 +60,7 @@ class IsDemoUser return response()->redirectTo($previous); } - return response()->redirectTo(route('index')); // @codeCoverageIgnore + return response()->redirectTo(route('index')); } return $next($request); diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index a58d45405c..3afa83902a 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -109,7 +109,7 @@ class Range // send error to view if could not set money format if (false === $moneyResult) { Log::error('Could not set locale. The following array doesnt work: ', $localeArray); - app('view')->share('invalidMonetaryLocale', true); // @codeCoverageIgnore + app('view')->share('invalidMonetaryLocale', true); } // save some formats: diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 82bf301873..e80efdc003 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -52,16 +52,15 @@ class SecureHeaders $trackingScriptSrc = $this->getTrackingScriptSource(); $csp = [ "default-src 'none'", - "object-src 'self'", - sprintf("script-src 'unsafe-inline' 'nonce-%1s' %2s", $nonce, $trackingScriptSrc), - "style-src 'self' 'unsafe-inline'", + "object-src 'none'", + "require-trusted-types-for 'script'", + //sprintf("script-src 'unsafe-inline' 'strict-dynamic' 'nonce-%1s' %2s", $nonce, $trackingScriptSrc), + sprintf("script-src 'unsafe-eval' 'strict-dynamic' 'self' 'unsafe-inline' 'nonce-%1s' %2s", $nonce, $trackingScriptSrc), + "style-src 'unsafe-inline' 'self'", "base-uri 'self'", "font-src 'self' data:", "connect-src 'self'", - sprintf( - "img-src 'self' data: https://a.tile.openstreetmap.org https://b.tile.openstreetmap.org https://c.tile.openstreetmap.org https://api.tiles.mapbox.com %s", - $trackingScriptSrc - ), + sprintf("img-src data: 'strict-dynamic' 'self' *.tile.openstreetmap.org %s", $trackingScriptSrc), "manifest-src 'self'", ]; @@ -80,7 +79,7 @@ class SecureHeaders "camera 'none'", "magnetometer 'none'", "gyroscope 'none'", - "speaker 'none'", + //"speaker 'none'", //"vibrate 'none'", "fullscreen 'self'", "payment 'none'", @@ -97,6 +96,9 @@ class SecureHeaders $response->header('X-XSS-Protection', '1; mode=block'); $response->header('X-Content-Type-Options', 'nosniff'); $response->header('Referrer-Policy', 'no-referrer'); + $response->header('X-Download-Options', 'noopen'); + $response->header('X-Permitted-Cross-Domain-Policies', 'none'); + $response->header('X-Robots-Tag', 'none'); $response->header('Feature-Policy', implode('; ', $featurePolicies)); return $response; diff --git a/app/Http/Requests/AccountFormRequest.php b/app/Http/Requests/AccountFormRequest.php index 939a21f41b..ff6bc71ed6 100644 --- a/app/Http/Requests/AccountFormRequest.php +++ b/app/Http/Requests/AccountFormRequest.php @@ -47,8 +47,7 @@ class AccountFormRequest extends FormRequest $data = [ 'name' => $this->string('name'), 'active' => $this->boolean('active'), - 'account_type' => $this->string('objectType'), - 'account_type_id' => 0, + 'account_type_name' => $this->string('objectType'), 'currency_id' => $this->integer('currency_id'), 'virtual_balance' => $this->string('virtual_balance'), 'iban' => $this->string('iban'), @@ -59,7 +58,7 @@ class AccountFormRequest extends FormRequest 'opening_balance_date' => $this->date('opening_balance_date'), 'cc_type' => $this->string('cc_type'), 'cc_monthly_payment_date' => $this->string('cc_monthly_payment_date'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'interest' => $this->string('interest'), 'interest_period' => $this->string('interest_period'), 'include_net_worth' => '1', @@ -72,9 +71,9 @@ class AccountFormRequest extends FormRequest // if the account type is "liabilities" there are actually four types of liability // that could have been selected. - if ('liabilities' === $data['account_type']) { - $data['account_type'] = null; - $data['account_type_id'] = $this->integer('liability_type_id'); + if ('liabilities' === $data['account_type_name']) { + $data['account_type_name'] = null; + $data['account_type_id'] = $this->integer('liability_type_id'); } return $data; diff --git a/app/Http/Requests/BillStoreRequest.php b/app/Http/Requests/BillStoreRequest.php index 10eb7c88a3..32ae63a4b2 100644 --- a/app/Http/Requests/BillStoreRequest.php +++ b/app/Http/Requests/BillStoreRequest.php @@ -49,7 +49,7 @@ class BillStoreRequest extends FormRequest 'date' => $this->date('date'), 'repeat_freq' => $this->string('repeat_freq'), 'skip' => $this->integer('skip'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), 'object_group_title' => $this->string('object_group'), ]; diff --git a/app/Http/Requests/BillUpdateRequest.php b/app/Http/Requests/BillUpdateRequest.php index 6d09666903..13431c7d5a 100644 --- a/app/Http/Requests/BillUpdateRequest.php +++ b/app/Http/Requests/BillUpdateRequest.php @@ -50,7 +50,7 @@ class BillUpdateRequest extends FormRequest 'date' => $this->date('date'), 'repeat_freq' => $this->string('repeat_freq'), 'skip' => $this->integer('skip'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), 'object_group_title' => $this->string('object_group'), ]; diff --git a/app/Http/Requests/CategoryFormRequest.php b/app/Http/Requests/CategoryFormRequest.php index 6b1a3bf7a5..0d1c15b5a7 100644 --- a/app/Http/Requests/CategoryFormRequest.php +++ b/app/Http/Requests/CategoryFormRequest.php @@ -43,7 +43,7 @@ class CategoryFormRequest extends FormRequest { return [ 'name' => $this->string('name'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), ]; } diff --git a/app/Http/Requests/ObjectGroupFormRequest.php b/app/Http/Requests/ObjectGroupFormRequest.php index 816b33a154..f17d09557a 100644 --- a/app/Http/Requests/ObjectGroupFormRequest.php +++ b/app/Http/Requests/ObjectGroupFormRequest.php @@ -53,9 +53,8 @@ class ObjectGroupFormRequest extends FormRequest */ public function rules(): array { - /** @var ObjectGroup $piggy */ + /** @var ObjectGroup $objectGroup */ $objectGroup = $this->route()->parameter('objectGroup'); - $titleRule = 'required|between:1,255|uniqueObjectGroup'; if (null !== $objectGroup) { diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php index a0014784a2..b9fee6510b 100644 --- a/app/Http/Requests/PiggyBankStoreRequest.php +++ b/app/Http/Requests/PiggyBankStoreRequest.php @@ -46,7 +46,7 @@ class PiggyBankStoreRequest extends FormRequest 'account_id' => $this->integer('account_id'), 'targetamount' => $this->string('targetamount'), 'targetdate' => $this->date('targetdate'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'object_group_title' => $this->string('object_group'), ]; } diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.php index 9719ba8a32..bb35919338 100644 --- a/app/Http/Requests/PiggyBankUpdateRequest.php +++ b/app/Http/Requests/PiggyBankUpdateRequest.php @@ -47,7 +47,7 @@ class PiggyBankUpdateRequest extends FormRequest 'account_id' => $this->integer('account_id'), 'targetamount' => $this->string('targetamount'), 'targetdate' => $this->date('targetdate'), - 'notes' => $this->nlString('notes'), + 'notes' => $this->stringWithNewlines('notes'), 'object_group_title' => $this->string('object_group'), ]; } diff --git a/app/Http/Requests/ReconciliationStoreRequest.php b/app/Http/Requests/ReconciliationStoreRequest.php index d76a6b85d9..ad5bdd5f65 100644 --- a/app/Http/Requests/ReconciliationStoreRequest.php +++ b/app/Http/Requests/ReconciliationStoreRequest.php @@ -45,7 +45,7 @@ class ReconciliationStoreRequest extends FormRequest { $transactions = $this->get('journals'); if (!is_array($transactions)) { - $transactions = []; // @codeCoverageIgnore + $transactions = []; } $data = [ 'start' => $this->date('start'), diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php index 75c5d16508..a7026eb65b 100644 --- a/app/Http/Requests/RecurrenceFormRequest.php +++ b/app/Http/Requests/RecurrenceFormRequest.php @@ -56,15 +56,15 @@ class RecurrenceFormRequest extends FormRequest $repetitionData = $this->parseRepetitionData(); $return = [ 'recurrence' => [ - 'type' => $this->string('transaction_type'), - 'title' => $this->string('title'), - 'description' => $this->string('recurring_description'), - 'first_date' => $this->date('first_date'), - 'repeat_until' => $this->date('repeat_until'), - 'repetitions' => $this->integer('repetitions'), - 'apply_rules' => $this->boolean('apply_rules'), - 'active' => $this->boolean('active'), - 'repetition_end' => $this->string('repetition_end'), + 'type' => $this->string('transaction_type'), + 'title' => $this->string('title'), + 'description' => $this->string('recurring_description'), + 'first_date' => $this->date('first_date'), + 'repeat_until' => $this->date('repeat_until'), + 'nr_of_repetitions' => $this->integer('repetitions'), + 'apply_rules' => $this->boolean('apply_rules'), + 'active' => $this->boolean('active'), + 'repetition_end' => $this->string('repetition_end'), ], 'transactions' => [ [ @@ -109,7 +109,7 @@ class RecurrenceFormRequest extends FormRequest // fill in source and destination account data switch ($this->string('transaction_type')) { default: - throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore + throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); case 'withdrawal': $return['transactions'][0]['source_id'] = $this->integer('source_id'); $return['transactions'][0]['destination_id'] = $this->integer('withdrawal_destination_id'); @@ -251,7 +251,7 @@ class RecurrenceFormRequest extends FormRequest break; default: - throw new FireflyException(sprintf('Cannot handle transaction type of type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore + throw new FireflyException(sprintf('Cannot handle transaction type of type "%s"', $this->string('transaction_type'))); } // update some rules in case the user is editing a post: @@ -308,7 +308,7 @@ class RecurrenceFormRequest extends FormRequest switch ($this->string('transaction_type')) { default: - throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore + throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); case 'withdrawal': $sourceId = (int)$data['source_id']; $destinationId = (int)$data['withdrawal_destination_id']; diff --git a/app/Http/Requests/ReportFormRequest.php b/app/Http/Requests/ReportFormRequest.php index b2e24bfc37..212fa59ad7 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -149,12 +149,12 @@ class ReportFormRequest extends FormRequest if (2 === count($parts)) { try { $date = new Carbon($parts[1]); - // @codeCoverageIgnoreStart + } catch (Exception $e) { $error = sprintf('"%s" is not a valid date range: %s', $range, $e->getMessage()); Log::error($error); - throw new FireflyException($error); - // @codeCoverageIgnoreEnd + throw new FireflyException($error, 0, $e); + } } @@ -177,12 +177,12 @@ class ReportFormRequest extends FormRequest if (2 === count($parts)) { try { $date = new Carbon($parts[0]); - // @codeCoverageIgnoreStart + } catch (Exception $e) { $error = sprintf('"%s" is not a valid date range: %s', $range, $e->getMessage()); Log::error($error); - throw new FireflyException($error); - // @codeCoverageIgnoreEnd + throw new FireflyException($error, 0, $e); + } } diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php index a207ef96f9..df558c61d2 100644 --- a/app/Http/Requests/RuleFormRequest.php +++ b/app/Http/Requests/RuleFormRequest.php @@ -48,7 +48,7 @@ class RuleFormRequest extends FormRequest 'rule_group_id' => $this->integer('rule_group_id'), 'active' => $this->boolean('active'), 'trigger' => $this->string('trigger'), - 'description' => $this->nlString('description'), + 'description' => $this->stringWithNewlines('description'), 'stop_processing' => $this->boolean('stop_processing'), 'strict' => $this->boolean('strict'), 'triggers' => $this->getRuleTriggerData(), diff --git a/app/Http/Requests/RuleGroupFormRequest.php b/app/Http/Requests/RuleGroupFormRequest.php index d7a4b0224b..8645e04651 100644 --- a/app/Http/Requests/RuleGroupFormRequest.php +++ b/app/Http/Requests/RuleGroupFormRequest.php @@ -49,7 +49,7 @@ class RuleGroupFormRequest extends FormRequest return [ 'title' => $this->string('title'), - 'description' => $this->nlString('description'), + 'description' => $this->stringWithNewlines('description'), 'active' => $active, ]; } diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 37e5471b77..31f3dd82b3 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -106,7 +106,7 @@ class CreateRecurringTransactions implements ShouldQueue Log::debug(sprintf('Left after filtering is %d', $filtered->count())); /** @var Recurrence $recurrence */ foreach ($filtered as $recurrence) { - if (!isset($result[$recurrence->user_id])) { + if (!array_key_exists($recurrence->user_id, $result)) { $result[$recurrence->user_id] = new Collection; } $this->repository->setUser($recurrence->user); @@ -239,9 +239,9 @@ class CreateRecurringTransactions implements ShouldQueue } /** - * Has the reuccrence started yet. + * Has the recurrence started yet? * - * @param $recurrence + * @param Recurrence $recurrence * * @return bool */ @@ -373,10 +373,10 @@ class CreateRecurringTransactions implements ShouldQueue $groupTitle = null; if ($recurrence->recurrenceTransactions->count() > 1) { /** @var RecurrenceTransaction $first */ - // @codeCoverageIgnoreStart + $first = $recurrence->recurrenceTransactions()->first(); $groupTitle = $first->description; - // @codeCoverageIgnoreEnd + } $array = [ diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index f58c737dcb..1ecce5dba6 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -39,14 +39,10 @@ class MailError extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; - /** @var string Destination */ - protected $destination; - /** @var array Exception information */ - protected $exception; - /** @var string IP address */ - protected $ipAddress; - /** @var array User information */ - protected $userData; + protected string $destination; + protected array $exception; + protected string $ipAddress; + protected array $userData; /** * MailError constructor. @@ -89,7 +85,7 @@ class MailError extends Job implements ShouldQueue } } ); - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::error('Exception when mailing: ' . $e->getMessage()); } } diff --git a/app/Jobs/SubmitTelemetryData.php b/app/Jobs/SubmitTelemetryData.php index 7054d68a17..a30cd6567b 100644 --- a/app/Jobs/SubmitTelemetryData.php +++ b/app/Jobs/SubmitTelemetryData.php @@ -46,10 +46,8 @@ class SubmitTelemetryData implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - /** @var Carbon The current date */ - private $date; - /** @var bool Force the transaction to be created no matter what. */ - private $force; + private Carbon $date; + private bool $force; /** * Create a new job instance. @@ -86,7 +84,7 @@ class SubmitTelemetryData implements ShouldQueue } catch (JsonException $e) { Log::error($e->getMessage()); Log::error('Could not parse JSON.'); - throw new FireflyException(sprintf('Could not parse telemetry JSON: %s', $e->getMessage())); + throw new FireflyException(sprintf('Could not parse telemetry JSON: %s', $e->getMessage()), 0, $e); } $client = new Client; @@ -105,7 +103,7 @@ class SubmitTelemetryData implements ShouldQueue Log::error($e->getMessage()); Log::error($e->getTraceAsString()); Log::error('Could not submit telemetry.'); - throw new FireflyException(sprintf('Could not submit telemetry: %s', $e->getMessage())); + throw new FireflyException(sprintf('Could not submit telemetry: %s', $e->getMessage()), 0, $e); } $body = (string)$result->getBody(); $statusCode = $result->getStatusCode(); diff --git a/app/Models/Account.php b/app/Models/Account.php index 5714a23d50..cb8494a026 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\Models; -use Carbon\Carbon; use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; @@ -33,7 +32,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Query\Builder; -use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -53,7 +51,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property int $order * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\AccountMeta[] $accountMeta * @property-read int|null $account_meta_count - * @property-read \FireflyIII\Models\AccountType $accountType + * @property \FireflyIII\Models\AccountType $accountType * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments * @property-read int|null $attachments_count * @property-read string $account_number @@ -248,7 +246,7 @@ class Account extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value * * @codeCoverageIgnore */ diff --git a/app/Models/AccountMeta.php b/app/Models/AccountMeta.php index c35eb5804c..dd5e0ee9a5 100644 --- a/app/Models/AccountMeta.php +++ b/app/Models/AccountMeta.php @@ -76,7 +76,7 @@ class AccountMeta extends Model } /** - * @param $value + * @param mixed $value * * @codeCoverageIgnore * @return mixed @@ -87,7 +87,7 @@ class AccountMeta extends Model } /** - * @param $value + * @param mixed $value * * @codeCoverageIgnore */ diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php index 263f050b5b..ba68970d71 100644 --- a/app/Models/Attachment.php +++ b/app/Models/Attachment.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\Models; -use Carbon\Carbon; use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Collection; @@ -37,24 +36,26 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * FireflyIII\Models\Attachment * - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property int $attachable_id - * @property string $attachable_type - * @property string $md5 - * @property string $filename - * @property string|null $title - * @property string|null $description - * @property string $mime - * @property int $size - * @property bool $uploaded - * @property-read Model|\Eloquent $attachable + * @property int $id + * @property \Illuminate\Support\Carbon|null $created_at + * @property \Illuminate\Support\Carbon|null $updated_at + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $user_id + * @property int $attachable_id + * @property string $attachable_type + * @property bool $file_exists + * @property string $md5 + * @property string $filename + * @property string|null $title + * @property string|null $description + * @property string $mime + * @property int $size + * @property bool $uploaded + * @property string $notes_text + * @property-read Model|\Eloquent $attachable * @property Collection|\FireflyIII\Models\Note[] $notes - * @property-read int|null $notes_count - * @property-read User $user + * @property-read int|null $notes_count + * @property-read User $user * @method static \Illuminate\Database\Eloquent\Builder|Attachment newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Attachment newQuery() * @method static Builder|Attachment onlyTrashed() @@ -101,13 +102,13 @@ class Attachment extends Model * * @param string $value * - * @throws NotFoundHttpException * @return Attachment + * @throws NotFoundHttpException */ public static function routeBinder(string $value): Attachment { if (auth()->check()) { - $attachmentId = (int) $value; + $attachmentId = (int)$value; /** @var User $user */ $user = auth()->user(); /** @var Attachment $attachment */ @@ -139,7 +140,7 @@ class Attachment extends Model */ public function fileName(): string { - return sprintf('at-%s.data', (string) $this->id); + return sprintf('at-%s.data', (string)$this->id); } /** diff --git a/app/Models/Bill.php b/app/Models/Bill.php index 46a48a8b73..e1e924cd83 100644 --- a/app/Models/Bill.php +++ b/app/Models/Bill.php @@ -176,7 +176,7 @@ class Bill extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setAmountMaxAttribute($value): void { @@ -184,7 +184,7 @@ class Bill extends Model } /** - * @param $value + * @param mixed $value * * @codeCoverageIgnore */ diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php index 2c78ab3d9b..be3c853dbd 100644 --- a/app/Models/BudgetLimit.php +++ b/app/Models/BudgetLimit.php @@ -40,6 +40,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property \Illuminate\Support\Carbon $start_date * @property \Illuminate\Support\Carbon|null $end_date * @property string $amount + * @property string $spent * @property string|null $period * @property int $generated * @property-read \FireflyIII\Models\Budget $budget @@ -83,7 +84,7 @@ class BudgetLimit extends Model * * @param string $value * - * @return mixed + * @return BudgetLimit * @throws NotFoundHttpException */ public static function routeBinder(string $value): BudgetLimit diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php index c75609a7cd..4913d85c2d 100644 --- a/app/Models/Configuration.php +++ b/app/Models/Configuration.php @@ -70,9 +70,10 @@ class Configuration extends Model protected $table = 'configuration'; /** + * TODO can be replaced by native laravel code * @codeCoverageIgnore * - * @param $value + * @param mixed $value * * @return mixed */ @@ -84,7 +85,7 @@ class Configuration extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setDataAttribute($value): void { diff --git a/app/Models/LinkType.php b/app/Models/LinkType.php index ff50e87374..be9510f90c 100644 --- a/app/Models/LinkType.php +++ b/app/Models/LinkType.php @@ -81,7 +81,7 @@ class LinkType extends Model /** * Route binder. Converts the key in the URL to the specified object (or throw 404). * - * @param $value + * @param string $value * * @throws NotFoundHttpException * @return LinkType diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index 419be6f8b2..2525948f81 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -181,7 +181,7 @@ class PiggyBank extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setTargetamountAttribute($value): void { diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index 666049215d..1990360bb0 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -37,7 +37,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property int|null $transaction_journal_id * @property \Illuminate\Support\Carbon $date * @property string $amount - * @property-read \FireflyIII\Models\PiggyBank $piggyBank + * @property \FireflyIII\Models\PiggyBank $piggyBank * @property-read \FireflyIII\Models\TransactionJournal|null $transactionJournal * @method static Builder|PiggyBankEvent newModelQuery() * @method static Builder|PiggyBankEvent newQuery() @@ -81,7 +81,7 @@ class PiggyBankEvent extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setAmountAttribute($value): void { diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php index 5c249f2f60..f9214107ac 100644 --- a/app/Models/PiggyBankRepetition.php +++ b/app/Models/PiggyBankRepetition.php @@ -120,7 +120,7 @@ class PiggyBankRepetition extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setCurrentamountAttribute($value): void { diff --git a/app/Models/Preference.php b/app/Models/Preference.php index 4dc348ea22..f473853d77 100644 --- a/app/Models/Preference.php +++ b/app/Models/Preference.php @@ -38,7 +38,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property \Illuminate\Support\Carbon|null $updated_at * @property int $user_id * @property string $name - * @property array|null $data + * @property int|string|array|null $data * @property-read User $user * @method static Builder|Preference newModelQuery() * @method static Builder|Preference newQuery() diff --git a/app/Models/RecurrenceMeta.php b/app/Models/RecurrenceMeta.php index 43af735266..60a2cf843b 100644 --- a/app/Models/RecurrenceMeta.php +++ b/app/Models/RecurrenceMeta.php @@ -38,7 +38,7 @@ use Illuminate\Support\Carbon; * @property Carbon|null $deleted_at * @property int $recurrence_id * @property string $name - * @property string $value + * @property mixed $value * @property-read \FireflyIII\Models\Recurrence $recurrence * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta newQuery() diff --git a/app/Models/RecurrenceTransactionMeta.php b/app/Models/RecurrenceTransactionMeta.php index f2030342c6..f71dee3bf1 100644 --- a/app/Models/RecurrenceTransactionMeta.php +++ b/app/Models/RecurrenceTransactionMeta.php @@ -38,7 +38,7 @@ use Illuminate\Support\Carbon; * @property Carbon|null $deleted_at * @property int $rt_id * @property string $name - * @property string $value + * @property mixed $value * @property-read \FireflyIII\Models\RecurrenceTransaction $recurrenceTransaction * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta newQuery() diff --git a/app/Models/Rule.php b/app/Models/Rule.php index 5a15335d6f..9d9b8e413f 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -48,10 +48,11 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property bool $active * @property bool $stop_processing * @property bool $strict + * @property-read string $action_value * @property-read Collection|RuleAction[] $ruleActions * @property-read int|null $rule_actions_count * @property-read RuleGroup $ruleGroup - * @property-read Collection|RuleTrigger[] $ruleTriggers + * @property Collection|RuleTrigger[] $ruleTriggers * @property-read int|null $rule_triggers_count * @property-read User $user * @method static \Illuminate\Database\Eloquent\Builder|Rule newModelQuery() @@ -148,7 +149,7 @@ class Rule extends Model } /** - * @param $value + * @param mixed $value * * @codeCoverageIgnore */ diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index e3ceb4e359..418a673d00 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -44,6 +44,10 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property int $transaction_journal_id * @property string|null $description * @property int|null $transaction_currency_id + * @property string $modified + * @property string $modified_foreign + * @property string $date + * @property string $max_date * @property string $amount * @property string|null $foreign_amount * @property int|null $foreign_currency_id @@ -226,7 +230,7 @@ class Transaction extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setAmountAttribute($value): void { diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index 922caf3382..0b63f2e1df 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -35,54 +35,55 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; + /** * FireflyIII\Models\TransactionJournal * - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property int $transaction_type_id - * @property int|null $transaction_group_id - * @property int|null $bill_id - * @property int|null $transaction_currency_id - * @property string $description - * @property \Illuminate\Support\Carbon $date - * @property \Illuminate\Support\Carbon|null $interest_date - * @property \Illuminate\Support\Carbon|null $book_date - * @property \Illuminate\Support\Carbon|null $process_date - * @property int $order - * @property int $tag_count - * @property bool $encrypted - * @property bool $completed - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments - * @property-read int|null $attachments_count - * @property-read \FireflyIII\Models\Bill|null $bill - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Budget[] $budgets - * @property-read int|null $budgets_count - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Category[] $categories - * @property-read int|null $categories_count + * @property int $id + * @property \Carbon\Carbon|null $created_at + * @property \Carbon\Carbon|null $updated_at + * @property \Carbon\Carbon|null $deleted_at + * @property int $user_id + * @property int $transaction_type_id + * @property int|null $transaction_group_id + * @property int|null $bill_id + * @property int|null $transaction_currency_id + * @property string $description + * @property \Carbon\Carbon $date + * @property \Carbon\Carbon|null $interest_date + * @property \Carbon\Carbon|null $book_date + * @property \Carbon\Carbon|null $process_date + * @property int $order + * @property int $tag_count + * @property string $transaction_type_type + * @property bool $encrypted + * @property bool $completed + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments + * @property-read int|null $attachments_count + * @property-read \FireflyIII\Models\Bill|null $bill + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Budget[] $budgets + * @property-read int|null $budgets_count + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Category[] $categories + * @property-read int|null $categories_count * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournalLink[] $destJournalLinks - * @property-read int|null $dest_journal_links_count - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @property-read int|null $notes_count - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBankEvent[] $piggyBankEvents - * @property-read int|null $piggy_bank_events_count + * @property-read int|null $dest_journal_links_count + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes + * @property-read int|null $notes_count + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBankEvent[] $piggyBankEvents + * @property-read int|null $piggy_bank_events_count * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournalLink[] $sourceJournalLinks - * @property-read int|null $source_journal_links_count - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Tag[] $tags - * @property-read int|null $tags_count - * @property-read \FireflyIII\Models\TransactionCurrency|null $transactionCurrency - * @property-read \FireflyIII\Models\TransactionGroup|null $transactionGroup + * @property-read int|null $source_journal_links_count + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Tag[] $tags + * @property-read int|null $tags_count + * @property-read \FireflyIII\Models\TransactionCurrency|null $transactionCurrency + * @property-read \FireflyIII\Models\TransactionGroup|null $transactionGroup * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournalMeta[] $transactionJournalMeta - * @property-read int|null $transaction_journal_meta_count - * @property-read \FireflyIII\Models\TransactionType $transactionType - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions - * @property-read int|null $transactions_count - * @property-read User $user + * @property-read int|null $transaction_journal_meta_count + * @property-read \FireflyIII\Models\TransactionType $transactionType + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions + * @property-read int|null $transactions_count + * @property-read User $user * @method static EloquentBuilder|TransactionJournal after(\Carbon\Carbon $date) * @method static EloquentBuilder|TransactionJournal before(\Carbon\Carbon $date) * @method static EloquentBuilder|TransactionJournal newModelQuery() @@ -111,8 +112,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @method static \Illuminate\Database\Query\Builder|TransactionJournal withTrashed() * @method static \Illuminate\Database\Query\Builder|TransactionJournal withoutTrashed() * @mixin Eloquent - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Location[] $locations - * @property-read int|null $locations_count + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Location[] $locations + * @property-read int|null $locations_count */ class TransactionJournal extends Model { @@ -175,14 +176,14 @@ class TransactionJournal extends Model * * @param string $value * - * @throws NotFoundHttpException - * @throws FireflyException * @return TransactionJournal + * @throws FireflyException + * @throws NotFoundHttpException */ public static function routeBinder(string $value): TransactionJournal { if (auth()->check()) { - $journalId = (int) $value; + $journalId = (int)$value; /** @var User $user */ $user = auth()->user(); /** @var TransactionJournal $journal */ @@ -317,7 +318,7 @@ class TransactionJournal extends Model if (!self::isJoined($query, 'transaction_types')) { $query->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id'); } - if (!empty($types)) { + if (0 !== count($types)) { $query->whereIn('transaction_types.type', $types); } } diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index e50bd2e2c8..c6eacc0862 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -46,6 +46,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read Collection|\FireflyIII\Models\Note[] $notes * @property-read int|null $notes_count * @property-read \FireflyIII\Models\TransactionJournal $source + * @property-read string $inward + * @property-read string $outward * @method static Builder|TransactionJournalLink newModelQuery() * @method static Builder|TransactionJournalLink newQuery() * @method static Builder|TransactionJournalLink query() @@ -79,7 +81,7 @@ class TransactionJournalLink extends Model * @param string $value * * @throws NotFoundHttpException - * @return mixed + * @return TransactionJournalLink * */ public static function routeBinder(string $value): TransactionJournalLink diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 017f45aa2c..88e1da9134 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -79,7 +79,7 @@ class TransactionJournalMeta extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value * * @return mixed */ @@ -91,7 +91,7 @@ class TransactionJournalMeta extends Model /** * @codeCoverageIgnore * - * @param $value + * @param mixed $value */ public function setDataAttribute($value): void { diff --git a/app/Models/TransactionType.php b/app/Models/TransactionType.php index 7f3f9f5c23..d48f725be6 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -79,7 +79,7 @@ class TransactionType extends Model * @param string $type * * @throws NotFoundHttpException - * @return Model|null|static + * @return TransactionType */ public static function routeBinder(string $type): TransactionType { diff --git a/app/Providers/AccountServiceProvider.php b/app/Providers/AccountServiceProvider.php index c87627d280..c6fae4af38 100644 --- a/app/Providers/AccountServiceProvider.php +++ b/app/Providers/AccountServiceProvider.php @@ -64,7 +64,7 @@ class AccountServiceProvider extends ServiceProvider /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -78,7 +78,7 @@ class AccountServiceProvider extends ServiceProvider /** @var OperationsRepository $repository */ $repository = app(OperationsRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -98,7 +98,7 @@ class AccountServiceProvider extends ServiceProvider /** @var AccountTaskerInterface $tasker */ $tasker = app(AccountTasker::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $tasker->setUser(auth()->user()); } diff --git a/app/Providers/AdminServiceProvider.php b/app/Providers/AdminServiceProvider.php index 1eb49323db..41b2c87f8e 100644 --- a/app/Providers/AdminServiceProvider.php +++ b/app/Providers/AdminServiceProvider.php @@ -58,7 +58,7 @@ class AdminServiceProvider extends ServiceProvider function (Application $app) { /** @var LinkTypeRepository $repository */ $repository = app(LinkTypeRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/AttachmentServiceProvider.php b/app/Providers/AttachmentServiceProvider.php index 94e3052727..adf299f740 100644 --- a/app/Providers/AttachmentServiceProvider.php +++ b/app/Providers/AttachmentServiceProvider.php @@ -50,7 +50,7 @@ class AttachmentServiceProvider extends ServiceProvider function (Application $app) { /** @var AttachmentRepositoryInterface $repository */ $repository = app(AttachmentRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 1876d368fc..fcd48ce4c4 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -53,7 +53,7 @@ class AuthServiceProvider extends ServiceProvider { Auth::provider( 'remote_user_provider', function ($app, array $config) { - return new RemoteUserProvider($app, $config); + return new RemoteUserProvider; } ); diff --git a/app/Providers/BillServiceProvider.php b/app/Providers/BillServiceProvider.php index 7190f26798..ecaefa8edc 100644 --- a/app/Providers/BillServiceProvider.php +++ b/app/Providers/BillServiceProvider.php @@ -51,7 +51,7 @@ class BillServiceProvider extends ServiceProvider /** @var BillRepositoryInterface $repository */ $repository = app(BillRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/BudgetServiceProvider.php b/app/Providers/BudgetServiceProvider.php index ebcee13138..d36d5b9bb4 100644 --- a/app/Providers/BudgetServiceProvider.php +++ b/app/Providers/BudgetServiceProvider.php @@ -58,7 +58,7 @@ class BudgetServiceProvider extends ServiceProvider static function (Application $app) { /** @var BudgetRepositoryInterface $repository */ $repository = app(BudgetRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -72,7 +72,7 @@ class BudgetServiceProvider extends ServiceProvider static function (Application $app) { /** @var AvailableBudgetRepositoryInterface $repository */ $repository = app(AvailableBudgetRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -86,7 +86,7 @@ class BudgetServiceProvider extends ServiceProvider static function (Application $app) { /** @var BudgetLimitRepositoryInterface $repository */ $repository = app(BudgetLimitRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -100,7 +100,7 @@ class BudgetServiceProvider extends ServiceProvider static function (Application $app) { /** @var NoBudgetRepositoryInterface $repository */ $repository = app(NoBudgetRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -114,7 +114,7 @@ class BudgetServiceProvider extends ServiceProvider static function (Application $app) { /** @var OperationsRepositoryInterface $repository */ $repository = app(OperationsRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/CategoryServiceProvider.php b/app/Providers/CategoryServiceProvider.php index af3679b08f..0df0767cd1 100644 --- a/app/Providers/CategoryServiceProvider.php +++ b/app/Providers/CategoryServiceProvider.php @@ -54,7 +54,7 @@ class CategoryServiceProvider extends ServiceProvider static function (Application $app) { /** @var CategoryRepository $repository */ $repository = app(CategoryRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -67,7 +67,7 @@ class CategoryServiceProvider extends ServiceProvider static function (Application $app) { /** @var OperationsRepository $repository */ $repository = app(OperationsRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -80,7 +80,7 @@ class CategoryServiceProvider extends ServiceProvider static function (Application $app) { /** @var NoCategoryRepository $repository */ $repository = app(NoCategoryRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/CurrencyServiceProvider.php b/app/Providers/CurrencyServiceProvider.php index 0e4eafb253..ae527f4026 100644 --- a/app/Providers/CurrencyServiceProvider.php +++ b/app/Providers/CurrencyServiceProvider.php @@ -50,7 +50,7 @@ class CurrencyServiceProvider extends ServiceProvider function (Application $app) { /** @var CurrencyRepository $repository */ $repository = app(CurrencyRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index a31b381d4e..34bdfe4209 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -169,8 +169,7 @@ class EventServiceProvider extends ServiceProvider try { Log::debug('Trying to send message...'); Mail::to($email)->send(new OAuthTokenCreatedMail($email, $ipAddress, $oauthClient)); - // @codeCoverageIgnoreStart - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index cfc57fe7e9..ae216cdb74 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -186,7 +186,7 @@ class FireflyServiceProvider extends ServiceProvider static function (Application $app) { /** @var ObjectGroupRepository $repository */ $repository = app(ObjectGroupRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -199,7 +199,7 @@ class FireflyServiceProvider extends ServiceProvider static function (Application $app) { /** @var WebhookRepository $repository */ $repository = app(WebhookRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -212,7 +212,7 @@ class FireflyServiceProvider extends ServiceProvider static function (Application $app) { /** @var SearchRuleEngine $engine */ $engine = app(SearchRuleEngine::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $engine->setUser(auth()->user()); } diff --git a/app/Providers/JournalServiceProvider.php b/app/Providers/JournalServiceProvider.php index cf8eb35024..b2c6e2672f 100644 --- a/app/Providers/JournalServiceProvider.php +++ b/app/Providers/JournalServiceProvider.php @@ -68,7 +68,7 @@ class JournalServiceProvider extends ServiceProvider static function (Application $app) { /** @var JournalRepositoryInterface $repository */ $repository = app(JournalRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -82,7 +82,7 @@ class JournalServiceProvider extends ServiceProvider static function (Application $app) { /** @var JournalAPIRepositoryInterface $repository */ $repository = app(JournalAPIRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -96,7 +96,7 @@ class JournalServiceProvider extends ServiceProvider static function (Application $app) { /** @var JournalCLIRepositoryInterface $repository */ $repository = app(JournalCLIRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -115,7 +115,7 @@ class JournalServiceProvider extends ServiceProvider static function (Application $app) { /** @var TransactionGroupRepositoryInterface $repository */ $repository = app(TransactionGroupRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -134,7 +134,7 @@ class JournalServiceProvider extends ServiceProvider static function (Application $app) { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollector::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $collector->setUser(auth()->user()); } diff --git a/app/Providers/PiggyBankServiceProvider.php b/app/Providers/PiggyBankServiceProvider.php index d7e511f78c..59501483f7 100644 --- a/app/Providers/PiggyBankServiceProvider.php +++ b/app/Providers/PiggyBankServiceProvider.php @@ -50,7 +50,7 @@ class PiggyBankServiceProvider extends ServiceProvider function (Application $app) { /** @var PiggyBankRepository $repository */ $repository = app(PiggyBankRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/RecurringServiceProvider.php b/app/Providers/RecurringServiceProvider.php index a306b58934..ca247c9cae 100644 --- a/app/Providers/RecurringServiceProvider.php +++ b/app/Providers/RecurringServiceProvider.php @@ -51,7 +51,7 @@ class RecurringServiceProvider extends ServiceProvider /** @var RecurringRepositoryInterface $repository */ $repository = app(RecurringRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/RuleGroupServiceProvider.php b/app/Providers/RuleGroupServiceProvider.php index 19b9eceb78..8c4f96374b 100644 --- a/app/Providers/RuleGroupServiceProvider.php +++ b/app/Providers/RuleGroupServiceProvider.php @@ -50,7 +50,7 @@ class RuleGroupServiceProvider extends ServiceProvider function (Application $app) { /** @var RuleGroupRepository $repository */ $repository = app(RuleGroupRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/RuleServiceProvider.php b/app/Providers/RuleServiceProvider.php index 5215fd7a4d..41bc572893 100644 --- a/app/Providers/RuleServiceProvider.php +++ b/app/Providers/RuleServiceProvider.php @@ -50,7 +50,7 @@ class RuleServiceProvider extends ServiceProvider function (Application $app) { /** @var RuleRepository $repository */ $repository = app(RuleRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Providers/SearchServiceProvider.php b/app/Providers/SearchServiceProvider.php index 1aa5941516..5e49a10c5a 100644 --- a/app/Providers/SearchServiceProvider.php +++ b/app/Providers/SearchServiceProvider.php @@ -50,7 +50,7 @@ class SearchServiceProvider extends ServiceProvider function (Application $app) { /** @var OperatorQuerySearch $search */ $search = app(OperatorQuerySearch::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $search->setUser(auth()->user()); } diff --git a/app/Providers/TagServiceProvider.php b/app/Providers/TagServiceProvider.php index 64b9b3cf29..4bcf89b463 100644 --- a/app/Providers/TagServiceProvider.php +++ b/app/Providers/TagServiceProvider.php @@ -53,7 +53,7 @@ class TagServiceProvider extends ServiceProvider /** @var TagRepository $repository */ $repository = app(TagRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } @@ -67,7 +67,7 @@ class TagServiceProvider extends ServiceProvider /** @var OperationsRepository $repository */ $repository = app(OperationsRepository::class); - if ($app->auth->check()) { + if ($app->auth->check()) { // @phpstan-ignore-line $repository->setUser(auth()->user()); } diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 71dbda25c4..06ed6e8dd6 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -125,7 +125,7 @@ class AccountRepository implements AccountRepositoryInterface { $query = $this->user->accounts()->where('iban', '!=', '')->whereNotNull('iban'); - if (!empty($types)) { + if (0!==count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); $query->whereIn('account_types.type', $types); } @@ -153,7 +153,7 @@ class AccountRepository implements AccountRepositoryInterface { $query = $this->user->accounts(); - if (!empty($types)) { + if (0 !== count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); $query->whereIn('account_types.type', $types); } @@ -210,7 +210,7 @@ class AccountRepository implements AccountRepositoryInterface */ public function getAccountTypeByType(string $type): ?AccountType { - return AccountType::whereType($type)->first(); + return AccountType::whereType(ucfirst($type))->first(); } /** @@ -220,10 +220,9 @@ class AccountRepository implements AccountRepositoryInterface */ public function getAccountsById(array $accountIds): Collection { - /** @var Collection $result */ $query = $this->user->accounts(); - if (!empty($accountIds)) { + if (0 !== count($accountIds)) { $query->whereIn('accounts.id', $accountIds); } $query->orderBy('accounts.order', 'ASC'); @@ -240,9 +239,8 @@ class AccountRepository implements AccountRepositoryInterface */ public function getAccountsByType(array $types): Collection { - /** @var Collection $result */ $query = $this->user->accounts(); - if (!empty($types)) { + if (0 !== count($types)) { $query->accountTypeIn($types); } $res = array_intersect([AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], $types); @@ -263,13 +261,12 @@ class AccountRepository implements AccountRepositoryInterface */ public function getActiveAccountsByType(array $types): Collection { - /** @var Collection $result */ $query = $this->user->accounts()->with( ['accountmeta' => function (HasMany $query) { $query->where('name', 'account_role'); }, 'attachments'] ); - if (!empty($types)) { + if (0 !== count($types)) { $query->accountTypeIn($types); } $query->where('active', 1); @@ -324,13 +321,12 @@ class AccountRepository implements AccountRepositoryInterface */ public function getInactiveAccountsByType(array $types): Collection { - /** @var Collection $result */ $query = $this->user->accounts()->with( ['accountmeta' => function (HasMany $query) { $query->where('name', 'account_role'); }] ); - if (!empty($types)) { + if (0 !== count($types)) { $query->accountTypeIn($types); } $query->where('active', 0); @@ -504,12 +500,12 @@ class AccountRepository implements AccountRepositoryInterface } $data = [ - 'account_type_id' => null, - 'account_type' => AccountType::RECONCILIATION, - 'active' => true, - 'name' => $name, - 'currency_id' => $currency->id, - 'currency_code' => $currency->code, + 'account_type_id' => null, + 'account_type_name' => AccountType::RECONCILIATION, + 'active' => true, + 'name' => $name, + 'currency_id' => $currency->id, + 'currency_code' => $currency->code, ]; /** @var AccountFactory $factory */ @@ -668,7 +664,7 @@ class AccountRepository implements AccountRepositoryInterface } } - if (!empty($types)) { + if (0 !== count($types)) { $dbQuery->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); $dbQuery->whereIn('account_types.type', $types); } @@ -706,7 +702,7 @@ class AccountRepository implements AccountRepositoryInterface ); } } - if (!empty($types)) { + if (0 !== count($types)) { $dbQuery->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); $dbQuery->whereIn('account_types.type', $types); } diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php index 90e606a992..18f45aa92f 100644 --- a/app/Repositories/Account/AccountTasker.php +++ b/app/Repositories/Account/AccountTasker.php @@ -268,7 +268,7 @@ class AccountTasker implements AccountTaskerInterface $sourceId = (int)$journal['source_account_id']; $currencyId = (int)$journal['currency_id']; $key = sprintf('%s-%s', $sourceId, $currencyId); - if (!isset($report['accounts'][$key])) { + if (!array_key_exists($key, $report['accounts'])) { $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepos->findNull($currencyId); $report['accounts'][$key] = [ 'id' => $sourceId, diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php index 1bea61be7f..c5b943b289 100644 --- a/app/Repositories/Account/OperationsRepository.php +++ b/app/Repositories/Account/OperationsRepository.php @@ -203,7 +203,7 @@ class OperationsRepository implements OperationsRepositoryInterface ]; $array[$currencyId]['transaction_journals'][$journalId] = [ - 'amount' => app('steam')->$direction($journal['amount']), + 'amount' => app('steam')->$direction((string)$journal['amount']), 'date' => $journal['date'], 'transaction_journal_id' => $journalId, 'budget_name' => $journal['budget_name'], @@ -364,7 +364,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'currency_code' => $journal['currency_code'], 'currency_decimal_places' => $journal['currency_decimal_places'], ]; - $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method($journal['amount'])); + $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string)$journal['amount'])); // also do foreign amount: if (0 !== (int)$journal['foreign_currency_id']) { @@ -379,7 +379,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'currency_code' => $journal['foreign_currency_code'], 'currency_decimal_places' => $journal['foreign_currency_decimal_places'], ]; - $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method($journal['foreign_amount'])); + $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string)$journal['foreign_amount'])); } } diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index 6a51a73345..b7923a4370 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -59,8 +59,8 @@ class AttachmentRepository implements AttachmentRepositoryInterface $path = $helper->getAttachmentLocation($attachment); try { Storage::disk('upload')->delete($path); - } catch (Exception $e) { - Log::error(sprintf('Could not delete file for attachment %d: %s', $attachment->id, $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } $attachment->delete(); @@ -209,8 +209,8 @@ class AttachmentRepository implements AttachmentRepositoryInterface if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index fd6b073fb5..1a9897d53a 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -29,6 +29,7 @@ use FireflyIII\Factory\BillFactory; use FireflyIII\Models\Attachment; use FireflyIII\Models\Bill; use FireflyIII\Models\Note; +use FireflyIII\Models\Rule; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; @@ -200,7 +201,6 @@ class BillRepository implements BillRepositoryInterface */ public function getBills(): Collection { - /** @var Collection $set */ return $this->user->bills() ->orderBy('order', 'ASC') ->orderBy('active', 'DESC') @@ -549,6 +549,7 @@ class BillRepository implements BillRepositoryInterface ->where('rule_actions.action_type', 'link_to_bill') ->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']); $array = []; + /** @var Rule $rule */ foreach ($rules as $rule) { $array[$rule->action_value] = $array[$rule->action_value] ?? []; $array[$rule->action_value][] = ['id' => $rule->id, 'title' => $rule->title, 'active' => $rule->active]; @@ -648,7 +649,7 @@ class BillRepository implements BillRepositoryInterface $cache->addProperty('nextDateMatch'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // find the most recent date for this bill NOT in the future. Cache this date: $start = clone $bill->date; @@ -682,7 +683,7 @@ class BillRepository implements BillRepositoryInterface $cache->addProperty('nextExpectedMatch'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // find the most recent date for this bill NOT in the future. Cache this date: $start = clone $bill->date; diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index 64854c7c29..f5f40ca3c9 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -55,8 +55,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface { try { $availableBudget->delete(); - } catch (Exception $e) { - Log::error(sprintf('Could not delete available budget: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -262,7 +262,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface */ public function update(AvailableBudget $availableBudget, array $data): AvailableBudget { - if (isset($data['amount'])) { + if (array_key_exists('amount', $data)) { $availableBudget->amount = $data['amount']; } $availableBudget->save(); diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index e8553b0180..1474ec94f5 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -124,8 +124,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface { try { $budgetLimit->delete(); - } catch (Exception $e) { - Log::info(sprintf('Could not delete budget limit: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -320,25 +320,25 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface // find the budget: $budget = $this->user->budgets()->find((int)$data['budget_id']); if (null === $budget) { - throw new FireflyException('200004: Budget does not exist.'); // @codeCoverageIgnore + throw new FireflyException('200004: Budget does not exist.'); } // find limit with same date range and currency. $limit = $budget->budgetlimits() - ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d 00:00:00')) - ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d 23:59:59')) + ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d')) + ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d')) ->where('budget_limits.transaction_currency_id', $currency->id) - ->get(['budget_limits.*'])->first(); + ->first(['budget_limits.*']); if (null !== $limit) { - throw new FireflyException('200027: Budget limit already exists.'); // @codeCoverageIgnore + throw new FireflyException('200027: Budget limit already exists.'); } Log::debug('No existing budget limit, create a new one'); // or create one and return it. $limit = new BudgetLimit; $limit->budget()->associate($budget); - $limit->start_date = $data['start_date']->format('Y-m-d 00:00:00'); - $limit->end_date = $data['end_date']->format('Y-m-d 23:59:59'); + $limit->start_date = $data['start_date']->format('Y-m-d'); + $limit->end_date = $data['end_date']->format('Y-m-d'); $limit->amount = $data['amount']; $limit->transaction_currency_id = $currency->id; $limit->save(); @@ -397,7 +397,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface $limits = $budget->budgetlimits() ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00')) ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00')) - ->get(['budget_limits.*'])->count(); + ->count(['budget_limits.*']); Log::debug(sprintf('Found %d budget limits.', $limits)); // there might be a budget limit for these dates: @@ -423,8 +423,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface Log::debug(sprintf('%s is zero, delete budget limit #%d', $amount, $limit->id)); try { $limit->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete limit: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } return null; } diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 0a92850bfd..833b4cb041 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -58,8 +58,8 @@ class BudgetRepository implements BudgetRepositoryInterface // delete limits with amount 0: try { BudgetLimit::where('amount', 0)->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete budget limit: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } $budgets = $this->getActiveBudgets(); /** @@ -326,7 +326,7 @@ class BudgetRepository implements BudgetRepositoryInterface } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException('400002: Could not store budget.'); + throw new FireflyException('400002: Could not store budget.', 0, $e); } if (!array_key_exists('auto_budget_type', $data)) { return $newBudget; diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php index cf960845a5..56eeb24d85 100644 --- a/app/Repositories/Budget/NoBudgetRepository.php +++ b/app/Repositories/Budget/NoBudgetRepository.php @@ -75,7 +75,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface ]; $date = $journal['date']->format($carbonFormat); - if (!isset($data[$currencyId]['entries'][$date])) { + if (!array_key_exists($date, $data[$currencyId]['entries'])) { $data[$currencyId]['entries'][$date] = '0'; } $data[$currencyId]['entries'][$date] = bcadd($data[$currencyId]['entries'][$date], $journal['amount']); @@ -118,7 +118,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface /** @var array $journal */ foreach ($journals as $journal) { $code = $journal['currency_code']; - if (!isset($currencies[$code])) { + if (!array_key_exists($code, $currencies)) { $currencies[$code] = [ 'id' => $journal['currency_id'], 'name' => $journal['currency_name'], @@ -126,7 +126,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface 'decimal_places' => $journal['currency_decimal_places'], ]; } - $total[$code] = isset($total[$code]) ? bcadd($total[$code], $journal['amount']) : $journal['amount']; + $total[$code] = array_key_exists($code, $total) ? bcadd($total[$code], $journal['amount']) : $journal['amount']; } foreach ($total as $code => $spent) { /** @var TransactionCurrency $currency */ diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index d054290e14..35995e1460 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -237,7 +237,7 @@ class OperationsRepository implements OperationsRepositoryInterface /** @var array $transaction */ foreach ($group['transactions'] as $transaction) { $code = $transaction['currency_code']; - if (!isset($currencies[$code])) { + if (!array_key_exists($code, $currencies)) { $currencies[$code] = [ 'id' => $transaction['currency_id'], 'decimal_places' => $transaction['currency_decimal_places'], @@ -246,7 +246,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'symbol' => $transaction['currency_symbol'], ]; } - $total[$code] = isset($total[$code]) ? bcadd($total[$code], $transaction['amount']) : $transaction['amount']; + $total[$code] = array_key_exists($code, $total) ? bcadd($total[$code], $transaction['amount']) : $transaction['amount']; } } /** diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index 1f2601c059..d96e2aad6c 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -432,25 +432,6 @@ class CurrencyRepository implements CurrencyRepositoryInterface return null; } - /** - * Return a list of exchange rates with this currency. - * - * @param TransactionCurrency $currency - * - * @return Collection - */ - public function getExchangeRates(TransactionCurrency $currency): Collection - { - /** @var CurrencyExchangeRate $rate */ - return $this->user->currencyExchangeRates() - ->where( - function (Builder $query) use ($currency) { - $query->where('from_currency_id', $currency->id); - $query->orWhere('to_currency_id', $currency->id); - } - )->get(); - } - /** * @inheritDoc */ diff --git a/app/Repositories/Currency/CurrencyRepositoryInterface.php b/app/Repositories/Currency/CurrencyRepositoryInterface.php index b6f3daafef..fc9ddbfd67 100644 --- a/app/Repositories/Currency/CurrencyRepositoryInterface.php +++ b/app/Repositories/Currency/CurrencyRepositoryInterface.php @@ -207,15 +207,6 @@ interface CurrencyRepositoryInterface */ public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate; - /** - * Return a list of exchange rates with this currency. - * - * @param TransactionCurrency $currency - * - * @return Collection - */ - public function getExchangeRates(TransactionCurrency $currency): Collection; - /** * @param TransactionCurrency $currency * diff --git a/app/Repositories/Journal/JournalAPIRepository.php b/app/Repositories/Journal/JournalAPIRepository.php index 7873ba6565..f50d7821fe 100644 --- a/app/Repositories/Journal/JournalAPIRepository.php +++ b/app/Repositories/Journal/JournalAPIRepository.php @@ -97,7 +97,7 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface */ public function getPiggyBankEvents(TransactionJournal $journal): Collection { - /** @var Collection $set */ + /** @var Collection $events */ $events = $journal->piggyBankEvents()->get(); $events->each( function (PiggyBankEvent $event) { diff --git a/app/Repositories/Journal/JournalCLIRepository.php b/app/Repositories/Journal/JournalCLIRepository.php index 691e2c6638..53d7294f09 100644 --- a/app/Repositories/Journal/JournalCLIRepository.php +++ b/app/Repositories/Journal/JournalCLIRepository.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Journal; + use Carbon\Carbon; use DB; use Exception; @@ -29,7 +30,6 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Support\CacheProperties; use FireflyIII\User; use Illuminate\Support\Collection; -use Log; use stdClass; /** @@ -128,9 +128,9 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface if ($cache->has()) { $result = null; try { - $result = new Carbon($cache->get()); // @codeCoverageIgnore - } catch (Exception $e) { - $e->getMessage(); + $result = new Carbon($cache->get()); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } return $result; @@ -143,13 +143,12 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface $value = null; try { $value = new Carbon($entry->data); - } catch (Exception $e) { - $e->getMessage(); - - return null; + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException + } + if (null !== $value) { + $cache->store($value); } - - $cache->store($entry->data); return $value; } @@ -170,7 +169,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface $cache->addProperty($field); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $entry = $journal->transactionJournalMeta()->where('name', $field)->first(); @@ -188,13 +187,11 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface } // return when something else: + $return = (string)$value; try { - $return = (string)$value; $cache->store($return); - } catch (Exception $e) { - Log::error($e->getMessage()); - - return ''; + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } return $return; diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index 1268306c39..bdde8e2583 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -137,7 +137,7 @@ class JournalRepository implements JournalRepositoryInterface $cache->addProperty($journal->id); $cache->addProperty('destination-account-list'); if ($useCache && $cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $transactions = $journal->transactions()->where('amount', '>', 0)->orderBy('transactions.account_id')->with('account')->get(); $list = new Collection; @@ -165,7 +165,7 @@ class JournalRepository implements JournalRepositoryInterface $cache->addProperty($journal->id); $cache->addProperty('source-account-list'); if ($useCache && $cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $transactions = $journal->transactions()->where('amount', '<', 0)->orderBy('transactions.account_id')->with('account')->get(); $list = new Collection; @@ -192,7 +192,7 @@ class JournalRepository implements JournalRepositoryInterface $cache->addProperty($journal->id); $cache->addProperty('amount-positive'); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // saves on queries: @@ -250,7 +250,7 @@ class JournalRepository implements JournalRepositoryInterface $cache->addProperty($field); if ($cache->has()) { - return new Carbon($cache->get()); // @codeCoverageIgnore + return new Carbon($cache->get()); } $entry = TransactionJournalMeta::where('transaction_journal_id', $journalId) ->where('name', $field)->first(); @@ -278,7 +278,7 @@ class JournalRepository implements JournalRepositoryInterface } /** - * @param int $transactionId + * @param int $journalId */ public function reconcileById(int $journalId): void { diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index c6a0028461..7ab2a41aa5 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -169,7 +169,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface /** * Returns all the journal links (of a specific type). * - * @param $linkType + * @param LinkType|null $linkType * * @return Collection */ @@ -379,8 +379,8 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface if (null !== $dbNote && '' === $text) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Repositories/ObjectGroup/CreatesObjectGroups.php b/app/Repositories/ObjectGroup/CreatesObjectGroups.php index 02691f6089..2a25e58ab8 100644 --- a/app/Repositories/ObjectGroup/CreatesObjectGroups.php +++ b/app/Repositories/ObjectGroup/CreatesObjectGroups.php @@ -43,7 +43,6 @@ trait CreatesObjectGroups } /** - * @param User $user * @param string $title * * @return ObjectGroup|null diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php index 75c00e1ac2..c6098a7ccc 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php @@ -180,6 +180,14 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface return $objectGroup; } + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; + } + /** * @inheritDoc */ @@ -197,12 +205,4 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface return $objectGroup; } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } } diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepositoryInterface.php b/app/Repositories/ObjectGroup/ObjectGroupRepositoryInterface.php index fce3a6bb68..c22ff21833 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepositoryInterface.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepositoryInterface.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\ObjectGroup; use FireflyIII\Models\ObjectGroup; +use FireflyIII\User; use Illuminate\Support\Collection; /** @@ -87,6 +88,11 @@ interface ObjectGroupRepositoryInterface */ public function setOrder(ObjectGroup $objectGroup, int $newOrder): ObjectGroup; + /** + * @param User $user + */ + public function setUser(User $user): void; + /** * @param ObjectGroup $objectGroup * @param array $data diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php index 84793d7e5d..5235d66d27 100644 --- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php +++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php @@ -304,7 +304,7 @@ trait ModifiesPiggyBanks $piggyBank = PiggyBank::create($piggyData); } catch (QueryException $e) { Log::error(sprintf('Could not store piggy bank: %s', $e->getMessage()), $piggyData); - throw new FireflyException('400005: Could not store new piggy bank.'); + throw new FireflyException('400005: Could not store new piggy bank.',0,$e); } // reset order then set order: @@ -315,7 +315,7 @@ trait ModifiesPiggyBanks // repetition is auto created. $repetition = $this->getRepetition($piggyBank); - if (null !== $repetition && isset($data['current_amount']) && '' !== $data['current_amount']) { + if (null !== $repetition && array_key_exists('current_amount',$data) && '' !== $data['current_amount']) { $repetition->currentamount = $data['current_amount']; $repetition->save(); } @@ -422,8 +422,8 @@ trait ModifiesPiggyBanks if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 9b9072ded5..ec04b519d0 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -55,6 +55,7 @@ class RecurringRepository implements RecurringRepositoryInterface use CalculateRangeOccurrences, CalculateXOccurrences, CalculateXOccurrencesSince, FiltersWeekends; private User $user; + /** * Destroy a recurring transaction. * @@ -169,7 +170,7 @@ class RecurringRepository implements RecurringRepositoryInterface $query->where('transaction_journals.date', '<=', $end->format('Y-m-d 00:00:00')); } - return $query->get(['transaction_journals.*'])->count(); + return $query->count(['transaction_journals.id']); } /** @@ -240,6 +241,7 @@ class RecurringRepository implements RecurringRepositoryInterface if ('yearly' === $repetition->repetition_type) { $occurrences = $this->getYearlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); } + // filter out all the weekend days: return $this->filterWeekends($repetition, $occurrences); } @@ -332,7 +334,7 @@ class RecurringRepository implements RecurringRepositoryInterface foreach ($journalMeta as $journalId) { $search[] = (int)$journalId; } - if (empty($search)) { + if (0 === count($search)) { return new Collection; } diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 9cb50e7af9..68130393cd 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -502,7 +502,7 @@ class RuleRepository implements RuleRepositoryInterface */ private function setRuleTrigger(string $moment, Rule $rule): void { - /** @var RuleTrigger $trigger */ + /** @var RuleTrigger|null $trigger */ $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); if (null !== $trigger) { $trigger->trigger_value = $moment; diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 0acb5964b5..9f6ce7bc85 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -29,6 +29,7 @@ use FireflyIII\Factory\TagFactory; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Attachment; use FireflyIII\Models\Location; +use FireflyIII\Models\Note; use FireflyIII\Models\Tag; use FireflyIII\Models\TransactionType; use FireflyIII\User; @@ -150,12 +151,12 @@ class TagRepository implements TagRepositoryInterface $disk = Storage::disk('upload'); return $set->each( - static function (Attachment $attachment) use ($disk) { - $notes = $attachment->notes()->first(); + static function (Attachment $attachment, int $index) use ($disk) { + /** @var Note $note */ + $note = $attachment->notes()->first(); + // only used in v1 view of tags $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes = $notes ? $notes->text : ''; - - return $attachment; + $attachment->notes_text = null === $note ? '' : $note->text; } ); } @@ -171,7 +172,7 @@ class TagRepository implements TagRepositoryInterface /** * @param int|null $year * - * @return Collection + * @return array */ public function getTagsInYear(?int $year): array { @@ -384,57 +385,6 @@ class TagRepository implements TagRepositoryInterface return $sums; } - /** - * Generates a tag cloud. - * - * @param int|null $year - * - * @return array - * @deprecated - */ - public function tagCloud(?int $year): array - { - // Some vars - $tags = $this->getTagsInYear($year); - - $max = $this->getMaxAmount($tags); - $min = $this->getMinAmount($tags); - $diff = bcsub($max, $min); - $return = []; - $minimumFont = '12'; // default scale is from 12 to 24, so 12 points. - $maxPoints = '12'; - $pointsPerCoin = '0'; - - Log::debug(sprintf('Minimum is %s, maximum is %s, difference is %s', $min, $max, $diff)); - - if (0 !== bccomp($diff, '0')) { // for each full coin in tag, add so many points - // minus the smallest tag. - $pointsPerCoin = bcdiv($maxPoints, $diff); - } - - Log::debug(sprintf('Each coin in a tag earns it %s points', $pointsPerCoin)); - /** @var Tag $tag */ - foreach ($tags as $tag) { - $amount = (string)$tag->amount_sum; - $amount = '' === $amount ? '0' : $amount; - $amountMin = bcsub($amount, $min); - $pointsForTag = bcmul($amountMin, $pointsPerCoin); - $fontSize = bcadd($minimumFont, $pointsForTag); - Log::debug(sprintf('Tag "%s": Amount is %s, so points is %s', $tag->tag, $amount, $fontSize)); - - // return value for tag cloud: - $return[$tag->id] = [ - 'size' => $fontSize, - 'tag' => $tag->tag, - 'id' => $tag->id, - 'created_at' => $tag->created_at, - 'location' => $this->getLocation($tag), - ]; - } - - return $return; - } - /** * @param Tag $tag * @param Carbon $start @@ -507,51 +457,4 @@ class TagRepository implements TagRepositoryInterface return $tag; } - /** - * @param Collection $tags - * - * @return string - */ - private function getMaxAmount(Collection $tags): string - { - $max = '0'; - /** @var Tag $tag */ - foreach ($tags as $tag) { - $amount = (string)$tag->amount_sum; - $amount = '' === $amount ? '0' : $amount; - $max = 1 === bccomp($amount, $max) ? $amount : $max; - - } - Log::debug(sprintf('Maximum is %s.', $max)); - - return $max; - } - - /** - * @param Collection $tags - * - * @return string - * - */ - private function getMinAmount(Collection $tags): string - { - $min = null; - - /** @var Tag $tag */ - foreach ($tags as $tag) { - $amount = (string)$tag->amount_sum; - $amount = '' === $amount ? '0' : $amount; - - if (null === $min) { - $min = $amount; - } - $min = -1 === bccomp($amount, $min) ? $amount : $min; - } - if (null === $min) { - $min = '0'; - } - Log::debug(sprintf('Minimum is %s.', $min)); - - return $min; - } } diff --git a/app/Repositories/Tag/TagRepositoryInterface.php b/app/Repositories/Tag/TagRepositoryInterface.php index c5a019bd0b..bf231e8fb8 100644 --- a/app/Repositories/Tag/TagRepositoryInterface.php +++ b/app/Repositories/Tag/TagRepositoryInterface.php @@ -187,17 +187,6 @@ interface TagRepositoryInterface */ public function sumsOfTag(Tag $tag, ?Carbon $start, ?Carbon $end): array; - /** - * Generates a tag cloud. - * - * @param int|null $year - * - * @return array - * @deprecated - * - */ - public function tagCloud(?int $year): array; - /** * @param Tag $tag * @param Carbon $start diff --git a/app/Repositories/Telemetry/TelemetryRepository.php b/app/Repositories/Telemetry/TelemetryRepository.php index ad6026a167..403ad37c69 100644 --- a/app/Repositories/Telemetry/TelemetryRepository.php +++ b/app/Repositories/Telemetry/TelemetryRepository.php @@ -25,7 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Telemetry; use FireflyIII\Models\Telemetry; -use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Contracts\Pagination\LengthAwarePaginator; /** * Class TelemetryRepository diff --git a/app/Repositories/Telemetry/TelemetryRepositoryInterface.php b/app/Repositories/Telemetry/TelemetryRepositoryInterface.php index 898251fc53..fef7f8ddfc 100644 --- a/app/Repositories/Telemetry/TelemetryRepositoryInterface.php +++ b/app/Repositories/Telemetry/TelemetryRepositoryInterface.php @@ -23,7 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Telemetry; -use Illuminate\Pagination\LengthAwarePaginator; + +use Illuminate\Contracts\Pagination\LengthAwarePaginator; /** * Interface TelemetryRepositoryInterface diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 99575cdade..a0581d398e 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -112,7 +112,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface $result[$journalId] = $result[$journalId] ?? []; $current = $attachment->toArray(); $current['file_exists'] = true; - $current['journal_title'] = $attachment->attachable->description; + $current['journal_title'] = $attachment->attachable->description; // @phpstan-ignore-line $result[$journalId][] = $current; } @@ -246,7 +246,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface */ public function getNoteText(int $journalId): ?string { - /** @var Note $note */ + /** @var Note|null $note */ $note = Note ::where('noteable_id', $journalId) ->where('noteable_type', TransactionJournal::class) @@ -269,6 +269,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface { $return = []; $journals = $group->transactionJournals->pluck('id')->toArray(); + $currency = app('amount')->getDefaultCurrencyByUser($this->user); $data = PiggyBankEvent ::whereIn('transaction_journal_id', $journals) ->with('piggyBank', 'piggyBank.account') @@ -357,12 +358,12 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface return $factory->create($data); } catch (DuplicateTransactionException $e) { Log::warning('Group repository caught group factory with a duplicate exception!'); - throw new DuplicateTransactionException($e->getMessage()); + throw new DuplicateTransactionException($e->getMessage(),0, $e); } catch (FireflyException $e) { Log::warning('Group repository caught group factory with an exception!'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException($e->getMessage()); + throw new FireflyException($e->getMessage(),0, $e); } } diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index d17756ed9a..780d6c6376 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -96,7 +96,7 @@ class UserRepository implements UserRepositoryInterface // update user $user->email = $newEmail; - $user->blocked = 1; + $user->blocked = true; $user->blocked_code = 'email_changed'; $user->save(); @@ -215,7 +215,7 @@ class UserRepository implements UserRepositoryInterface */ public function getRoleByUser(User $user): ?string { - /** @var Role $role */ + /** @var Role|null $role */ $role = $user->roles()->first(); if (null !== $role) { return $role->name; @@ -252,7 +252,8 @@ class UserRepository implements UserRepositoryInterface ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->where('amount', '>', 0) ->whereNull('budgets.deleted_at') - ->where('budgets.user_id', $user->id)->get(['budget_limits.budget_id'])->count(); + ->where('budgets.user_id', $user->id) + ->count('budget_limits.budget_id'); $return['rule_groups'] = $user->ruleGroups()->count(); $return['rules'] = $user->rules()->count(); $return['tags'] = $user->tags()->count(); @@ -335,7 +336,7 @@ class UserRepository implements UserRepositoryInterface */ public function unblockUser(User $user): void { - $user->blocked = 0; + $user->blocked = false; $user->blocked_code = ''; $user->save(); @@ -352,13 +353,13 @@ class UserRepository implements UserRepositoryInterface public function update(User $user, array $data): User { $this->updateEmail($user, $data['email'] ?? ''); - if (isset($data['blocked']) && is_bool($data['blocked'])) { + if (array_key_exists('blocked', $data) && is_bool($data['blocked'])) { $user->blocked = $data['blocked']; } - if (isset($data['blocked_code']) && '' !== $data['blocked_code'] && is_string($data['blocked_code'])) { + if (array_key_exists('blocked_code', $data) && '' !== $data['blocked_code'] && is_string($data['blocked_code'])) { $user->blocked_code = $data['blocked_code']; } - if (isset($data['role']) && '' === $data['role']) { + if (array_key_exists('role', $data) && '' === $data['role']) { $this->removeRole($user, 'owner'); $this->removeRole($user, 'demo'); } diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php index 7140206e60..cc71d832dd 100644 --- a/app/Rules/BelongsUser.php +++ b/app/Rules/BelongsUser.php @@ -74,7 +74,7 @@ class BelongsUser implements Rule { $attribute = $this->parseAttribute($attribute); if (!auth()->check()) { - return true; // @codeCoverageIgnore + return true; } $attribute = (string)$attribute; Log::debug(sprintf('Going to validate %s', $attribute)); @@ -97,7 +97,7 @@ class BelongsUser implements Rule case 'destination_id': return $this->validateAccountId((int)$value); default: - throw new FireflyException(sprintf('Rule BelongUser cannot handle "%s"', $attribute)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Rule BelongUser cannot handle "%s"', $attribute)); } } @@ -116,7 +116,7 @@ class BelongsUser implements Rule return $parts[2]; } - return $attribute; // @codeCoverageIgnore + return $attribute; } /** @@ -186,6 +186,9 @@ class BelongsUser implements Rule */ private function validateBillId(int $value): bool { + if (0 === $value) { + return true; + } $count = Bill::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count(); return 1 === $count; diff --git a/app/Rules/IsDateOrTime.php b/app/Rules/IsDateOrTime.php index 7247f8db84..04b0331bb1 100644 --- a/app/Rules/IsDateOrTime.php +++ b/app/Rules/IsDateOrTime.php @@ -26,7 +26,6 @@ namespace FireflyIII\Rules; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; -use Exception; use Illuminate\Contracts\Validation\Rule; use Log; @@ -65,7 +64,7 @@ class IsDateOrTime implements Rule // probably a date format. try { Carbon::createFromFormat('Y-m-d', $value); - } catch (InvalidDateException | Exception $e) { + } catch (InvalidDateException $e) { Log::error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage())); return false; @@ -76,7 +75,7 @@ class IsDateOrTime implements Rule // is an atom string, I hope? try { Carbon::parse($value); - } catch (InvalidDateException | Exception $e) { + } catch (InvalidDateException $e) { Log::error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage())); return false; diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index fa67b3d0e9..df6174a3a5 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -110,7 +110,7 @@ class IsValidAttachmentModel implements Rule Transaction::class => 'validateTransaction', TransactionJournal::class => 'validateJournal', ]; - if (!isset($methods[$this->model])) { + if (!array_key_exists($this->model, $methods)) { Log::error(sprintf('Cannot validate model "%s" in %s.', $this->model, __METHOD__)); return false; diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index 62cc70010c..dd5c1c2554 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -87,10 +87,10 @@ class UniqueAccountNumber implements Rule public function passes($attribute, $value): bool { if (!auth()->check()) { - return true; // @codeCoverageIgnore + return true; } if (null === $this->expectedType) { - return true; // @codeCoverageIgnore + return true; } $maxCounts = $this->getMaxOccurrences(); diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php index 325a6ef689..7958170cff 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -84,10 +84,10 @@ class UniqueIban implements Rule public function passes($attribute, $value): bool { if (!auth()->check()) { - return true; // @codeCoverageIgnore + return true; } if (null === $this->expectedType) { - return true; // @codeCoverageIgnore + return true; } $maxCounts = $this->getMaxOccurrences(); diff --git a/app/Scopes/LdapFilterScope.php b/app/Scopes/LdapFilterScope.php index 38ba147852..0def667abe 100644 --- a/app/Scopes/LdapFilterScope.php +++ b/app/Scopes/LdapFilterScope.php @@ -27,7 +27,8 @@ namespace FireflyIII\Scopes; use Adldap\Laravel\Scopes\ScopeInterface; use Adldap\Query\Builder; -class LdapFilterScope implements ScopeInterface +// @phpstan-ignore-next-line +class LdapFilterScope implements ScopeInterface // @phpstan-ignore-line { /** * If the ADLDAP_AUTH_FILTER is provided, apply the filter to the LDAP query. diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index 2f2d4d2866..f5d1a9a27f 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -91,7 +91,7 @@ class UpdateRequest implements UpdateRequestInterface 'timeout' => 3.1415, ]; $res = $client->request('GET', $uri, $options); - } catch (GuzzleException | Exception $e) { + } catch (GuzzleException $e) { Log::error('Ran into Guzzle error.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -111,7 +111,7 @@ class UpdateRequest implements UpdateRequestInterface try { $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); - } catch (JsonException | Exception $e) { + } catch (JsonException $e) { Log::error('Body is not valid JSON'); Log::error($body); $return['message'] = 'Invalid JSON :('; @@ -119,7 +119,7 @@ class UpdateRequest implements UpdateRequestInterface return $return; } - if (!isset($json['firefly_iii'][$channel])) { + if (!array_key_exists($channel, $json['firefly_iii'])) { Log::error(sprintf('No valid update channel "%s"', $channel)); Log::error($body); $return['message'] = sprintf('Unknown update channel "%s" :(', $channel); diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index a23d4f39f3..743fe59bc9 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -69,8 +69,8 @@ class AccountDestroyService // delete account. try { $account->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete account: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -115,9 +115,32 @@ class AccountDestroyService * @param Account $account * @param Account $moveTo */ - private function moveTransactions(Account $account, Account $moveTo): void + public function moveTransactions(Account $account, Account $moveTo): void { + Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id)); DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]); + + $collection = Transaction::groupBy('transaction_journal_id', 'account_id') + ->where('account_id', $moveTo->id) + ->get(['transaction_journal_id', 'account_id', DB::raw('count(*) as the_count')]); // @phpstan-ignore-line + if (0 === $collection->count()) { + return; + } + + /** @var JournalDestroyService $service */ + $service = app(JournalDestroyService::class); + $user = $account->user; + /** @var \stdClass $row */ + foreach ($collection as $row) { + if ((int)$row->the_count > 1) { + $journalId = (int)$row->transaction_journal_id; + $journal = $user->transactionJournals()->find($journalId); + if (null !== $journal) { + Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id)); + $service->destroy($journal); + } + } + } } /** diff --git a/app/Services/Internal/Destroy/BillDestroyService.php b/app/Services/Internal/Destroy/BillDestroyService.php index 735f282ba1..e9719679bb 100644 --- a/app/Services/Internal/Destroy/BillDestroyService.php +++ b/app/Services/Internal/Destroy/BillDestroyService.php @@ -40,8 +40,8 @@ class BillDestroyService { try { $bill->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete bill: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Destroy/BudgetDestroyService.php b/app/Services/Internal/Destroy/BudgetDestroyService.php index 3fb5897e05..aa8c4190d8 100644 --- a/app/Services/Internal/Destroy/BudgetDestroyService.php +++ b/app/Services/Internal/Destroy/BudgetDestroyService.php @@ -43,8 +43,8 @@ class BudgetDestroyService try { $budget->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete budget: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } // also delete auto budget: diff --git a/app/Services/Internal/Destroy/CategoryDestroyService.php b/app/Services/Internal/Destroy/CategoryDestroyService.php index a161b16770..e93240f104 100644 --- a/app/Services/Internal/Destroy/CategoryDestroyService.php +++ b/app/Services/Internal/Destroy/CategoryDestroyService.php @@ -42,8 +42,8 @@ class CategoryDestroyService { try { $category->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete category: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } // also delete all relations between categories and transaction journals: diff --git a/app/Services/Internal/Destroy/CurrencyDestroyService.php b/app/Services/Internal/Destroy/CurrencyDestroyService.php index 358f223246..53bf9026ff 100644 --- a/app/Services/Internal/Destroy/CurrencyDestroyService.php +++ b/app/Services/Internal/Destroy/CurrencyDestroyService.php @@ -42,8 +42,8 @@ class CurrencyDestroyService try { $currency->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::error(sprintf('Could not delete transaction currency: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Destroy/JournalDestroyService.php b/app/Services/Internal/Destroy/JournalDestroyService.php index 321c3be0ae..841f39a89b 100644 --- a/app/Services/Internal/Destroy/JournalDestroyService.php +++ b/app/Services/Internal/Destroy/JournalDestroyService.php @@ -96,8 +96,8 @@ class JournalDestroyService } } - } catch (Exception $e) { - Log::error(sprintf('Could not delete bill: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Destroy/RecurrenceDestroyService.php b/app/Services/Internal/Destroy/RecurrenceDestroyService.php index 3f7ce76bc7..efa7d95f46 100644 --- a/app/Services/Internal/Destroy/RecurrenceDestroyService.php +++ b/app/Services/Internal/Destroy/RecurrenceDestroyService.php @@ -60,8 +60,8 @@ class RecurrenceDestroyService try { // delete all meta data $recurrence->recurrenceMeta()->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::info(sprintf('Could not delete recurrence meta: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } // delete all transactions. /** @var RecurrenceTransaction $transaction */ @@ -69,8 +69,8 @@ class RecurrenceDestroyService $transaction->recurrenceTransactionMeta()->delete(); try { $transaction->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::info(sprintf('Could not delete recurrence transaction: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } // delete all repetitions @@ -79,8 +79,8 @@ class RecurrenceDestroyService // delete recurrence try { $recurrence->delete(); - } catch (Exception $e) { // @codeCoverageIgnore - Log::info(sprintf('Could not delete recurrence: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php index e04736266a..c5e79feaa4 100644 --- a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php +++ b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php @@ -46,8 +46,8 @@ class TransactionGroupDestroyService } try { $transactionGroup->delete(); - } catch (Exception $e) { - app('log')->error(sprintf('Could not delete transaction group: %s', $e->getMessage())); // @codeCoverageIgnore + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index 0f8a7c8343..5926f6fcf7 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -66,6 +66,7 @@ trait AccountServiceTrait return null; } + return $iban; } @@ -84,7 +85,7 @@ trait AccountServiceTrait // not set, so false. return false; } - // if isset, but is empty: + // if is set, but is empty: if ( (array_key_exists('opening_balance', $data) && '' === $data['opening_balance']) || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date']) @@ -125,21 +126,21 @@ trait AccountServiceTrait } if ($account->accountType->type === AccountType::ASSET && array_key_exists('account_role', $data) && 'ccAsset' === $data['account_role']) { - $fields = $this->validCCFields; // @codeCoverageIgnore + $fields = $this->validCCFields; } /** @var AccountMetaFactory $factory */ $factory = app(AccountMetaFactory::class); foreach ($fields as $field) { // if the field is set but NULL, skip it. // if the field is set but "", update it. - if (isset($data[$field]) && null !== $data[$field]) { + if (array_key_exists($field, $data) && null !== $data[$field]) { // convert boolean value: if (is_bool($data[$field]) && false === $data[$field]) { - $data[$field] = 0; // @codeCoverageIgnore + $data[$field] = 0; } if (is_bool($data[$field]) && true === $data[$field]) { - $data[$field] = 1; // @codeCoverageIgnore + $data[$field] = 1; } $factory->crud($account, $field, (string)$data[$field]); @@ -161,8 +162,8 @@ trait AccountServiceTrait if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug($e->getMessage()); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -190,9 +191,9 @@ trait AccountServiceTrait { $data['opening_balance'] = (string)($data['opening_balance'] ?? ''); if ('' !== $data['opening_balance'] && 0 === bccomp($data['opening_balance'], '0')) { - $data['opening_balance'] = ''; // @codeCoverageIgnore + $data['opening_balance'] = ''; } - if ('' !== $data['opening_balance'] && isset($data['opening_balance'], $data['opening_balance_date'])) { + if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date']) { Log::debug('Array has valid opening balance data.'); return true; @@ -244,7 +245,7 @@ trait AccountServiceTrait // find currency, or use default currency instead. /** @var TransactionCurrencyFactory $factory */ $factory = app(TransactionCurrencyFactory::class); - /** @var TransactionCurrency $currency */ + /** @var TransactionCurrency|null $currency */ $currency = $factory->find($currencyId, $currencyCode); if (null === $currency) { @@ -349,11 +350,11 @@ trait AccountServiceTrait $sourceId = $account->id; } if (0 === bccomp($amount, '0')) { - // @codeCoverageIgnoreStart + Log::debug('Amount is zero, so will not make an OB group.'); return null; - // @codeCoverageIgnoreEnd + } $amount = app('steam')->positive($amount); if (!array_key_exists('currency_id', $data)) { @@ -401,14 +402,11 @@ trait AccountServiceTrait try { $group = $factory->create($submission); - // @codeCoverageIgnoreStart + } catch (FireflyException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); } - - // @codeCoverageIgnoreEnd - return $group; } } diff --git a/app/Services/Internal/Support/BillServiceTrait.php b/app/Services/Internal/Support/BillServiceTrait.php index 17b0476a3f..bf79f2330f 100644 --- a/app/Services/Internal/Support/BillServiceTrait.php +++ b/app/Services/Internal/Support/BillServiceTrait.php @@ -74,8 +74,8 @@ trait BillServiceTrait if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Error deleting note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index a5dfbe4eea..968eef3507 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -168,7 +168,7 @@ trait JournalServiceTrait * @return Account * @throws FireflyException */ - private function createAccount(?Account $account, array $data, string $preferredType): Account + private function createAccount(?Account $account, array $data, string $preferredType): ?Account { Log::debug('Now in createAccount()', $data); // return new account. @@ -185,26 +185,34 @@ trait JournalServiceTrait // final attempt, create it. if (AccountType::ASSET === $preferredType) { - throw new FireflyException('TransactionFactory: Cannot create asset account with these values', $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']) { Log::debug(sprintf('Account name is now IBAN ("%s")', $data['iban'])); $data['name'] = $data['iban']; } - + // fix name of account if only number is given: + if ('' === (string)$data['name'] && '' !== (string)$data['number']) { + Log::debug(sprintf('Account name is now account number ("%s")', $data['number'])); + $data['name'] = $data['number']; + } + // if name is still NULL, return NULL. + if(null === $data['name']) { + return null; + } $data['name'] = $data['name'] ?? '(no name)'; $account = $this->accountRepository->store( [ - 'account_type_id' => null, - 'account_type' => $preferredType, - 'name' => $data['name'], - 'virtual_balance' => null, - 'active' => true, - 'iban' => $data['iban'], - 'currency_id' => $data['currency_id'] ?? null, - 'order' => $this->accountRepository->maxOrder($preferredType), + 'account_type_id' => null, + 'account_type_name' => $preferredType, + 'name' => $data['name'], + 'virtual_balance' => null, + 'active' => true, + 'iban' => $data['iban'], + 'currency_id' => $data['currency_id'] ?? null, + 'order' => $this->accountRepository->maxOrder($preferredType), ] ); // store BIC @@ -358,11 +366,9 @@ trait JournalServiceTrait // try to delete existing notes. try { $note->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::debug(sprintf('Could not delete journal notes: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } - // @codeCoverageIgnoreEnd } } diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index b2974b289b..45089c8d4c 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -41,6 +41,7 @@ use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Validation\AccountValidator; use Log; + /** * Trait RecurringTransactionTrait * @@ -60,8 +61,8 @@ trait RecurringTransactionTrait if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Error deleting note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -135,11 +136,11 @@ trait RecurringTransactionTrait $validator->setUser($recurrence->user); $validator->setTransactionType($recurrence->transactionType->type); if (!$validator->validateSource($source->id, null, null)) { - throw new FireflyException(sprintf('Source invalid: %s', $validator->sourceError)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Source invalid: %s', $validator->sourceError)); } if (!$validator->validateDestination($destination->id, null, null)) { - throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError)); // @codeCoverageIgnore + throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError)); } if (array_key_exists('foreign_amount', $array) && '' === (string)$array['foreign_amount']) { unset($array['foreign_amount']); @@ -179,10 +180,9 @@ trait RecurringTransactionTrait } /** - * @param array $expectedTypes - * @param Account|null $account - * @param int|null $accountId - * @param string|null $accountName + * @param array $expectedTypes + * @param int|null $accountId + * @param string|null $accountName * * @return Account */ @@ -212,6 +212,7 @@ trait RecurringTransactionTrait /** @var AccountFactory $factory */ $factory = app(AccountFactory::class); $factory->setUser($this->user); + /** @var string $expectedType */ foreach ($expectedTypes as $expectedType) { if (in_array($expectedType, $cannotCreate, true)) { continue; @@ -219,11 +220,11 @@ trait RecurringTransactionTrait if (!in_array($expectedType, $cannotCreate, true)) { try { $result = $factory->findOrCreate($accountName, $expectedType); - // @codeCoverageIgnoreStart + } catch (FireflyException $e) { Log::error($e->getMessage()); } - // @codeCoverageIgnoreEnd + } } @@ -287,7 +288,7 @@ trait RecurringTransactionTrait $factory->setUser($transaction->recurrence->user); $piggyBank = $factory->find($piggyId, null); if (null !== $piggyBank) { - /** @var RecurrenceMeta $entry */ + /** @var RecurrenceMeta|null $entry */ $entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first(); if (null === $entry) { $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]); @@ -307,8 +308,8 @@ trait RecurringTransactionTrait */ protected function updateTags(RecurrenceTransaction $transaction, array $tags): void { - if (!empty($tags)) { - /** @var RecurrenceMeta $entry */ + if (count($tags) > 0) { + /** @var RecurrenceMeta|null $entry */ $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); if (null === $entry) { $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]); @@ -316,7 +317,7 @@ trait RecurringTransactionTrait $entry->value = json_encode($tags); $entry->save(); } - if (empty($tags)) { + if (0 === count($tags)) { // delete if present $transaction->recurrenceTransactionMeta()->where('name', 'tags')->delete(); } @@ -345,8 +346,8 @@ trait RecurringTransactionTrait $transaction->recurrenceTransactionMeta()->delete(); try { $transaction->delete(); - } catch (Exception $e) { - Log::debug($e->getMessage()); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } } diff --git a/app/Services/Internal/Support/TransactionTypeTrait.php b/app/Services/Internal/Support/TransactionTypeTrait.php index ffaa0552a7..650b75ccdb 100644 --- a/app/Services/Internal/Support/TransactionTypeTrait.php +++ b/app/Services/Internal/Support/TransactionTypeTrait.php @@ -48,8 +48,8 @@ trait TransactionTypeTrait $factory = app(TransactionTypeFactory::class); $transactionType = $factory->find($type); if (null === $transactionType) { - Log::error(sprintf('Could not find transaction type for "%s"', $type)); // @codeCoverageIgnore - throw new FireflyException(sprintf('Could not find transaction type for "%s"', $type)); // @codeCoverageIgnore + Log::error(sprintf('Could not find transaction type for "%s"', $type)); + throw new FireflyException(sprintf('Could not find transaction type for "%s"', $type)); } return $transactionType; diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index ec51c6d6dd..09ca4f9833 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -51,12 +51,11 @@ class AccountUpdateService */ public function __construct() { - // TODO move to configuration. - $this->canHaveVirtual = [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD]; + $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); $this->accountRepository = app(AccountRepositoryInterface::class); - $this->validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; - $this->validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; - $this->validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth']; } /** @@ -100,12 +99,12 @@ class AccountUpdateService $this->updateOpeningBalance($account, $data); // update note: - if (isset($data['notes']) && null !== $data['notes']) { + if (array_key_exists('notes', $data) && null !== $data['notes']) { $this->updateNote($account, (string)$data['notes']); } // update preferences if inactive: - $this->updatePreferences($account, $data); + $this->updatePreferences($account); return $account; } @@ -290,34 +289,29 @@ class AccountUpdateService /** * @param Account $account - * @param array $data */ - private function updatePreferences(Account $account, array $data): void + private function updatePreferences(Account $account): void { - Log::debug(sprintf('Now in updatePreferences(#%d)', $account->id)); - if (array_key_exists('active', $data) && (false === $data['active'] || 0 === $data['active'])) { - Log::debug('Account was marked as inactive.'); - $preference = app('preferences')->getForUser($account->user, 'frontpageAccounts'); - if (null !== $preference) { - $removeAccountId = (int)$account->id; - $array = $preference->data; - Log::debug('Current list of accounts: ', $array); - Log::debug(sprintf('Going to remove account #%d', $removeAccountId)); - $filtered = array_filter( - $array, function ($accountId) use ($removeAccountId) { - return (int)$accountId !== $removeAccountId; - } - ); - Log::debug('Left with accounts', array_values($filtered)); - app('preferences')->setForUser($account->user, 'frontpageAccounts', array_values($filtered)); - app('preferences')->forget($account->user, 'frontpageAccounts'); - - return; - } - Log::debug("Found no frontpageAccounts preference, do nothing."); - + $account->refresh(); + if (true === $account->active) { return; } - Log::debug('Account was not marked as inactive, do nothing.'); + $preference = app('preferences')->getForUser($account->user, 'frontpageAccounts'); + if (null === $preference) { + return; + } + $array = $preference->data; + Log::debug('Old array is: ', $array); + Log::debug(sprintf('Must remove : %d', $account->id)); + $removeAccountId = (int)$account->id; + $new = []; + foreach ($array as $value) { + if ((int)$value !== $removeAccountId) { + Log::debug(sprintf('Will include: %d', $value)); + $new[] = (int)$value; + } + } + Log::debug('Final new array is', $new); + app('preferences')->setForUser($account->user, 'frontpageAccounts', $new); } } diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index 48616fd059..c1a1cc1ffb 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -144,20 +144,20 @@ class BillUpdateService */ private function updateBillProperties(Bill $bill, array $data): Bill { - if (isset($data['name']) && '' !== (string)$data['name']) { + if (array_key_exists('name', $data) && '' !== (string)$data['name']) { $bill->name = $data['name']; } - if (isset($data['amount_min']) && '' !== (string)$data['amount_min']) { + if (array_key_exists('amount_min', $data) && '' !== (string)$data['amount_min']) { $bill->amount_min = $data['amount_min']; } - if (isset($data['amount_max']) && '' !== (string)$data['amount_max']) { + if (array_key_exists('amount_max', $data) && '' !== (string)$data['amount_max']) { $bill->amount_max = $data['amount_max']; } - if (isset($data['date']) && '' !== (string)$data['date']) { + if (array_key_exists('date', $data) && '' !== (string)$data['date']) { $bill->date = $data['date']; } - if (isset($data['repeat_freq']) && '' !== (string)$data['repeat_freq']) { + if (array_key_exists('repeat_freq', $data) && '' !== (string)$data['repeat_freq']) { $bill->repeat_freq = $data['repeat_freq']; } if (array_key_exists('skip', $data)) { diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php index c3e96764f6..6520cabdad 100644 --- a/app/Services/Internal/Update/CategoryUpdateService.php +++ b/app/Services/Internal/Update/CategoryUpdateService.php @@ -153,8 +153,8 @@ class CategoryUpdateService if (null !== $dbNote) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug($e->getMessage()); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index 0c7bf27885..3146eea33b 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -130,15 +130,15 @@ class GroupUpdateService foreach ($transactions as $index => $transaction) { Log::debug(sprintf('Now at #%d of %d', ($index + 1), count($transactions)), $transaction); $journalId = (int)($transaction['transaction_journal_id'] ?? 0); - /** @var TransactionJournal $journal */ + /** @var TransactionJournal|null $journal */ $journal = $transactionGroup->transactionJournals()->find($journalId); if (null === $journal) { Log::debug('This entry has no existing journal: make a new split.'); // force the transaction type on the transaction data. // by plucking it from another journal in the group: - if (!isset($transaction['type'])) { + if (!array_key_exists('type', $transaction)) { Log::debug('No transaction type is indicated.'); - /** @var TransactionJournal $randomJournal */ + /** @var TransactionJournal|null $randomJournal */ $randomJournal = $transactionGroup->transactionJournals()->inRandomOrder()->with(['transactionType'])->first(); if (null !== $randomJournal) { $transaction['type'] = $randomJournal->transactionType->type; @@ -182,7 +182,7 @@ class GroupUpdateService } catch (FireflyException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException(sprintf('Could not create new transaction journal: %s', $e->getMessage())); + throw new FireflyException(sprintf('Could not create new transaction journal: %s', $e->getMessage()), 0, $e); } $collection->each( function (TransactionJournal $journal) use ($transactionGroup) { diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index 3203bd3796..3a285c2c21 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -616,7 +616,7 @@ class JournalUpdateService if ($this->hasFields([$field])) { try { $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]); - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); return; diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index b7370de5e2..cc6a3cfc40 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -133,11 +133,10 @@ class RecurrenceUpdateService if (null !== $dbNote && '' === $text) { try { $dbNote->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete note: %s', $e->getMessage())); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } - } /** @@ -252,7 +251,7 @@ class RecurrenceUpdateService $currency = $currencyFactory->find($current['currency_id'] ?? null, $currency['currency_code'] ?? null); } if (null === $currency) { - unset($current['currency_id'], $currency['currency_code']); + unset($current['currency_id'], $current['currency_code']); } if (null !== $currency) { $current['currency_id'] = (int)$currency->id; diff --git a/app/Services/Password/PwndVerifierV2.php b/app/Services/Password/PwndVerifierV2.php index 8566ba7dbf..6ebdae729b 100644 --- a/app/Services/Password/PwndVerifierV2.php +++ b/app/Services/Password/PwndVerifierV2.php @@ -22,9 +22,9 @@ declare(strict_types=1); namespace FireflyIII\Services\Password; -use Exception; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; +use GuzzleHttp\Exception\RequestException; use Log; use RuntimeException; @@ -51,7 +51,7 @@ class PwndVerifierV2 implements Verifier $uri = sprintf('https://api.pwnedpasswords.com/range/%s', $prefix); $opt = [ 'headers' => [ - 'User-Agent' => 'Firefly III v' . config('firefly.version'), + 'User-Agent' => sprintf('Firefly III v%s', config('firefly.version')), 'Add-Padding' => 'true', ], 'timeout' => 3.1415]; @@ -62,7 +62,7 @@ class PwndVerifierV2 implements Verifier try { $client = new Client(); $res = $client->request('GET', $uri, $opt); - } catch (GuzzleException | Exception $e) { + } catch (GuzzleException | RequestException $e) { Log::error(sprintf('Could not verify password security: %s', $e->getMessage())); return true; @@ -73,7 +73,7 @@ class PwndVerifierV2 implements Verifier } try { $strpos = stripos($res->getBody()->getContents(), $rest); - } catch (RuntimeException $e) { + } catch (RuntimeException $e) { // @phpstan-ignore-line Log::error(sprintf('Could not get body from Pwnd result: %s', $e->getMessage())); $strpos = false; } diff --git a/app/Services/Webhook/StandardWebhookSender.php b/app/Services/Webhook/StandardWebhookSender.php index 90035f6b31..a877d4a355 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -23,12 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Services\Webhook; -use Exception; use FireflyIII\Helpers\Webhook\SignatureGeneratorInterface; use FireflyIII\Models\WebhookAttempt; use FireflyIII\Models\WebhookMessage; use GuzzleHttp\Client; -use GuzzleHttp\Exception\ClientException; +use GuzzleHttp\Exception\RequestException; use JsonException; use Log; @@ -92,7 +91,7 @@ class StandardWebhookSender implements WebhookSenderInterface try { $res = $client->request('POST', $this->message->webhook->url, $options); $this->message->sent = true; - } catch (ClientException | Exception $e) { + } catch (RequestException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -104,7 +103,7 @@ class StandardWebhookSender implements WebhookSenderInterface $attempt = new WebhookAttempt; $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = $e->getResponse() ? $e->getResponse()->getStatusCode() : 0; + $attempt->status_code = $e->hasResponse() ? $e->getResponse()->getStatusCode() : 0; $attempt->logs = $logs; $attempt->save(); diff --git a/app/Support/Amount.php b/app/Support/Amount.php index d2280d48f0..f16e7037a3 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -115,7 +115,7 @@ class Amount $cache = new CacheProperties; $cache->addProperty('getCurrencyCode'); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $currencyPreference = app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR')); @@ -152,7 +152,7 @@ class Amount $cache->addProperty('getDefaultCurrency'); $cache->addProperty($user->id); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $currencyPreference = app('preferences')->getForUser($user, 'currencyPreference', config('firefly.default_currency', 'EUR')); $currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR'; @@ -164,7 +164,7 @@ class Amount if (strlen($currencyCode) > 3) { $currencyCode = json_decode($currencyCode, true, 512, JSON_THROW_ON_ERROR) ?? 'EUR'; } - /** @var TransactionCurrency $currency */ + /** @var TransactionCurrency|null $currency */ $currency = TransactionCurrency::where('code', $currencyCode)->first(); if (null === $currency) { // get EUR @@ -185,7 +185,7 @@ class Amount try { $value = Crypt::decrypt($value); // verified } catch (DecryptException $e) { - // ignore decryption error. + // @ignoreException } return $value; diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index 9d24ca6f1a..f5ab52986a 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -47,7 +47,8 @@ class RemoteUserGuard implements Guard * * @return void */ - public function __construct(UserProvider $provider, Application $app) + // @phpstan-ignore-next-line + public function __construct(UserProvider $provider, Application $app) // @phpstan-ignore-line { $this->application = $app; $this->provider = $provider; diff --git a/app/Support/Binder/BudgetList.php b/app/Support/Binder/BudgetList.php index c0bb888b4f..ba4daf89f2 100644 --- a/app/Support/Binder/BudgetList.php +++ b/app/Support/Binder/BudgetList.php @@ -54,12 +54,12 @@ class BudgetList implements BinderInterface $list = array_unique(array_map('\intval', explode(',', $value))); - // @codeCoverageIgnoreStart + if (0 === count($list)) { Log::warning('Budget list count is zero, return 404.'); throw new NotFoundHttpException; } - // @codeCoverageIgnoreEnd + /** @var Collection $collection */ $collection = auth()->user()->budgets() diff --git a/app/Support/Binder/CategoryList.php b/app/Support/Binder/CategoryList.php index de7f2a13f8..60a36b97d4 100644 --- a/app/Support/Binder/CategoryList.php +++ b/app/Support/Binder/CategoryList.php @@ -51,7 +51,7 @@ class CategoryList implements BinderInterface $list = array_unique(array_map('\intval', explode(',', $value))); if (0 === count($list)) { - throw new NotFoundHttpException; // @codeCoverageIgnore + throw new NotFoundHttpException; } /** @var \Illuminate\Support\Collection $collection */ diff --git a/app/Support/Binder/Date.php b/app/Support/Binder/Date.php index 423b699a7d..d458b343f5 100644 --- a/app/Support/Binder/Date.php +++ b/app/Support/Binder/Date.php @@ -62,7 +62,7 @@ class Date implements BinderInterface 'previousFiscalYearStart' => $fiscalHelper->startOfFiscalYear(Carbon::now())->subYear(), 'previousFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(Carbon::now())->subYear(), ]; - if (isset($magicWords[$value])) { + if (array_key_exists($value, $magicWords)) { $return = $magicWords[$value]; Log::debug(sprintf('User requests "%s", so will return "%s"', $value, $return)); @@ -71,7 +71,7 @@ class Date implements BinderInterface try { $result = new Carbon($value); - } catch (Exception $e) { + } catch (Exception $e) { // @phpstan-ignore-line Log::error(sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage())); throw new NotFoundHttpException; } diff --git a/app/Support/Binder/EitherConfigKey.php b/app/Support/Binder/EitherConfigKey.php index a880ff6873..3956afb77d 100644 --- a/app/Support/Binder/EitherConfigKey.php +++ b/app/Support/Binder/EitherConfigKey.php @@ -35,6 +35,12 @@ class EitherConfigKey 'firefly.default_location', 'firefly.account_to_transaction', 'firefly.allowed_opposing_types', + 'firefly.accountRoles', + 'firefly.valid_liabilities', + 'firefly.interest_periods', + 'firefly.enable_external_map', + 'firefly.expected_source_types', + 'app.timezone', ]; /** * @param string $value diff --git a/app/Support/Binder/JournalList.php b/app/Support/Binder/JournalList.php index 2ae8f9ad94..c562ebebc6 100644 --- a/app/Support/Binder/JournalList.php +++ b/app/Support/Binder/JournalList.php @@ -69,7 +69,7 @@ class JournalList implements BinderInterface { $list = array_unique(array_map('\intval', explode(',', $value))); if (0 === count($list)) { - throw new NotFoundHttpException; // @codeCoverageIgnore + throw new NotFoundHttpException; } return $list; diff --git a/app/Support/Binder/TagList.php b/app/Support/Binder/TagList.php index a35a048bd3..07d2d5ab53 100644 --- a/app/Support/Binder/TagList.php +++ b/app/Support/Binder/TagList.php @@ -52,12 +52,12 @@ class TagList implements BinderInterface } $list = array_unique(array_map('\strtolower', explode(',', $value))); Log::debug('List of tags is', $list); - // @codeCoverageIgnoreStart + if (0 === count($list)) { Log::error('Tag list is empty.'); throw new NotFoundHttpException; } - // @codeCoverageIgnoreEnd + /** @var TagRepositoryInterface $repository */ $repository = app(TagRepositoryInterface::class); diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index 4d7c36ab15..8301e839f9 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -23,9 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Support; use Cache; -use Carbon\Carbon; -use FireflyIII\Models\Category; use Illuminate\Support\Collection; +use JsonException; /** * Class CacheProperties. @@ -34,10 +33,8 @@ use Illuminate\Support\Collection; */ class CacheProperties { - /** @var string */ - protected $hash = ''; - /** @var Collection */ - protected $properties; + protected string $hash = ''; + protected Collection $properties; /** * @@ -52,8 +49,7 @@ class CacheProperties } /** - * @param $property - * @param Collection|Carbon|Category|array|int|string $property + * @param mixed $property */ public function addProperty($property): void { @@ -90,19 +86,24 @@ class CacheProperties } /** + * @throws JsonException */ private function hash(): void { $content = ''; foreach ($this->properties as $property) { - $content .= json_encode($property, JSON_THROW_ON_ERROR, 512); + try { + $content .= json_encode($property, JSON_THROW_ON_ERROR, 512); + } catch (JsonException $e) { + // @ignoreException + $content .= hash('sha256', (string)time()); + } } $this->hash = substr(hash('sha256', $content), 0, 16); } /** - * @param $data - * @param (array|mixed)[]|Collection|\Carbon\Carbon|string $data + * @param mixed $data */ public function store($data): void { diff --git a/app/Support/Chart/Budget/FrontpageChartGenerator.php b/app/Support/Chart/Budget/FrontpageChartGenerator.php index 3ea24b1cb2..941fdfabe0 100644 --- a/app/Support/Chart/Budget/FrontpageChartGenerator.php +++ b/app/Support/Chart/Budget/FrontpageChartGenerator.php @@ -30,6 +30,7 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Collection; + /** * Class FrontpageChartGenerator */ @@ -97,12 +98,7 @@ class FrontpageChartGenerator return $this->noBudgetLimits($data, $budget); } - // if limits: - if (0 !== $limits->count()) { - return $this->budgetLimits($data, $budget, $limits); - } - - return $data; + return $this->budgetLimits($data, $budget, $limits); } /** diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php index b79592cf19..97efb1a165 100644 --- a/app/Support/Chart/Category/WholePeriodChartGenerator.php +++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php @@ -130,13 +130,13 @@ class WholePeriodChartGenerator $step = '1D'; $months = $start->diffInMonths($end); if ($months > 3) { - $step = '1W'; // @codeCoverageIgnore + $step = '1W'; } if ($months > 24) { - $step = '1M'; // @codeCoverageIgnore + $step = '1M'; } if ($months > 100) { - $step = '1Y'; // @codeCoverageIgnore + $step = '1Y'; } return $step; diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index a43005de6c..19a5ae44a2 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -25,6 +25,7 @@ namespace FireflyIII\Support\Cronjobs; use Carbon\Carbon; use Exception; +use FireflyIII\Exceptions\FireflyException; /** * Class AbstractCronjob @@ -45,8 +46,6 @@ abstract class AbstractCronjob /** * AbstractCronjob constructor. - * - * @throws Exception */ public function __construct() { @@ -66,7 +65,7 @@ abstract class AbstractCronjob /** * @param Carbon $date */ - public function setDate(Carbon $date): void + final public function setDate(Carbon $date): void { $newDate = clone $date; $this->date = $newDate; @@ -75,7 +74,7 @@ abstract class AbstractCronjob /** * @param bool $force */ - public function setForce(bool $force): void + final public function setForce(bool $force): void { $this->force = $force; } diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php index 96bf9d5f96..bfd5118f36 100644 --- a/app/Support/Cronjobs/AutoBudgetCronjob.php +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -43,7 +43,7 @@ class AutoBudgetCronjob extends AbstractCronjob $config = app('fireflyconfig')->get('last_ab_job', 0); $lastTime = (int)$config->data; $diff = time() - $lastTime; - $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), true); + $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime),null, true); if (0 === $lastTime) { Log::info('Auto budget cron-job has never fired before.'); } diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index f68f826a0d..4c00551e3d 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -44,7 +44,7 @@ class RecurringCronjob extends AbstractCronjob $config = app('fireflyconfig')->get('last_rt_job', 0); $lastTime = (int)$config->data; $diff = time() - $lastTime; - $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), true); + $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null,true); if (0 === $lastTime) { Log::info('Recurring transactions cron-job has never fired before.'); diff --git a/app/Support/Cronjobs/TelemetryCronjob.php b/app/Support/Cronjobs/TelemetryCronjob.php index 624f1f523f..88a7850ef5 100644 --- a/app/Support/Cronjobs/TelemetryCronjob.php +++ b/app/Support/Cronjobs/TelemetryCronjob.php @@ -54,7 +54,7 @@ class TelemetryCronjob extends AbstractCronjob $config = app('fireflyconfig')->get('last_tm_job', 0); $lastTime = (int)$config->data; $diff = time() - $lastTime; - $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), true); + $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { Log::info('Telemetry cron-job has never fired before.'); } diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index d5fb36f40a..a5286b9b7a 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -64,7 +64,7 @@ class ExpandedForm } try { $html = prefixView('form.amount-no-currency', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); $html = 'Could not render amountNoCurrency.'; } @@ -100,7 +100,7 @@ class ExpandedForm unset($options['placeholder'], $options['autocomplete'], $options['class']); try { $html = prefixView('form.checkbox', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); $html = 'Could not render checkbox.'; } @@ -125,7 +125,7 @@ class ExpandedForm unset($options['placeholder']); try { $html = prefixView('form.date', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render date(): %s', $e->getMessage())); $html = 'Could not render date.'; } @@ -148,7 +148,7 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { $html = prefixView('form.file', compact('classes', 'name', 'label', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render file(): %s', $e->getMessage())); $html = 'Could not render file.'; } @@ -174,7 +174,7 @@ class ExpandedForm $options['step'] = '1'; try { $html = prefixView('form.integer', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render integer(): %s', $e->getMessage())); $html = 'Could not render integer.'; } @@ -199,7 +199,7 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { $html = prefixView('form.location', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render location(): %s', $e->getMessage())); $html = 'Could not render location.'; } @@ -220,12 +220,12 @@ class ExpandedForm $fields = ['title', 'name', 'description']; /** @var Eloquent $entry */ foreach ($set as $entry) { - $entryId = (int)$entry->id; + $entryId = (int)$entry->id; // @phpstan-ignore-line $title = null; foreach ($fields as $field) { - if (isset($entry->$field) && null === $title) { - $title = $entry->$field; + if (property_exists($entry, $field) && null === $title) { + $title = $entry->$field; // @phpstan-ignore-line } } $selectList[$entryId] = $title; @@ -257,7 +257,7 @@ class ExpandedForm } try { $html = prefixView('form.non-selectable-amount', compact('selectedCurrency', 'classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render nonSelectableAmount(): %s', $e->getMessage())); $html = 'Could not render nonSelectableAmount.'; } @@ -283,7 +283,7 @@ class ExpandedForm unset($options['placeholder']); try { $html = prefixView('form.number', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render number(): %s', $e->getMessage())); $html = 'Could not render number.'; } @@ -312,7 +312,7 @@ class ExpandedForm try { $html = prefixView('form.object_group', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); $html = 'Could not render objectGroup.'; } @@ -331,7 +331,7 @@ class ExpandedForm { try { $html = prefixView('form.options', compact('type', 'name'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render optionsList.'; } @@ -354,7 +354,7 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { $html = prefixView('form.password', compact('classes', 'name', 'label', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render password(): %s', $e->getMessage())); $html = 'Could not render password.'; } @@ -382,7 +382,7 @@ class ExpandedForm unset($options['placeholder']); try { $html = prefixView('form.percentage', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render percentage(): %s', $e->getMessage())); $html = 'Could not render percentage.'; } @@ -405,7 +405,7 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { $html = prefixView('form.static', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render staticText(): %s', $e->getMessage())); $html = 'Could not render staticText.'; } @@ -429,7 +429,7 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { $html = prefixView('form.text', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render text(): %s', $e->getMessage())); $html = 'Could not render text.'; } @@ -459,7 +459,7 @@ class ExpandedForm try { $html = prefixView('form.textarea', compact('classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render textarea(): %s', $e->getMessage())); $html = 'Could not render textarea.'; } diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index 612c10b818..03657a2201 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Export; use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Account; use FireflyIII\Models\Bill; @@ -52,6 +53,7 @@ use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface use FireflyIII\User; use Illuminate\Support\Collection; use League\Csv\CannotInsertRecord; +use League\Csv\Exception; use League\Csv\Writer; /** @@ -93,6 +95,8 @@ class ExportDataGenerator /** * @return array * @throws CannotInsertRecord + * @throws Exception + * @throws FireflyException */ public function export(): array { @@ -168,16 +172,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportBills(): string { @@ -211,17 +226,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string - * @throws CannotInsertRecord + * @throws FireflyException */ private function exportBudgets(): string { @@ -265,17 +290,28 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportCategories(): string { @@ -303,16 +339,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportPiggies(): string { @@ -356,16 +403,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportRecurring(): string { @@ -397,7 +455,7 @@ class ExportDataGenerator $recurrence->transactionType->type, $recurrence->title, $recurrence->description, - $recurrence->first_date ? $recurrence->first_date->format('Y-m-d') : null, + null !== $recurrence->first_date ? $recurrence->first_date->format('Y-m-d') : null, $recurrence->repeat_until ? $recurrence->repeat_until->format('Y-m-d') : null, $recurrence->latest_date ? $recurrence->latest_date->format('Y-m-d') : null, $recurrence->repetitions, @@ -443,16 +501,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportRules(): string { @@ -468,7 +537,7 @@ class ExportDataGenerator $records[] = [ $this->user->id, $rule->id, 'rule', $rule->created_at->toAtomString(), $rule->updated_at->toAtomString(), - $rule->ruleGroup->id, $rule->ruleGroup->name, + $rule->ruleGroup->id, $rule->ruleGroup->title, $rule->title, $rule->description, $rule->order, $rule->active, $rule->stop_processing, $rule->strict, ]; /** @var RuleTrigger $trigger */ @@ -499,16 +568,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportTags(): string { @@ -538,16 +618,27 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** * @return string + * @throws FireflyException */ private function exportTransactions(): string { @@ -647,12 +738,22 @@ class ExportDataGenerator $csv = Writer::createFromString(''); //insert the header - $csv->insertOne($header); + try { + $csv->insertOne($header); + } catch (CannotInsertRecord $e) { + throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); + } //insert all the records $csv->insertAll($records); - return $csv->getContent(); //returns the CSV document as a string + try { + $string = $csv->toString(); + } catch (Exception $e) { + throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); + } + + return $string; } /** @@ -662,7 +763,7 @@ class ExportDataGenerator */ private function mergeTags(array $tags): string { - if (empty($tags)) { + if (0 === count($tags)) { return ''; } $smol = []; diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index de5e3cd02f..5f923758b9 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -27,7 +27,6 @@ use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Configuration; use Illuminate\Database\QueryException; -use Log; /** * Class FireflyConfig. @@ -48,9 +47,8 @@ class FireflyConfig } try { Configuration::where('name', $name)->delete(); - } catch (Exception $e) { - Log::debug(sprintf('Could not delete config value: %s', $e->getMessage())); - + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } } @@ -65,8 +63,8 @@ class FireflyConfig } /** - * @param string $name - * @param null $default + * @param string $name + * @param bool|string|int|null $default * * @return Configuration|null * @throws FireflyException @@ -79,13 +77,13 @@ class FireflyConfig } try { - /** @var Configuration $config */ + /** @var Configuration|null $config */ $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); - } catch (QueryException | Exception $e) { + } catch (QueryException | Exception $e) { // @phpstan-ignore-line throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage())); } - if ($config) { + if (null !== $config) { Cache::forever($fullName, $config); return $config; @@ -122,29 +120,26 @@ class FireflyConfig /** * @param string $name - * @param $value + * @param mixed $value * * @return Configuration */ public function put(string $name, $value): Configuration { - return $this->set($name, $value); } /** - * @param string $name - * @param $value - * @param int|string|true $value + * @param string $name + * @param mixed $value * * @return Configuration */ public function set(string $name, $value): Configuration { - /** @var Configuration $config */ try { $config = Configuration::whereName($name)->first(); - } catch (QueryException | Exception $e) { + } catch (QueryException | Exception $e) { // @phpstan-ignore-line $item = new Configuration; $item->name = $name; $item->data = $value; diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index 17c1c59f3a..16b0ae0b40 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -43,9 +43,9 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -94,9 +94,9 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -116,11 +116,10 @@ class AccountForm /** * Check list of asset accounts. * - * @param string $name - * @param array $options + * @param string $name + * @param array|null $options * * @return string - * */ public function assetAccountCheckList(string $name, array $options = null): string { @@ -137,7 +136,7 @@ class AccountForm unset($options['class']); try { $html = prefixView('form.assetAccountCheckList', compact('classes', 'selected', 'name', 'label', 'options', 'grouped'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); $html = 'Could not render assetAccountCheckList.'; } @@ -148,9 +147,9 @@ class AccountForm /** * Basic list of asset accounts. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -164,9 +163,9 @@ class AccountForm /** * Same list but all liabilities as well. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index 5e7e2e888c..e27d167150 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -22,8 +22,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; + use Amount as Amt; -use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use Illuminate\Support\Collection; @@ -42,9 +42,9 @@ class CurrencyForm use FormSupport; /** - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -54,13 +54,12 @@ class CurrencyForm } /** - * @param string $name - * @param string $view - * @param mixed $value - * @param array $options + * @param string $name + * @param string $view + * @param mixed $value + * @param array|null $options * * @return string - * */ protected function currencyField(string $name, string $view, $value = null, array $options = null): string { @@ -77,7 +76,7 @@ class CurrencyForm // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) $preFilled = session('preFilled'); $key = 'amount_currency_id_' . $name; - $sentCurrencyId = isset($preFilled[$key]) ? (int)$preFilled[$key] : $defaultCurrency->id; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -96,7 +95,7 @@ class CurrencyForm } try { $html = prefixView('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; } @@ -107,12 +106,11 @@ class CurrencyForm /** * TODO describe and cleanup. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string - * @throws FireflyException */ public function balanceAll(string $name, $value = null, array $options = null): string { @@ -122,13 +120,12 @@ class CurrencyForm /** * TODO cleanup and describe better. * - * @param string $name - * @param string $view - * @param mixed $value - * @param array $options + * @param string $name + * @param string $view + * @param mixed $value + * @param array|null $options * * @return string - * */ protected function allCurrencyField(string $name, string $view, $value = null, array $options = null): string { @@ -145,7 +142,7 @@ class CurrencyForm // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) $preFilled = session('preFilled'); $key = 'amount_currency_id_' . $name; - $sentCurrencyId = isset($preFilled[$key]) ? (int)$preFilled[$key] : $defaultCurrency->id; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -164,7 +161,7 @@ class CurrencyForm } try { $html = prefixView('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; } @@ -175,9 +172,9 @@ class CurrencyForm /** * TODO cleanup and describe. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -200,9 +197,9 @@ class CurrencyForm /** * TODO cleanup and describe. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index ccad30a682..c6c720cc44 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -37,10 +37,10 @@ use Throwable; trait FormSupport { /** - * @param string $name - * @param array $list - * @param mixed $selected - * @param array $options + * @param string $name + * @param array|null $list + * @param mixed $selected + * @param array|null $options * * @return string */ @@ -54,7 +54,7 @@ trait FormSupport unset($options['autocomplete'], $options['placeholder']); try { $html = prefixView('form.select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render select.'; } @@ -63,15 +63,15 @@ trait FormSupport } /** - * @param $name - * @param $options + * @param string $name + * @param array|null $options * * @return string */ protected function label(string $name, array $options = null): string { $options = $options ?? []; - if (isset($options['label'])) { + if (array_key_exists('label', $options)) { return $options['label']; } $name = str_replace('[]', '', $name); @@ -80,9 +80,9 @@ trait FormSupport } /** - * @param $name - * @param $label - * @param array $options + * @param string $name + * @param mixed $label + * @param array|null $options * * @return array */ @@ -99,7 +99,7 @@ trait FormSupport } /** - * @param $name + * @param string $name * * @return string */ @@ -118,8 +118,8 @@ trait FormSupport } /** - * @param string $name - * @param $value + * @param string $name + * @param mixed|null $value * * @return mixed */ @@ -127,14 +127,14 @@ trait FormSupport { if (app('session')->has('preFilled')) { $preFilled = session('preFilled'); - $value = isset($preFilled[$name]) && null === $value ? $preFilled[$name] : $value; + $value = array_key_exists($name, $preFilled) && null === $value ? $preFilled[$name] : $value; } try { if (null !== request()->old($name)) { $value = request()->old($name); } - } catch (RuntimeException $e) { + } catch (RuntimeException $e) { // @phpstan-ignore-line // don't care about session errors. Log::debug(sprintf('Run time: %s', $e->getMessage())); } @@ -163,8 +163,8 @@ trait FormSupport $date = null; try { $date = today(config('app.timezone')); - } catch (Exception $e) { - $e->getMessage(); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException } return $date; diff --git a/app/Support/Form/PiggyBankForm.php b/app/Support/Form/PiggyBankForm.php index 21e11d31bc..068bfbcfca 100644 --- a/app/Support/Form/PiggyBankForm.php +++ b/app/Support/Form/PiggyBankForm.php @@ -37,9 +37,9 @@ class PiggyBankForm /** * TODO cleanup and describe. * - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ diff --git a/app/Support/Form/RuleForm.php b/app/Support/Form/RuleForm.php index d1f0748f7b..f90091c697 100644 --- a/app/Support/Form/RuleForm.php +++ b/app/Support/Form/RuleForm.php @@ -36,9 +36,9 @@ class RuleForm use FormSupport; /** - * @param string $name - * @param mixed $value - * @param array $options + * @param string $name + * @param mixed $value + * @param array|null $options * * @return string */ @@ -79,7 +79,7 @@ class RuleForm ]; /** @var RuleGroup $group */ foreach ($list as $group) { - if (isset($options['hidden']) && (int)$options['hidden'] !== $group->id) { + if (array_key_exists('hidden', $options) && (int)$options['hidden'] !== $group->id) { $array[$group->id] = $group->title; } } diff --git a/app/Support/Http/Controllers/AugumentData.php b/app/Support/Http/Controllers/AugumentData.php index e3d1a1adfc..19c28683a4 100644 --- a/app/Support/Http/Controllers/AugumentData.php +++ b/app/Support/Http/Controllers/AugumentData.php @@ -123,7 +123,7 @@ trait AugumentData foreach ($accountIds as $combinedId) { $parts = explode('-', $combinedId); $accountId = (int)$parts[0]; - if (isset($grouped[$accountId])) { + if (array_key_exists($accountId, $grouped)) { $return[$accountId] = $grouped[$accountId][0]['name']; } } @@ -147,7 +147,7 @@ trait AugumentData $grouped = $budgets->groupBy('id')->toArray(); $return = []; foreach ($budgetIds as $budgetId) { - if (isset($grouped[$budgetId])) { + if (array_key_exists($budgetId, $grouped)) { $return[$budgetId] = $grouped[$budgetId][0]['name']; } } @@ -173,7 +173,7 @@ trait AugumentData foreach ($categoryIds as $combinedId) { $parts = explode('-', $combinedId); $categoryId = (int)$parts[0]; - if (isset($grouped[$categoryId])) { + if (array_key_exists($categoryId, $grouped)) { $return[$categoryId] = $grouped[$categoryId][0]['name']; } } @@ -206,7 +206,7 @@ trait AugumentData $cache->addProperty('get-limits'); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $set = $blRepository->getBudgetLimits($budget, $start, $end); @@ -286,7 +286,7 @@ trait AugumentData $currencyId = (int)$journal['currency_id']; // if not set, set to zero: - if (!isset($sum['per_currency'][$currencyId])) { + if (!array_key_exists($currencyId, $sum['per_currency'])) { $sum['per_currency'][$currencyId] = [ 'sum' => '0', 'currency' => [ diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index 22f498f4bc..50415ca22c 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -57,7 +57,7 @@ trait ChartGeneration $cache->addProperty('chart.account.account-balance-chart'); $cache->addProperty($accounts); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } Log::debug('Regenerate chart.account.account-balance-chart from scratch.'); $locale = app('steam')->getLocale(); diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index 892218c9a0..28188f75ee 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -32,6 +32,7 @@ use Laravel\Passport\Passport; use Log; use phpseclib\Crypt\RSA as LegacyRSA; use phpseclib3\Crypt\RSA; + /** * Trait CreateStuff * @@ -54,7 +55,7 @@ trait CreateStuff $assetAccount = [ 'name' => $request->get('bank_name'), 'iban' => null, - 'account_type' => 'asset', + 'account_type_name' => 'asset', 'virtual_balance' => 0, 'account_type_id' => null, 'active' => true, @@ -84,7 +85,7 @@ trait CreateStuff $assetAccount = [ 'name' => (string)trans('firefly.cash_wallet', [], $language), 'iban' => null, - 'account_type' => 'asset', + 'account_type_name' => 'asset', 'virtual_balance' => 0, 'account_type_id' => null, 'active' => true, @@ -114,7 +115,7 @@ trait CreateStuff } // switch on class existence. - + $keys= []; Log::info(sprintf('PHP version is %s', phpversion())); if (class_exists(LegacyRSA::class)) { // PHP 7 @@ -128,11 +129,11 @@ trait CreateStuff $keys = RSA::createKey(4096); } - // @codeCoverageIgnoreStart + Log::alert('NO OAuth keys were found. They have been created.'); - file_put_contents($publicKey, array_get($keys, 'publickey')); - file_put_contents($privateKey, array_get($keys, 'privatekey')); + file_put_contents($publicKey, $keys['publickey']); + file_put_contents($privateKey, $keys['privatekey']); } /** @@ -151,7 +152,7 @@ trait CreateStuff $savingsAccount = [ 'name' => (string)trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), 'iban' => null, - 'account_type' => 'asset', + 'account_type_name' => 'asset', 'account_type_id' => null, 'virtual_balance' => 0, 'active' => true, diff --git a/app/Support/Http/Controllers/DateCalculation.php b/app/Support/Http/Controllers/DateCalculation.php index 0a70f06081..68d1ae743c 100644 --- a/app/Support/Http/Controllers/DateCalculation.php +++ b/app/Support/Http/Controllers/DateCalculation.php @@ -88,13 +88,13 @@ trait DateCalculation $step = '1D'; $months = $start->diffInMonths($end); if ($months > 3) { - $step = '1W'; // @codeCoverageIgnore + $step = '1W'; } if ($months > 24) { - $step = '1M'; // @codeCoverageIgnore + $step = '1M'; } if ($months > 100) { - $step = '1Y'; // @codeCoverageIgnore + $step = '1Y'; } return $step; diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index ca35c4de5c..7f6b16014c 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -57,15 +57,12 @@ trait ModelInformation 'count' => 1, ] )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); $result = 'Could not render view. See log files.'; } - // @codeCoverageIgnoreEnd - return [$result]; } @@ -149,13 +146,11 @@ trait ModelInformation 'triggers' => $triggers, ] )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); Log::debug($e->getTraceAsString()); $string = ''; - // @codeCoverageIgnoreEnd } if ('' !== $string) { $result[] = $string; @@ -189,9 +184,9 @@ trait ModelInformation $index = 0; // amount, description, category, budget, tags, source, destination, notes, currency type //,type - /** @var Transaction $source */ + /** @var Transaction|null $source */ $source = $journal->transactions()->where('amount', '<', 0)->first(); - /** @var Transaction $destination */ + /** @var Transaction|null $destination */ $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $destination || null === $source) { return $result; @@ -267,13 +262,11 @@ trait ModelInformation 'triggers' => $triggers, ] )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getTriggersForJournal(): %s', $e->getMessage())); Log::debug($e->getTraceAsString()); $string = ''; - // @codeCoverageIgnoreEnd } if ('' !== $string) { $result[] = $string; diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index cdf90716b7..374702dbf7 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -29,6 +29,7 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Category; use FireflyIII\Models\Tag; use FireflyIII\Models\TransactionType; +use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; use Log; @@ -63,15 +64,16 @@ use Log; */ trait PeriodOverview { + protected JournalRepositoryInterface $journalRepos; /** * This method returns "period entries", so nov-2015, dec-2015, etc etc (this depends on the users session range) * and for each period, the amount of money spent and earned. This is a complex operation which is cached for * performance reasons. * - * @param Account $account The account involved - * @param Carbon $date The start date. - * @param Carbon $end The end date. + * @param Account $account + * @param Carbon $start + * @param Carbon $end * * @return array */ @@ -87,7 +89,7 @@ trait PeriodOverview $cache->addProperty('account-show-period-entries'); $cache->addProperty($account->id); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var array $dates */ $dates = app('navigation')->blockPeriods($start, $end, $range); @@ -220,7 +222,7 @@ trait PeriodOverview foreach ($journals as $journal) { $currencyId = (int)$journal['currency_id']; $foreignCurrencyId = $journal['foreign_currency_id']; - if (!isset($return[$currencyId])) { + if (!array_key_exists($currencyId, $return)) { $return[$currencyId] = [ 'amount' => '0', 'count' => 0, @@ -235,7 +237,7 @@ trait PeriodOverview $return[$currencyId]['count']++; if (null !== $foreignCurrencyId && null !== $journal['foreign_amount']) { - if (!isset($return[$foreignCurrencyId])) { + if (!array_key_exists($foreignCurrencyId, $return)) { $return[$foreignCurrencyId] = [ 'amount' => '0', 'count' => 0, @@ -279,7 +281,7 @@ trait PeriodOverview $cache->addProperty($category->id); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var array $dates */ $dates = app('navigation')->blockPeriods($start, $end, $range); @@ -338,7 +340,7 @@ trait PeriodOverview * This method has been refactored recently. * * @param Carbon $start - * @param Carbon $date + * @param Carbon $end * * @return array */ @@ -354,7 +356,7 @@ trait PeriodOverview $cache->addProperty('no-budget-period-entries'); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var array $dates */ @@ -413,7 +415,7 @@ trait PeriodOverview $cache->addProperty('no-category-period-entries'); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $dates = app('navigation')->blockPeriods($start, $end, $range); @@ -469,10 +471,11 @@ trait PeriodOverview * This shows a period overview for a tag. It goes back in time and lists all relevant transactions and sums. * * @param Tag $tag - * - * @param Carbon $date + * @param Carbon $start + * @param Carbon $end * * @return array + * @throws \FireflyIII\Exceptions\FireflyException */ protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array // period overview for tags. { @@ -487,7 +490,7 @@ trait PeriodOverview $cache->addProperty('tag-period-entries'); $cache->addProperty($tag->id); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var array $dates */ $dates = app('navigation')->blockPeriods($start, $end, $range); @@ -542,9 +545,11 @@ trait PeriodOverview /** * @param string $transactionType - * @param Carbon $endDate + * @param Carbon $start + * @param Carbon $end * * @return array + * @throws \FireflyIII\Exceptions\FireflyException */ protected function getTransactionPeriodOverview(string $transactionType, Carbon $start, Carbon $end): array { @@ -559,7 +564,7 @@ trait PeriodOverview $cache->addProperty('transactions-period-entries'); $cache->addProperty($transactionType); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var array $dates */ $dates = app('navigation')->blockPeriods($start, $end, $range); diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index f726a488ab..9608927719 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -65,16 +65,13 @@ trait RenderPartialViews $account = $accountRepos->findNull((int)$attributes['accountId']); $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); - // @codeCoverageIgnoreStart + try { $view = prefixView('popup.report.balance-amount', compact('journals', 'budget', 'account'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; } - - // @codeCoverageIgnoreEnd - return $view; } @@ -88,16 +85,13 @@ trait RenderPartialViews /** @var BudgetRepositoryInterface $repository */ $repository = app(BudgetRepositoryInterface::class); $budgets = $repository->getBudgets(); - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.options.budget', compact('budgets'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) {// @phpstan-ignore-line Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return $result; } @@ -121,16 +115,13 @@ trait RenderPartialViews $budget = new Budget; } $journals = $popupHelper->byBudget($budget, $attributes); - // @codeCoverageIgnoreStart + try { $view = prefixView('popup.report.budget-spent-amount', compact('journals', 'budget'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; } - - // @codeCoverageIgnoreEnd - return $view; } @@ -153,7 +144,7 @@ trait RenderPartialViews try { $view = prefixView('popup.report.category-entry', compact('journals', 'category'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; } @@ -171,16 +162,13 @@ trait RenderPartialViews /** @var CategoryRepositoryInterface $repository */ $repository = app(CategoryRepositoryInterface::class); $categories = $repository->getCategories(); - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.options.category', compact('categories'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.options.category: %s', $e->getMessage())); $result = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return $result; } @@ -214,16 +202,13 @@ trait RenderPartialViews } } - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.options.double', compact('set'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return $result; } @@ -249,16 +234,13 @@ trait RenderPartialViews } $journals = $popupHelper->byExpenses($account, $attributes); - // @codeCoverageIgnoreStart + try { $view = prefixView('popup.report.expense-entry', compact('journals', 'account'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; } - - // @codeCoverageIgnoreEnd - return $view; } @@ -288,12 +270,12 @@ trait RenderPartialViews 'count' => $count, ] )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } - // @codeCoverageIgnoreEnd + ++$index; } @@ -339,12 +321,12 @@ trait RenderPartialViews 'triggers' => $triggers, ] )->render(); - // @codeCoverageIgnoreStart - } catch (Throwable $e) { + + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } - // @codeCoverageIgnoreEnd + ++$index; } } @@ -373,16 +355,13 @@ trait RenderPartialViews } $journals = $popupHelper->byIncome($account, $attributes); - // @codeCoverageIgnoreStart + try { $view = prefixView('popup.report.income-entry', compact('journals', 'account'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; } - - // @codeCoverageIgnoreEnd - return $view; } @@ -393,16 +372,13 @@ trait RenderPartialViews */ protected function noReportOptions(): string // render a view { - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.options.no-options')->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.options.no-options: %s', $e->getMessage())); $result = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return $result; } @@ -417,16 +393,13 @@ trait RenderPartialViews $repository = app(TagRepositoryInterface::class); $tags = $repository->get(); - // @codeCoverageIgnoreStart + try { $result = prefixView('reports.options.tag', compact('tags'))->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Cannot render reports.options.tag: %s', $e->getMessage())); $result = 'Could not render view.'; } - - // @codeCoverageIgnoreEnd - return $result; } } diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index e9159111f4..99ee491d86 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -48,7 +48,7 @@ trait RequestInformation * * @return string */ - protected function getDomain(): string // get request info + final protected function getDomain(): string // get request info { $url = url()->to('/'); $parts = parse_url($url); @@ -65,7 +65,7 @@ trait RequestInformation * @return string * */ - protected function getHelpText(string $route, string $language): string // get from internet. + final protected function getHelpText(string $route, string $language): string // get from internet. { $help = app(HelpInterface::class); // get language and default variables. @@ -113,13 +113,13 @@ trait RequestInformation return $content; } - return '
' . trans('firefly.route_has_no_help') . '
'; // @codeCoverageIgnore + return '' . trans('firefly.route_has_no_help') . '
'; } /** * @return string */ - protected function getPageName(): string // get request info + final protected function getPageName(): string // get request info { return str_replace('.', '_', RouteFacade::currentRouteName()); } @@ -129,7 +129,7 @@ trait RequestInformation * * @return string */ - protected function getSpecificPageName(): string // get request info + final protected function getSpecificPageName(): string // get request info { return null === RouteFacade::current()->parameter('objectType') ? '' : '_' . RouteFacade::current()->parameter('objectType'); } @@ -141,7 +141,7 @@ trait RequestInformation * * @return array */ - protected function getValidTriggerList(TestRuleFormRequest $request): array // process input + final protected function getValidTriggerList(TestRuleFormRequest $request): array // process input { $triggers = []; $data = $request->get('triggers'); @@ -163,7 +163,7 @@ trait RequestInformation * * @return bool */ - protected function hasSeenDemo(): bool // get request info + get preference + final protected function hasSeenDemo(): bool // get request info + get preference { $page = $this->getPageName(); $specificPage = $this->getSpecificPageName(); @@ -180,7 +180,7 @@ trait RequestInformation $shownDemo = app('preferences')->get($key, false)->data; } if (!is_bool($shownDemo)) { - $shownDemo = true; // @codeCoverageIgnore + $shownDemo = true; } return $shownDemo; @@ -194,7 +194,7 @@ trait RequestInformation * @return bool * */ - protected function notInSessionRange(Carbon $date): bool // Validate a preference + final protected function notInSessionRange(Carbon $date): bool // Validate a preference { /** @var Carbon $start */ $start = session('start', Carbon::now()->startOfMonth()); @@ -219,7 +219,7 @@ trait RequestInformation * * @return array */ - protected function parseAttributes(array $attributes): array // parse input + return result + final protected function parseAttributes(array $attributes): array // parse input + return result { $attributes['location'] = $attributes['location'] ?? ''; $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); @@ -253,7 +253,7 @@ trait RequestInformation * * @throws ValidationException */ - protected function validatePassword(User $user, string $current, string $new): bool //get request info + final protected function validatePassword(User $user, string $current, string $new): bool //get request info { if (!Hash::check($current, $user->password)) { throw new ValidationException((string)trans('firefly.invalid_current_password')); @@ -274,7 +274,7 @@ trait RequestInformation * @return ValidatorContract * @codeCoverageIgnore */ - protected function validator(array $data): ValidatorContract + final protected function validator(array $data): ValidatorContract { return Validator::make( $data, diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index 2ead11c60f..c9e2d6f4fd 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -108,7 +108,7 @@ trait RuleManagement 'count' => $index + 1, ] )->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } @@ -154,7 +154,7 @@ trait RuleManagement 'triggers' => $triggers, ] )->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } @@ -197,7 +197,7 @@ trait RuleManagement 'triggers' => $triggers, ] )->render(); - } catch (Throwable $e) { + } catch (Throwable $e) { // @phpstan-ignore-line Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index 5bf7c550cc..455e1b2c54 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -53,14 +53,14 @@ trait UserNavigation * * @return string */ - protected function getPreviousUri(string $identifier): string + final protected function getPreviousUri(string $identifier): string { Log::debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); $uri = (string)session($identifier); Log::debug(sprintf('The URI is %s', $uri)); if (false !== strpos($uri, 'jscript')) { - $uri = $this->redirectUri; // @codeCoverageIgnore + $uri = $this->redirectUri; Log::debug(sprintf('URI is now %s (uri contains jscript)', $uri)); } @@ -76,7 +76,7 @@ trait UserNavigation * * @return bool */ - protected function isEditableAccount(Account $account): bool + final protected function isEditableAccount(Account $account): bool { $editable = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]; $type = $account->accountType->type; @@ -89,9 +89,9 @@ trait UserNavigation * * @return bool */ - protected function isEditableGroup(TransactionGroup $group): bool + final protected function isEditableGroup(TransactionGroup $group): bool { - /** @var TransactionJournal $journal */ + /** @var TransactionJournal|null $journal */ $journal = $group->transactionJournals()->first(); if (null === $journal) { return false; @@ -107,13 +107,13 @@ trait UserNavigation * * @return RedirectResponse|Redirector */ - protected function redirectAccountToAccount(Account $account) + final protected function redirectAccountToAccount(Account $account) { $type = $account->accountType->type; if (AccountType::RECONCILIATION === $type || AccountType::INITIAL_BALANCE === $type) { // reconciliation must be stored somewhere in this account's transactions. - /** @var Transaction $transaction */ + /** @var Transaction|null $transaction */ $transaction = $account->transactions()->first(); if (null === $transaction) { Log::error(sprintf('Account #%d has no transactions. Dont know where it belongs.', $account->id)); @@ -122,7 +122,7 @@ trait UserNavigation return redirect(route('index')); } $journal = $transaction->transactionJournal; - /** @var Transaction $other */ + /** @var Transaction|null $other */ $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); if (null === $other) { Log::error(sprintf('Account #%d has no valid journals. Dont know where it belongs.', $account->id)); @@ -142,9 +142,9 @@ trait UserNavigation * * @return RedirectResponse|Redirector */ - protected function redirectGroupToAccount(TransactionGroup $group) + final protected function redirectGroupToAccount(TransactionGroup $group) { - /** @var TransactionJournal $journal */ + /** @var TransactionJournal|null $journal */ $journal = $group->transactionJournals()->first(); if (null === $journal) { Log::error(sprintf('No journals in group #%d', $group->id)); @@ -170,13 +170,13 @@ trait UserNavigation * * @return string|null */ - protected function rememberPreviousUri(string $identifier): ?string + final protected function rememberPreviousUri(string $identifier): ?string { $return = app('url')->previous(); - /** @var ViewErrorBag $errors */ + /** @var ViewErrorBag|null $errors */ $errors = session()->get('errors'); $forbidden = ['json', 'debug']; - if ((null === $errors || (null !== $errors && 0 === $errors->count())) && !Str::contains($return, $forbidden)) { + if ((null === $errors || (0 === $errors->count())) && !Str::contains($return, $forbidden)) { Log::debug(sprintf('Saving URL %s under key %s', $return, $identifier)); session()->put($identifier, $return); } diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 2f81cbcb4e..0322a5ed49 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -34,8 +34,8 @@ class Navigation { /** * @param \Carbon\Carbon $theDate - * @param $repeatFreq - * @param $skip + * @param string $repeatFreq + * @param int $skip * * @return \Carbon\Carbon */ @@ -71,12 +71,12 @@ class Navigation 'half-year' => 6, ]; - if (!isset($functionMap[$repeatFreq])) { + if (!array_key_exists($repeatFreq, $functionMap)) { Log::error(sprintf('Cannot do addPeriod for $repeat_freq "%s"', $repeatFreq)); return $theDate; } - if (isset($modifierMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $modifierMap)) { $add *= $modifierMap[$repeatFreq]; } $function = $functionMap[$repeatFreq]; @@ -156,12 +156,13 @@ class Navigation $loopCount++; } } + return $periods; } /** * @param \Carbon\Carbon $end - * @param $repeatFreq + * @param string $repeatFreq * * @return \Carbon\Carbon */ @@ -212,14 +213,14 @@ class Navigation return $currentEnd; } - if (!isset($functionMap[$repeatFreq])) { + if (!array_key_exists($repeatFreq, $functionMap)) { Log::error(sprintf('Cannot do endOfPeriod for $repeat_freq "%s"', $repeatFreq)); return $end; } $function = $functionMap[$repeatFreq]; - if (isset($modifierMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $modifierMap)) { $currentEnd->$function($modifierMap[$repeatFreq]); if (in_array($repeatFreq, $subDay, true)) { $currentEnd->subDay(); @@ -265,7 +266,7 @@ class Navigation $currentEnd = clone $theCurrentEnd; - if (isset($functionMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; $currentEnd->$function(); } @@ -338,7 +339,7 @@ class Navigation '6M' => (string)trans('config.half_year'), ]; - if (isset($formatMap[$repeatFrequency])) { + if (array_key_exists($repeatFrequency, $formatMap)) { return $date->formatLocalized((string)$formatMap[$repeatFrequency]); } if ('3M' === $repeatFrequency || 'quarter' === $repeatFrequency) { @@ -472,7 +473,7 @@ class Navigation /** * @param \Carbon\Carbon $theDate - * @param $repeatFreq + * @param string $repeatFreq * * @return \Carbon\Carbon */ @@ -496,7 +497,7 @@ class Navigation 'yearly' => 'startOfYear', '1Y' => 'startOfYear', ]; - if (isset($functionMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; $date->$function(); @@ -523,7 +524,7 @@ class Navigation /** * @param \Carbon\Carbon $theDate - * @param $repeatFreq + * @param string $repeatFreq * @param int $subtract * * @return \Carbon\Carbon @@ -555,13 +556,13 @@ class Navigation 'half-year' => 6, '6M' => 6, ]; - if (isset($functionMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; $date->$function($subtract); return $date; } - if (isset($modifierMap[$repeatFreq])) { + if (array_key_exists($repeatFreq, $modifierMap)) { $subtract *= $modifierMap[$repeatFreq]; $date->subMonths($subtract); @@ -577,6 +578,7 @@ class Navigation $tEnd = session('end', Carbon::now()->endOfMonth()); $diffInDays = $tStart->diffInDays($tEnd); $date->subDays($diffInDays * $subtract); + return $date; } @@ -584,7 +586,7 @@ class Navigation } /** - * @param $range + * @param string $range * @param \Carbon\Carbon $start * * @return \Carbon\Carbon @@ -602,7 +604,7 @@ class Navigation ]; $end = clone $start; - if (isset($functionMap[$range])) { + if (array_key_exists($range, $functionMap)) { $function = $functionMap[$range]; $end->$function(); @@ -630,7 +632,7 @@ class Navigation } /** - * @param $range + * @param string $range * @param \Carbon\Carbon $start * * @return \Carbon\Carbon @@ -646,7 +648,7 @@ class Navigation '3M' => 'firstOfQuarter', 'custom' => 'startOfMonth', // this only happens in test situations. ]; - if (isset($functionMap[$range])) { + if (array_key_exists($range, $functionMap)) { $function = $functionMap[$range]; $start->$function(); diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index 9d4b3d80fe..ae1f566064 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -386,7 +386,7 @@ class ParseDateString $direction = 0 === strpos($part, '+') ? 1 : 0; $period = $part[strlen($part) - 1]; $number = (int) substr($part, 1, -1); - if (!isset($functions[$direction][$period])) { + if (!array_key_exists($period, $functions[$direction])) { Log::error(sprintf('No method for direction %d and period "%s".', $direction, $period)); continue; } diff --git a/app/Support/Preferences.php b/app/Support/Preferences.php index 62bdbdefd7..f7d031f15a 100644 --- a/app/Support/Preferences.php +++ b/app/Support/Preferences.php @@ -24,6 +24,7 @@ namespace FireflyIII\Support; use Cache; use Exception; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Preference; use FireflyIII\User; use Illuminate\Support\Collection; @@ -49,9 +50,10 @@ class Preferences } /** - * @param $name + * @param string $name * * @return bool + * @throws FireflyException */ public function delete(string $name): bool { @@ -62,8 +64,7 @@ class Preferences try { Preference::where('user_id', auth()->user()->id)->where('name', $name)->delete(); } catch (Exception $e) { - Log::debug(sprintf('Could not delete preference: %s', $e->getMessage())); - // don't care. + throw new FireflyException(sprintf('Could not delete preference: %s', $e->getMessage()), 0, $e); } return true; @@ -87,7 +88,7 @@ class Preferences */ public function get(string $name, $default = null): ?Preference { - /** @var User $user */ + /** @var User|null $user */ $user = auth()->user(); if (null === $user) { $preference = new Preference; @@ -107,7 +108,7 @@ class Preferences */ public function getFresh(string $name, $default = null): ?Preference { - /** @var User $user */ + /** @var User|null $user */ $user = auth()->user(); if (null === $user) { $preference = new Preference; @@ -134,7 +135,7 @@ class Preferences $result[$preference->name] = $preference->data; } foreach ($list as $name) { - if (!isset($result[$name])) { + if (!array_key_exists($name, $result)) { $result[$name] = null; } } @@ -143,11 +144,12 @@ class Preferences } /** - * @param User $user - * @param string $name - * @param null|string $default + * @param User $user + * @param string $name + * @param null|string|int $default * * @return \FireflyIII\Models\Preference|null + * @throws FireflyException */ public function getForUser(User $user, string $name, $default = null): ?Preference { @@ -156,7 +158,7 @@ class Preferences try { $preference->delete(); } catch (Exception $e) { - Log::debug(sprintf('Could not delete preference #%d: %s', $preference->id, $e->getMessage())); + throw new FireflyException(sprintf('Could not delete preference #%d: %s', $preference->id, $e->getMessage()), 0, $e); } $preference = null; } @@ -252,19 +254,20 @@ class Preferences * @param mixed $value * * @return Preference + * @throws FireflyException */ public function setForUser(User $user, string $name, $value): Preference { $fullName = sprintf('preference%s%s', $user->id, $name); Cache::forget($fullName); - /** @var Preference $pref */ + /** @var Preference|null $pref */ $pref = Preference::where('user_id', $user->id)->where('name', $name)->first(['id', 'name', 'data', 'updated_at', 'created_at']); if (null !== $pref && null === $value) { try { $pref->delete(); } catch (Exception $e) { - Log::error(sprintf('Could not delete preference: %s', $e->getMessage())); + throw new FireflyException(sprintf('Could not delete preference: %s', $e->getMessage()), 0, $e); } return new Preference; @@ -272,20 +275,12 @@ class Preferences if (null === $value) { return new Preference; } - - if (null !== $pref) { - $pref->data = $value; - $pref->save(); - Cache::forever($fullName, $pref); - - return $pref; + if(null === $pref) { + $pref = new Preference; + $pref->user_id = $user->id; + $pref->name = $name; } - - $pref = new Preference; - $pref->name = $name; $pref->data = $value; - $pref->user()->associate($user); - $pref->save(); Cache::forever($fullName, $pref); diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php index 87da9c5c35..4f05f031e7 100644 --- a/app/Support/Request/AppendsLocationData.php +++ b/app/Support/Request/AppendsLocationData.php @@ -249,13 +249,4 @@ trait AppendsLocationData } - /** - * Abstract method to ensure filling later. - * - * @param string $field - * - * @return string|null - */ - abstract protected function nullableString(string $field): ?string; - } diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index 032dd4fbea..53f3cdfc3e 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Support\Request; use Carbon\Carbon; +use Carbon\Exceptions\InvalidFormatException; use Exception; use Log; @@ -32,6 +33,71 @@ use Log; */ trait ConvertsDataTypes { + /** + * @param string|null $string + * @param bool $keepNewlines + * + * @return string|null + */ + public function clearString(?string $string, bool $keepNewlines = true): ?string + { + if(null === $string) { + return null; + } + $search = [ + "\u{0001}", // start of heading + "\u{0002}", // start of text + "\u{0003}", // end of text + "\u{0004}", // end of transmission + "\u{0005}", // enquiry + "\u{0006}", // ACK + "\u{0007}", // BEL + "\u{0008}", // backspace + "\u{000E}", // shift out + "\u{000F}", // shift in + "\u{0010}", // data link escape + "\u{0011}", // DC1 + "\u{0012}", // DC2 + "\u{0013}", // DC3 + "\u{0014}", // DC4 + "\u{0015}", // NAK + "\u{0016}", // SYN + "\u{0017}", // ETB + "\u{0018}", // CAN + "\u{0019}", // EM + "\u{001A}", // SUB + "\u{001B}", // escape + "\u{001C}", // file separator + "\u{001D}", // group separator + "\u{001E}", // record separator + "\u{001F}", // unit separator + "\u{007F}", // DEL + "\u{00A0}", // non-breaking space + "\u{1680}", // ogham space mark + "\u{180E}", // mongolian vowel separator + "\u{2000}", // en quad + "\u{2001}", // em quad + "\u{2002}", // en space + "\u{2003}", // em space + "\u{2004}", // three-per-em space + "\u{2005}", // four-per-em space + "\u{2006}", // six-per-em space + "\u{2007}", // figure space + "\u{2008}", // punctuation space + "\u{2009}", // thin space + "\u{200A}", // hair space + "\u{200B}", // zero width space + "\u{202F}", // narrow no-break space + "\u{3000}", // ideographic space + "\u{FEFF}", // zero width no -break space + ]; + $replace = "\x20"; // plain old normal space + $string = str_replace($search, $replace, $string); + $secondSearch = $keepNewlines ? ["\r"] : ["\r", "\n", "\t", "\036", "\025"]; + $string = str_replace($secondSearch, '', $string); + + return trim($string); + } /** * Return integer value. @@ -45,18 +111,6 @@ trait ConvertsDataTypes return (int)$this->get($field); } - /** - * Return string value, but keep newlines. - * - * @param string $field - * - * @return string - */ - public function nlString(string $field): string - { - return app('steam')->nlCleanString((string)($this->get($field) ?? '')); - } - /** * Return string value. * @@ -66,11 +120,23 @@ trait ConvertsDataTypes */ public function string(string $field): string { - return app('steam')->cleanString((string)($this->get($field) ?? '')); + return $this->clearString((string)($this->get($field) ?? ''), false); } /** - * @param $array + * Return string value with newlines. + * + * @param string $field + * + * @return string + */ + public function stringWithNewlines(string $field): string + { + return $this->clearString((string)($this->get($field) ?? '')); + } + + /** + * @param mixed $array * * @return array|null */ @@ -108,15 +174,9 @@ trait ConvertsDataTypes if ('yes' === $value) { return true; } - if (1 === $value) { - return true; - } if ('1' === $value) { return true; } - if (true === $value) { - return true; - } return false; } @@ -133,8 +193,11 @@ trait ConvertsDataTypes $result = null; try { $result = $this->get($field) ? new Carbon($this->get($field)) : null; - } catch (Exception $e) { - Log::debug(sprintf('Exception when parsing date. Not interesting: %s', $e->getMessage())); + } catch (InvalidFormatException $e) { + // @ignoreException + } + if (null === $result) { + Log::debug(sprintf('Exception when parsing date "%s".', $this->get($field))); } return $result; @@ -153,10 +216,14 @@ trait ConvertsDataTypes if ('' === $string) { return null; } + $carbon = null; try { $carbon = new Carbon($string); - } catch (Exception $e) { - Log::debug(sprintf('Invalid date: %s: %s', $string, $e->getMessage())); + } catch (InvalidFormatException $e) { + // @ignoreException + } + if (null === $carbon) { + Log::debug(sprintf('Invalid date: %s', $string)); return null; } @@ -222,24 +289,6 @@ trait ConvertsDataTypes return (int)$string; } - /** - * Parse and clean a string, but keep the newlines. - * - * @param string|null $string - * - * @return string|null - */ - protected function nlStringFromValue(?string $string): ?string - { - if (null === $string) { - return null; - } - $result = app('steam')->nlCleanString($string); - - return '' === $result ? null : $result; - - } - /** * Return integer value, or NULL when it's not set. * @@ -261,56 +310,4 @@ trait ConvertsDataTypes return (int)$value; } - /** - * Return string value, but keep newlines, or NULL if empty. - * - * @param string $field - * - * @return string - */ - protected function nullableNlString(string $field): ?string - { - if (!$this->has($field)) { - return null; - } - - return app('steam')->nlCleanString((string)($this->get($field) ?? '')); - } - - /** - * Return string value, or NULL if empty. - * - * @param string $field - * - * @return string|null - */ - protected function nullableString(string $field): ?string - { - if (!$this->has($field)) { - return null; - } - $res = trim(app('steam')->cleanString((string)($this->get($field) ?? ''))); - if ('' === $res) { - return null; - } - - return $res; - } - - /** - * Parse and clean a string. - * - * @param string|null $string - * - * @return string|null - */ - protected function stringFromValue(?string $string): ?string - { - if (null === $string) { - return null; - } - $result = app('steam')->cleanString($string); - - return '' === $result ? null : $result; - } } diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index 52a41fa83f..b0792b2740 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -70,14 +70,14 @@ class OperatorQuerySearch implements SearchInterface private CurrencyRepositoryInterface $currencyRepository; private Carbon $date; private int $limit; -private Collection $modifiers; + private Collection $modifiers; private Collection $operators; private string $originalQuery; private int $page; private ParsedQuery $query; private float $startTime; private TagRepositoryInterface $tagRepository; - private TransactionTypeRepositoryInterface $typeRepository; // obsolete + private TransactionTypeRepositoryInterface $typeRepository; // obsolete private User $user; private array $validOperators; private array $words; @@ -179,7 +179,7 @@ private Collection $modifiers; public function searchTransactions(): LengthAwarePaginator { if (0 === count($this->getWords()) && 0 === count($this->getOperators())) { - return new LengthAwarePaginator; + return new LengthAwarePaginator([],0,5,1); } return $this->collector->getPaginatedGroups(); @@ -246,7 +246,7 @@ private Collection $modifiers; throw new FireflyException(sprintf('Firefly III search cant handle "%s"-nodes', $class)); case Subquery::class: // loop all notes in subquery: - foreach ($searchNode->getNodes() as $subNode) { + foreach ($searchNode->getNodes() as $subNode) { // @phpstan-ignore-line $this->handleSearchNode($subNode); // lets hope its not too recursive! } break; diff --git a/app/Support/Steam.php b/app/Support/Steam.php index f47cdb7f0c..063ea03783 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -56,7 +56,7 @@ class Steam $cache->addProperty($date); $cache->addProperty($currency ? $currency->id : 0); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); @@ -101,13 +101,13 @@ class Steam $cache->addProperty('balance-no-virtual'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); - $currencyId = (int)$repository->getMetaValue($account, 'currency_id'); + $currencyId = (int)$repository->getMetaValue($account, 'currency_id'); $transactions = $account->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) @@ -170,7 +170,7 @@ class Steam $cache->addProperty($start); $cache->addProperty($end); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $start->subDay(); @@ -179,8 +179,6 @@ class Steam $formatted = $start->format('Y-m-d'); $startBalance = $this->balance($account, $start, $currency); - /** @var AccountRepositoryInterface $repository */ - $balances[$formatted] = $startBalance; if (null === $currency) { $repository = app(AccountRepositoryInterface::class); @@ -202,7 +200,7 @@ class Steam ->orderBy('transaction_journals.date', 'ASC') ->whereNull('transaction_journals.deleted_at') ->get( - [ + [ // @phpstan-ignore-line 'transaction_journals.date', 'transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) AS modified'), @@ -252,13 +250,13 @@ class Steam $cache->addProperty('balance-per-currency'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } $query = $account->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->groupBy('transactions.transaction_currency_id'); - $balances = $query->get(['transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) as sum_for_currency')]); + $balances = $query->get(['transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) as sum_for_currency')]); // @phpstan-ignore-line $return = []; /** @var stdClass $entry */ foreach ($balances as $entry) { @@ -286,7 +284,7 @@ class Steam $cache->addProperty('balances'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // need to do this per account. @@ -318,7 +316,7 @@ class Steam $cache->addProperty('balances-per-currency'); $cache->addProperty($date); if ($cache->has()) { - return $cache->get(); // @codeCoverageIgnore + return $cache->get(); } // need to do this per account. @@ -333,136 +331,6 @@ class Steam return $result; } - /** - * Remove weird chars from strings. - * - * @param string $string - * TODO migrate to trait. - * - * @return string - * @deprecated - */ - public function cleanString(string $string): string - { - $search = [ - "\u{0001}", // start of heading - "\u{0002}", // start of text - "\u{0003}", // end of text - "\u{0004}", // end of transmission - "\u{0005}", // enquiry - "\u{0006}", // ACK - "\u{0007}", // BEL - "\u{0008}", // backspace - "\u{000E}", // shift out - "\u{000F}", // shift in - "\u{0010}", // data link escape - "\u{0011}", // DC1 - "\u{0012}", // DC2 - "\u{0013}", // DC3 - "\u{0014}", // DC4 - "\u{0015}", // NAK - "\u{0016}", // SYN - "\u{0017}", // ETB - "\u{0018}", // CAN - "\u{0019}", // EM - "\u{001A}", // SUB - "\u{001B}", // escape - "\u{001C}", // file separator - "\u{001D}", // group separator - "\u{001E}", // record separator - "\u{001F}", // unit separator - "\u{007F}", // DEL - "\u{00A0}", // non-breaking space - "\u{1680}", // ogham space mark - "\u{180E}", // mongolian vowel separator - "\u{2000}", // en quad - "\u{2001}", // em quad - "\u{2002}", // en space - "\u{2003}", // em space - "\u{2004}", // three-per-em space - "\u{2005}", // four-per-em space - "\u{2006}", // six-per-em space - "\u{2007}", // figure space - "\u{2008}", // punctuation space - "\u{2009}", // thin space - "\u{200A}", // hair space - "\u{200B}", // zero width space - "\u{202F}", // narrow no-break space - "\u{3000}", // ideographic space - "\u{FEFF}", // zero width no -break space - ]; - $replace = "\x20"; // plain old normal space - $string = str_replace($search, $replace, $string); - $string = str_replace(["\n", "\t", "\r"], "\x20", $string); - - return trim($string); - } - - /** - * Remove weird chars from strings, but keep newlines and tabs. - * - * @param string $string - * TODO migrate to trait. - * - * @return string - * @deprecated - */ - public function nlCleanString(string $string): string - { - $search = [ - "\u{0001}", // start of heading - "\u{0002}", // start of text - "\u{0003}", // end of text - "\u{0004}", // end of transmission - "\u{0005}", // enquiry - "\u{0006}", // ACK - "\u{0007}", // BEL - "\u{0008}", // backspace - "\u{000E}", // shift out - "\u{000F}", // shift in - "\u{0010}", // data link escape - "\u{0011}", // DC1 - "\u{0012}", // DC2 - "\u{0013}", // DC3 - "\u{0014}", // DC4 - "\u{0015}", // NAK - "\u{0016}", // SYN - "\u{0017}", // ETB - "\u{0018}", // CAN - "\u{0019}", // EM - "\u{001A}", // SUB - "\u{001B}", // escape - "\u{001C}", // file separator - "\u{001D}", // group separator - "\u{001E}", // record separator - "\u{001F}", // unit separator - "\u{007F}", // DEL - "\u{00A0}", // non-breaking space - "\u{1680}", // ogham space mark - "\u{180E}", // mongolian vowel separator - "\u{2000}", // en quad - "\u{2001}", // em quad - "\u{2002}", // en space - "\u{2003}", // em space - "\u{2004}", // three-per-em space - "\u{2005}", // four-per-em space - "\u{2006}", // six-per-em space - "\u{2007}", // figure space - "\u{2008}", // punctuation space - "\u{2009}", // thin space - "\u{200A}", // hair space - "\u{200B}", // zero width space - "\u{202F}", // narrow no-break space - "\u{3000}", // ideographic space - "\u{FEFF}", // zero width no -break space - ]; - $replace = "\x20"; // plain old normal space - $string = str_replace($search, $replace, $string); - $string = str_replace("\r", '', $string); - - return trim($string); - } - /** * @param array $accounts * @@ -475,7 +343,7 @@ class Steam $set = auth()->user()->transactions() ->whereIn('transactions.account_id', $accounts) ->groupBy(['transactions.account_id', 'transaction_journals.user_id']) - ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]); + ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]); // @phpstan-ignore-line foreach ($set as $entry) { $date = new Carbon($entry->max_date, 'UTC'); @@ -493,6 +361,9 @@ class Steam */ public function negative(string $amount): string { + if ('' === $amount) { + return '0'; + } if (1 === bccomp($amount, '0')) { $amount = bcmul($amount, '-1'); } @@ -554,6 +425,9 @@ class Steam */ public function positive(string $amount): string { + if ('' === $amount) { + return '0'; + } if (bccomp($amount, '0') === -1) { $amount = bcmul($amount, '-1'); } @@ -578,7 +452,6 @@ class Steam */ public function getLocale(): string // get preference { - /** @var string $language */ $locale = app('preferences')->get('locale', config('firefly.default_locale', 'equal'))->data; if ('equal' === $locale) { $locale = $this->getLanguage(); diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.php index 11303f80e0..80d1c17a19 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -93,8 +93,7 @@ class AmountFormat extends AbstractExtension * Will format the amount by the currency related to the given account. * * @return TwigFunction - * @deprecated - * TODO remove me because it executes a query in a view. + * TODO remove me when layout v1 is deprecated. */ protected function formatAmountByAccount(): TwigFunction { diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 58da41788b..32b346ef83 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -355,8 +355,7 @@ class General extends AbstractExtension /** * @return TwigFunction - * @deprecated because it uses a query in a view - * TODO remove me. + * TODO remove me once layout v1 is deprecated. */ protected function getMetaField(): TwigFunction { diff --git a/app/TransactionRules/Actions/ActionInterface.php b/app/TransactionRules/Actions/ActionInterface.php index 7da3388e85..0686714f3e 100644 --- a/app/TransactionRules/Actions/ActionInterface.php +++ b/app/TransactionRules/Actions/ActionInterface.php @@ -22,20 +22,11 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use FireflyIII\Models\RuleAction; - /** * Interface ActionInterface. */ interface ActionInterface { - /** - * ActionInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action); - /** * Execute the action on an array. Returns "true" if the action was a success and the action * was applied. Returns false if otherwise. diff --git a/app/TransactionRules/Actions/AddTag.php b/app/TransactionRules/Actions/AddTag.php index db64b8adfd..22b8345cef 100644 --- a/app/TransactionRules/Actions/AddTag.php +++ b/app/TransactionRules/Actions/AddTag.php @@ -55,14 +55,14 @@ class AddTag implements ActionInterface $factory = app(TagFactory::class); $factory->setUser(User::find($journal['user_id'])); $tag = $factory->findOrCreate($this->action->action_value); - // @codeCoverageIgnoreStart + if (null === $tag) { // could not find, could not create tag. Log::error(sprintf('RuleAction AddTag. Could not find or create tag "%s"', $this->action->action_value)); return false; } - // @codeCoverageIgnoreEnd + $count = DB::table('tag_transaction_journal') ->where('tag_id', $tag->id) ->where('transaction_journal_id', $journal['transaction_journal_id']) diff --git a/app/TransactionRules/Actions/ClearBudget.php b/app/TransactionRules/Actions/ClearBudget.php index ebf8e89f88..0890a7ff59 100644 --- a/app/TransactionRules/Actions/ClearBudget.php +++ b/app/TransactionRules/Actions/ClearBudget.php @@ -31,15 +31,6 @@ use Log; */ class ClearBudget implements ActionInterface { - /** - * TriggerInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action) - { - } - /** * @inheritDoc */ diff --git a/app/TransactionRules/Actions/ClearCategory.php b/app/TransactionRules/Actions/ClearCategory.php index 51133e39e4..4650c09196 100644 --- a/app/TransactionRules/Actions/ClearCategory.php +++ b/app/TransactionRules/Actions/ClearCategory.php @@ -31,15 +31,6 @@ use Log; */ class ClearCategory implements ActionInterface { - /** - * TriggerInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action) - { - } - /** * @inheritDoc */ diff --git a/app/TransactionRules/Actions/ClearNotes.php b/app/TransactionRules/Actions/ClearNotes.php index 54c55546a4..5e75226a11 100644 --- a/app/TransactionRules/Actions/ClearNotes.php +++ b/app/TransactionRules/Actions/ClearNotes.php @@ -32,15 +32,6 @@ use Log; */ class ClearNotes implements ActionInterface { - /** - * TriggerInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action) - { - } - /** * @inheritDoc */ diff --git a/app/TransactionRules/Actions/ConvertToDeposit.php b/app/TransactionRules/Actions/ConvertToDeposit.php index 6892c22783..70b78f862a 100644 --- a/app/TransactionRules/Actions/ConvertToDeposit.php +++ b/app/TransactionRules/Actions/ConvertToDeposit.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; + use DB; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\AccountFactory; @@ -148,7 +149,6 @@ class ConvertToDeposit implements ActionInterface $revenue = $factory->findOrCreate($revenueName, AccountType::REVENUE); Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $this->action->action_value, $journal['source_account_name'])); - unset($source); // update source transaction(s) to be revenue account DB::table('transactions') diff --git a/app/TransactionRules/Actions/ConvertToTransfer.php b/app/TransactionRules/Actions/ConvertToTransfer.php index 03350c696d..d13e00a083 100644 --- a/app/TransactionRules/Actions/ConvertToTransfer.php +++ b/app/TransactionRules/Actions/ConvertToTransfer.php @@ -22,11 +22,11 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; + use DB; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; use FireflyIII\Models\RuleAction; -use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; @@ -55,8 +55,8 @@ class ConvertToTransfer implements ActionInterface */ public function actOnArray(array $journal): bool { - $type = $journal['transaction_type_type']; - $user = User::find($journal['user_id']); + $type = $journal['transaction_type_type']; + $user = User::find($journal['user_id']); if (TransactionType::TRANSFER === $type) { Log::error( sprintf('Journal #%d is already a transfer so cannot be converted (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id) @@ -91,7 +91,7 @@ class ConvertToTransfer implements ActionInterface return $this->convertDepositArray($journal, $asset); } - return false; // @codeCoverageIgnore + return false; } /** diff --git a/app/TransactionRules/Actions/ConvertToWithdrawal.php b/app/TransactionRules/Actions/ConvertToWithdrawal.php index 1303ec642c..fa028db3f9 100644 --- a/app/TransactionRules/Actions/ConvertToWithdrawal.php +++ b/app/TransactionRules/Actions/ConvertToWithdrawal.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; + use DB; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\AccountFactory; @@ -72,7 +73,7 @@ class ConvertToWithdrawal implements ActionInterface return $this->convertTransferArray($journal); } - return false; // @codeCoverageIgnore + return false; } private function convertDepositArray(array $journal): bool diff --git a/app/TransactionRules/Actions/DeleteTransaction.php b/app/TransactionRules/Actions/DeleteTransaction.php index c372216f4f..a4108d0baf 100644 --- a/app/TransactionRules/Actions/DeleteTransaction.php +++ b/app/TransactionRules/Actions/DeleteTransaction.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Services\Internal\Destroy\JournalDestroyService; @@ -34,15 +33,6 @@ use Log; */ class DeleteTransaction implements ActionInterface { - /** - * TriggerInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action) - { - } - /** * @inheritDoc */ @@ -58,7 +48,7 @@ class DeleteTransaction implements ActionInterface $journal['transaction_journal_id'], $journal['description'] ) ); - $group = TransactionGroup::find($journal['transaction_group_id']); + $group = TransactionGroup::find($journal['transaction_group_id']); $service = app(TransactionGroupDestroyService::class); $service->destroy($group); diff --git a/app/TransactionRules/Actions/LinkToBill.php b/app/TransactionRules/Actions/LinkToBill.php index 8e8726b512..c813ef58eb 100644 --- a/app/TransactionRules/Actions/LinkToBill.php +++ b/app/TransactionRules/Actions/LinkToBill.php @@ -78,6 +78,7 @@ class LinkToBill implements ActionInterface $journal['transaction_journal_id'], $billName ) ); + return false; } } diff --git a/app/TransactionRules/Actions/RemoveAllTags.php b/app/TransactionRules/Actions/RemoveAllTags.php index f373786eec..f49ce6e34a 100644 --- a/app/TransactionRules/Actions/RemoveAllTags.php +++ b/app/TransactionRules/Actions/RemoveAllTags.php @@ -23,22 +23,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; use DB; -use FireflyIII\Models\RuleAction; use Log; + /** * Class RemoveAllTags. */ class RemoveAllTags implements ActionInterface { - /** - * TriggerInterface constructor. - * - * @param RuleAction $action - */ - public function __construct(RuleAction $action) - { - } - /** * @inheritDoc */ @@ -49,4 +40,5 @@ class RemoveAllTags implements ActionInterface return true; } + } diff --git a/app/TransactionRules/Actions/SetBudget.php b/app/TransactionRules/Actions/SetBudget.php index 73d032004d..2e149065dd 100644 --- a/app/TransactionRules/Actions/SetBudget.php +++ b/app/TransactionRules/Actions/SetBudget.php @@ -50,7 +50,7 @@ class SetBudget implements ActionInterface */ public function actOnArray(array $journal): bool { - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); $search = $this->action->action_value; $budget = $user->budgets()->where('name', $search)->first(); diff --git a/app/TransactionRules/Actions/SetCategory.php b/app/TransactionRules/Actions/SetCategory.php index 4b2f5a6d1e..118d5186b7 100644 --- a/app/TransactionRules/Actions/SetCategory.php +++ b/app/TransactionRules/Actions/SetCategory.php @@ -50,7 +50,7 @@ class SetCategory implements ActionInterface */ public function actOnArray(array $journal): bool { - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); $search = $this->action->action_value; if (null === $user) { Log::error(sprintf('Journal has no valid user ID so action SetCategory("%s") cannot be applied', $search), $journal); diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index 931362a0bb..c530568177 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -26,6 +26,9 @@ use DB; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; use FireflyIII\Models\RuleAction; +use FireflyIII\Models\Transaction; +use FireflyIII\Models\TransactionJournal; +use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Log; @@ -55,79 +58,104 @@ class SetDestinationAccount implements ActionInterface { $user = User::find($journal['user_id']); $type = $journal['transaction_type_type']; + /** @var TransactionJournal|null $object */ + $object = $user->transactionJournals()->find((int)$journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); + + if (null === $object) { + Log::error('Could not find journal.'); + + return false; + } + $this->repository->setUser($user); - // it depends on the type what kind of destination account is expected. - $expectedTypes = config(sprintf('firefly.source_dests.%s.%s', $type, $journal['source_account_type'])); - if (null === $expectedTypes) { + // 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); + if ((TransactionType::DEPOSIT === $type || TransactionType::TRANSFER === $type) && null === $newAccount) { Log::error( sprintf( - 'Configuration line "%s" is unexpectedly empty. Stopped.', sprintf('firefly.source_dests.%s.%s', $type, $journal['source_account_type']) + 'Cant change destination account of journal #%d because no asset account with name "%s" exists.', $object->id, $this->action->action_value ) ); return false; } - // try to find an account with the destination name and these types: - $destination = $this->findAccount($expectedTypes); - if (null !== $destination) { - // update account of destination transaction. - DB::table('transactions') - ->where('transaction_journal_id', '=', $journal['transaction_journal_id']) - ->where('amount', '>', 0) - ->update(['account_id' => $destination->id]); - Log::debug(sprintf('Updated journal #%d and gave it new account ID.', $journal['transaction_journal_id'])); - return true; + // new destination account must be different from the current source account: + /** @var Transaction|null $source */ + $source = $object->transactions()->where('amount', '<', 0)->first(); + if (null === $source) { + Log::error('Could not find source transaction.'); + + return false; } - Log::info(sprintf('Expected destination account "%s" not found.', $this->action->action_value)); + // account must not be deleted (in the mean time): + if (null === $source->account) { + Log::error('Could not find source transaction account.'); - if (in_array(AccountType::EXPENSE, $expectedTypes)) { - // does not exist, but can be created. - Log::debug('Expected type is expense, lets create it.'); - $expense = $this->findExpenseAccount(); - if (null === $expense) { - Log::error('Could not create expense account.'); + return false; + } + if (null !== $newAccount && (int)$newAccount->id === (int)$source->account_id) { + Log::error( + sprintf( + 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $newAccount->id, + $source->account_id + ) + ); - return false; - } - DB::table('transactions') - ->where('transaction_journal_id', '=', $journal['transaction_journal_id']) - ->where('amount', '>', 0) - ->update(['account_id' => $expense->id]); - Log::debug(sprintf('Updated journal #%d and gave it new account ID.', $journal['transaction_journal_id'])); - - return true; + return false; } - return false; + // if this is a withdrawal, the new destination account must be a expense account and may be created: + if (TransactionType::WITHDRAWAL === $type) { + $newAccount = $this->findExpenseAccount(); + } + + Log::debug(sprintf('New destination account is #%d ("%s").', $newAccount->id, $newAccount->name)); + + // update destination transaction with new destination account: + DB::table('transactions') + ->where('transaction_journal_id', '=', $object->id) + ->where('amount', '>', 0) + ->update(['account_id' => $newAccount->id]); + + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); + + return true; + + } /** - * @param array $types + * @param string $type * * @return Account|null */ - private function findAccount(array $types): ?Account + private function findAssetAccount(string $type): ?Account { - return $this->repository->findByName($this->action->action_value, $types); + // switch on type: + $allowed = config(sprintf('firefly.expected_source_types.destination.%s', $type)); + $allowed = is_array($allowed) ? $allowed : []; + Log::debug(sprintf('Check config for expected_source_types.destination.%s, result is', $type), $allowed); + + return $this->repository->findByName($this->action->action_value, $allowed); } /** - * @return Account|null + * @return Account */ - private function findExpenseAccount(): ?Account + private function findExpenseAccount(): Account { $account = $this->repository->findByName($this->action->action_value, [AccountType::EXPENSE]); if (null === $account) { $data = [ - 'name' => $this->action->action_value, - 'account_type' => 'expense', - 'account_type_id' => null, - 'virtual_balance' => 0, - 'active' => true, - 'iban' => null, + 'name' => $this->action->action_value, + 'account_type_name' => 'expense', + 'account_type_id' => null, + 'virtual_balance' => 0, + 'active' => true, + 'iban' => null, ]; $account = $this->repository->store($data); } @@ -135,4 +163,6 @@ class SetDestinationAccount implements ActionInterface return $account; } + + } diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index c8711b4e12..6c1f709c1d 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -55,63 +55,69 @@ class SetSourceAccount implements ActionInterface */ public function actOnArray(array $journal): bool { - $user = User::find($journal['user_id']); - $type = $journal['transaction_type_type']; - /** @var TransactionJournal $journal */ - $journal = TransactionJournal::find((int)$journal['transaction_journal_id']); - /** @var AccountRepositoryInterface repository */ + $user = User::find($journal['user_id']); + $type = $journal['transaction_type_type']; + /** @var TransactionJournal|null $object */ + $object = $user->transactionJournals()->find((int)$journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); + + if (null === $object) { + Log::error('Could not find journal.'); + + return false; + } + $this->repository->setUser($user); // if this is a transfer or a withdrawal, the new source account must be an asset account or a default account, and it MUST exist: $newAccount = $this->findAssetAccount($type); if ((TransactionType::WITHDRAWAL === $type || TransactionType::TRANSFER === $type) && null === $newAccount) { Log::error( - sprintf( - 'Cannot change source account of journal #%d because no asset account with name "%s" exists.', $journal['transaction_journal_id'], - $this->action->action_value - ) + sprintf('Cant change source account of journal #%d because no asset account with name "%s" exists.', $object->id, $this->action->action_value) ); return false; } - // new source account must be different from the current destination: - $destinationId = (int)$journal['destination_account_id']; - /** @var Transaction $source */ - $source = $journal->transactions()->where('amount', '>', 0)->first(); - if (null !== $source) { - $destinationId = $source->account ? (int)$source->account->id : $destinationId; + + // new source account must be different from the current destination account: + /** @var Transaction|null $destination */ + $destination = $object->transactions()->where('amount', '>', 0)->first(); + if (null === $destination) { + Log::error('Could not find destination transaction.'); + + return false; } - if (TransactionType::TRANSFER === $type && null !== $newAccount && (int)$newAccount->id === $destinationId) { + // account must not be deleted (in the mean time): + if (null === $destination->account) { + Log::error('Could not find destination transaction account.'); + + return false; + } + if (null !== $newAccount && (int)$newAccount->id === (int)$destination->account_id) { Log::error( sprintf( 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', $newAccount->id, - $destinationId + $destination->account_id ) ); return false; } + // if this is a deposit, the new source account must be a revenue account and may be created: if (TransactionType::DEPOSIT === $type) { $newAccount = $this->findRevenueAccount(); } - if (null === $newAccount) { - Log::error('New account is NULL'); - - return false; - } Log::debug(sprintf('New source account is #%d ("%s").', $newAccount->id, $newAccount->name)); // update source transaction with new source account: - // get source transaction: DB::table('transactions') - ->where('transaction_journal_id', '=', $journal['transaction_journal_id']) + ->where('transaction_journal_id', '=', $object->id) ->where('amount', '<', 0) ->update(['account_id' => $newAccount->id]); - Log::debug(sprintf('Updated journal #%d and gave it new source account ID.', $journal['transaction_journal_id'])); + Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); return true; } @@ -132,21 +138,21 @@ class SetSourceAccount implements ActionInterface } /** - * @return Account|null + * @return Account */ - private function findRevenueAccount(): ?Account + private function findRevenueAccount(): Account { $allowed = config('firefly.expected_source_types.source.Deposit'); $account = $this->repository->findByName($this->action->action_value, $allowed); if (null === $account) { // create new revenue account with this name: $data = [ - 'name' => $this->action->action_value, - 'account_type' => 'revenue', - 'account_type_id' => null, - 'virtual_balance' => 0, - 'active' => true, - 'iban' => null, + 'name' => $this->action->action_value, + 'account_type_name' => 'revenue', + 'account_type_id' => null, + 'virtual_balance' => 0, + 'active' => true, + 'iban' => null, ]; $account = $this->repository->store($data); } diff --git a/app/TransactionRules/Actions/UpdatePiggybank.php b/app/TransactionRules/Actions/UpdatePiggybank.php index 84fa7917ea..121da9fd18 100644 --- a/app/TransactionRules/Actions/UpdatePiggybank.php +++ b/app/TransactionRules/Actions/UpdatePiggybank.php @@ -21,7 +21,9 @@ */ declare(strict_types=1); + namespace FireflyIII\TransactionRules\Actions; + use FireflyIII\Models\PiggyBank; use FireflyIII\Models\RuleAction; use FireflyIII\Models\Transaction; diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php index 0105e3a48b..e9c8df73bd 100644 --- a/app/TransactionRules/Engine/SearchRuleEngine.php +++ b/app/TransactionRules/Engine/SearchRuleEngine.php @@ -390,7 +390,7 @@ class SearchRuleEngine implements RuleEngineInterface $result = $actionClass->actOnArray($transaction); $journalId = $transaction['transaction_journal_id'] ?? 0; if (true === $result) { - $this->resultCount[$journalId] = isset($this->resultCount[$journalId]) ? $this->resultCount[$journalId]++ : 1; + $this->resultCount[$journalId] = array_key_exists($journalId, $this->resultCount) ? $this->resultCount[$journalId]++ : 1; Log::debug( sprintf( 'Action "%s" on journal #%d was executed, so count a result. Updated transaction journal count is now %d.', @@ -514,7 +514,7 @@ class SearchRuleEngine implements RuleEngineInterface { $all = false; Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $group->rules->count())); - /** @var $rule */ + /** @var Rule $rule */ foreach ($group->rules as $rule) { Log::debug(sprintf('Going to fire rule #%d from group #%d', $rule->id, $group->id)); $result = $this->fireRule($rule); diff --git a/app/Transformers/AbstractTransformer.php b/app/Transformers/AbstractTransformer.php index fe4e8ec761..1e76cf7ac1 100644 --- a/app/Transformers/AbstractTransformer.php +++ b/app/Transformers/AbstractTransformer.php @@ -37,7 +37,7 @@ abstract class AbstractTransformer extends TransformerAbstract /** * @return ParameterBag */ - public function getParameters(): ParameterBag + final public function getParameters(): ParameterBag { return $this->parameters; } @@ -45,7 +45,7 @@ abstract class AbstractTransformer extends TransformerAbstract /** * @param ParameterBag $parameters */ - public function setParameters(ParameterBag $parameters): void + final public function setParameters(ParameterBag $parameters): void { $this->parameters = $parameters; } diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index ad450c9ec1..97cccf7953 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -206,8 +206,6 @@ class AccountTransformer extends AbstractTransformer * @param Account $account * @param string $accountType * - * @param int $decimalPlaces - * * @return array * * TODO refactor call to getOpeningBalanceAmount / Date because its extra queries. diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index a85e0e2da6..9ed54128b1 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -22,11 +22,11 @@ declare(strict_types=1); namespace FireflyIII\Transformers; + use FireflyIII\Models\AvailableBudget; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; -use Illuminate\Support\Collection; /** * Class AvailableBudgetTransformer @@ -97,11 +97,9 @@ class AvailableBudgetTransformer extends AbstractTransformer private function getSpentInBudgets(): array { $allActive = $this->repository->getActiveBudgets(); + $sums = $this->opsRepository->sumExpenses($this->parameters->get('start'), $this->parameters->get('end'), null, $allActive); - return $this->opsRepository->spentInPeriodMc( - $allActive, new Collection, $this->parameters->get('start'), $this->parameters->get('end') - ); - + return array_values($sums); } /** @@ -109,7 +107,8 @@ class AvailableBudgetTransformer extends AbstractTransformer */ private function spentOutsideBudgets(): array { - return $this->noBudgetRepository->spentInPeriodWoBudgetMc(new Collection, $this->parameters->get('start'), $this->parameters->get('end')); - } + $sums = $this->noBudgetRepository->sumExpenses($this->parameters->get('start'), $this->parameters->get('end')); + return array_values($sums); + } } diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index 61fa145cd9..300dab679b 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -209,10 +209,10 @@ class BillTransformer extends AbstractTransformer protected function lastPaidDate(Collection $dates, Carbon $default): Carbon { if (0 === $dates->count()) { - return $default; // @codeCoverageIgnore + return $default; } $latest = $dates->first()->date; - /** @var TransactionJournal $date */ + /** @var TransactionJournal $journal */ foreach ($dates as $journal) { if ($journal->date->gte($latest)) { $latest = $journal->date; diff --git a/app/Transformers/CurrencyExchangeRateTransformer.php b/app/Transformers/CurrencyExchangeRateTransformer.php deleted file mode 100644 index 2f4f72796a..0000000000 --- a/app/Transformers/CurrencyExchangeRateTransformer.php +++ /dev/null @@ -1,67 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers; -use FireflyIII\Models\CurrencyExchangeRate; - -/** - * Class CurrencyExchangeRateTransformer - */ -class CurrencyExchangeRateTransformer extends AbstractTransformer -{ - /** - * @param CurrencyExchangeRate $rate - * - * @return array - */ - public function transform(CurrencyExchangeRate $rate): array - { - $result = number_format((float)$rate->rate * (float)$this->parameters->get('amount'), $rate->toCurrency->decimal_places, '.', ''); - $result = 0.0 === $result ? null : $result; - - return [ - 'id' => (int)$rate->id, - 'created_at' => $rate->created_at->toAtomString(), - 'updated_at' => $rate->updated_at->toAtomString(), - 'from_currency_id' => (int)$rate->fromCurrency->id, - 'from_currency_name' => $rate->fromCurrency->name, - 'from_currency_code' => $rate->fromCurrency->code, - 'from_currency_symbol' => $rate->fromCurrency->symbol, - 'from_currency_decimal_places' => (int)$rate->fromCurrency->decimal_places, - 'to_currency_id' => (int)$rate->toCurrency->id, - 'to_currency_name' => $rate->toCurrency->name, - 'to_currency_code' => $rate->toCurrency->code, - 'to_currency_symbol' => $rate->toCurrency->symbol, - 'to_currency_decimal_places' => (int)$rate->toCurrency->decimal_places, - 'date' => $rate->date->format('Y-m-d'), - 'rate' => (float)$rate->rate, - 'amount' => $result, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/currency_exchange_rates/' . $rate->id, - ], - ], - ]; - } -} diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index ae69d7de8b..945d97c011 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -276,7 +276,6 @@ class RecurrenceTransformer extends AbstractTransformer $array['category_name'] = $category->name; } break; - break; case 'category_name': $category = $this->factory->findOrCreate(null, $transactionMeta->value); if (null !== $category) { diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index 2c74cfda85..2429718425 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -304,7 +304,7 @@ class TransactionGroupTransformer extends AbstractTransformer } catch (FireflyException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException(sprintf('Transaction group #%d is broken. Please check out your log files.', $group->id)); + throw new FireflyException(sprintf('Transaction group #%d is broken. Please check out your log files.', $group->id), 0, $e); } // do something else. diff --git a/app/User.php b/app/User.php index 91b37f202d..bfb66bb0b0 100644 --- a/app/User.php +++ b/app/User.php @@ -67,17 +67,14 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * * @property int $id * @property string $email - * @property bool $isAdmin used in admin user - * controller. - * @property bool $has2FA used in admin user - * controller. - * @property array $prefs used in admin user - * controller. - * @property string password + * @property bool $isAdmin + * @property bool $has2FA + * @property array $prefs + * @property string $password * @property string $mfa_secret - * @property Collection roles - * @property string blocked_code - * @property bool blocked + * @property Collection $roles + * @property string $blocked_code + * @property bool $blocked * @property Carbon|null $created_at * @property Carbon|null $updated_at * @property string|null $remember_token diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php index c9661a2c33..9f3c57e3aa 100644 --- a/app/Validation/Account/DepositValidation.php +++ b/app/Validation/Account/DepositValidation.php @@ -34,7 +34,7 @@ trait DepositValidation { /** * @param int|null $accountId - * @param $accountName + * @param mixed $accountName * * @return bool */ diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php index 3efabe83cc..c2bcf617da 100644 --- a/app/Validation/Account/OBValidation.php +++ b/app/Validation/Account/OBValidation.php @@ -35,7 +35,7 @@ trait OBValidation { /** * @param int|null $accountId - * @param $accountName + * @param mixed $accountName * * @return bool */ diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php index 44459963aa..70554a6f1c 100644 --- a/app/Validation/Account/TransferValidation.php +++ b/app/Validation/Account/TransferValidation.php @@ -33,7 +33,7 @@ trait TransferValidation { /** * @param int|null $accountId - * @param $accountName + * @param mixed $accountName * * @return bool */ diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index f70d860706..d98e4d5247 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -58,14 +58,12 @@ class AccountValidator */ public function __construct() { - $this->createMode = false; - $this->destError = 'No error yet.'; - $this->sourceError = 'No error yet.'; - $this->combinations = config('firefly.source_dests'); - $this->source = null; - $this->destination = null; - - /** @var AccountRepositoryInterface accountRepository */ + $this->createMode = false; + $this->destError = 'No error yet.'; + $this->sourceError = 'No error yet.'; + $this->combinations = config('firefly.source_dests'); + $this->source = null; + $this->destination = null; $this->accountRepository = app(AccountRepositoryInterface::class); } diff --git a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php index a9c844a115..606bd9bacf 100644 --- a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php +++ b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php @@ -57,7 +57,7 @@ trait ValidatesAutoBudgetRequest if ('' === $period) { $validator->errors()->add('auto_budget_period', (string)trans('validation.auto_budget_period_mandatory')); } - if (null !== $amount && null !== $currencyId && null !== $currencyCode && '' === $currencyCode && '' === $currencyId) { + if (null !== $amount && null !== $currencyId && null !== $currencyCode && '' === $currencyCode && 0 === $currencyId) { $validator->errors()->add('auto_budget_amount', (string)trans('validation.require_currency_info')); } } diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php index b92d9cb3f6..0c48b2a5a2 100644 --- a/app/Validation/CurrencyValidation.php +++ b/app/Validation/CurrencyValidation.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Validation; + use Illuminate\Validation\Validator; use Log; @@ -45,7 +46,11 @@ trait CurrencyValidation foreach ($transactions as $index => $transaction) { // if foreign amount is present, then the currency must be as well. - if (isset($transaction['foreign_amount']) && !(isset($transaction['foreign_currency_id']) || isset($transaction['foreign_currency_code'])) + if (array_key_exists('foreign_amount', $transaction) + && !(array_key_exists('foreign_currency_id', $transaction) + || array_key_exists( + 'foreign_currency_code', $transaction + )) && 0 !== bccomp('0', $transaction['foreign_amount']) ) { $validator->errors()->add( @@ -54,7 +59,10 @@ trait CurrencyValidation ); } // if the currency is present, then the amount must be present as well. - if ((isset($transaction['foreign_currency_id']) || isset($transaction['foreign_currency_code'])) && !isset($transaction['foreign_amount'])) { + if ((array_key_exists('foreign_currency_id', $transaction) || array_key_exists('foreign_currency_code', $transaction)) + && !array_key_exists( + 'foreign_amount', $transaction + )) { $validator->errors()->add( 'transactions.' . $index . '.foreign_amount', (string)trans('validation.require_currency_amount') diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index 8aef97bcec..db4523952a 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -52,14 +52,14 @@ use function is_string; class FireflyValidator extends Validator { /** - * @param $attribute - * @param $value + * @param mixed $attribute + * @param mixed $value * * @return bool */ public function validate2faCode($attribute, $value): bool { - if (!is_string($value) || null === $value || 6 !== strlen($value)) { + if (null === $value || !is_string($value) || 6 !== strlen($value)) { return false; } @@ -69,9 +69,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -88,8 +88,8 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value + * @param mixed $attribute + * @param mixed $value * * @return bool */ @@ -108,14 +108,14 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value + * @param mixed $attribute + * @param mixed $value * * @return bool */ public function validateIban($attribute, $value): bool { - if (!is_string($value) || null === $value || strlen($value) < 6) { + if (null === $value || !is_string($value) || strlen($value) < 6) { return false; } // strip spaces @@ -186,9 +186,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -201,9 +201,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -216,9 +216,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -235,9 +235,9 @@ class FireflyValidator extends Validator } /** - * @param string $attribute + * @param string $attribute * - * @param string $value + * @param string|null $value * * @return bool */ @@ -309,8 +309,8 @@ class FireflyValidator extends Validator /** * $attribute has the format triggers.%d.value. * - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string|null $value * * @return bool */ @@ -375,15 +375,15 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value + * @param mixed $attribute + * @param mixed $value * * @return bool */ public function validateSecurePassword($attribute, $value): bool { $verify = false; - if (isset($this->data['verify_password'])) { + if (array_key_exists('verify_password', $this->data)) { $verify = 1 === (int)$this->data['verify_password']; } if ($verify) { @@ -397,9 +397,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -410,21 +410,20 @@ class FireflyValidator extends Validator if (!auth()->check()) { return $this->validateAccountAnonymously(); } - if (isset($this->data['objectType'])) { - + if (array_key_exists('objectType', $this->data)) { return $this->validateByAccountTypeString($value, $parameters, $this->data['objectType']); } - if (isset($this->data['type'])) { + if (array_key_exists('type', $this->data)) { return $this->validateByAccountTypeString($value, $parameters, $this->data['type']); } - if (isset($this->data['account_type_id'])) { + if (array_key_exists('account_type_id', $this->data)) { return $this->validateByAccountTypeId($value, $parameters); } $parameterId = $parameters[0] ?? null; if (null !== $parameterId) { return $this->validateByParameterId((int)$parameterId, $value); } - if (isset($this->data['id'])) { + if (array_key_exists('id', $this->data)) { return $this->validateByAccountId($value); } @@ -437,7 +436,7 @@ class FireflyValidator extends Validator */ private function validateAccountAnonymously(): bool { - if (!isset($this->data['user_id'])) { + if (!array_key_exists('user_id',$this->data)) { return false; } @@ -466,7 +465,7 @@ class FireflyValidator extends Validator */ private function validateByAccountTypeString(string $value, array $parameters, string $type): bool { - /** @var array $search */ + /** @var array|null $search */ $search = Config::get('firefly.accountTypeByIdentifier.' . $type); if (null === $search) { @@ -491,8 +490,8 @@ class FireflyValidator extends Validator } /** - * @param $value - * @param $parameters + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -516,7 +515,8 @@ class FireflyValidator extends Validator } /** - * @param $value + * @param int $accountId + * @param mixed $value * * @return bool */ @@ -528,7 +528,6 @@ class FireflyValidator extends Validator $type = $existingAccount->accountType; $ignore = $existingAccount->id; - /** @var Collection $set */ $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore) ->where('name', $value) ->first(); @@ -537,7 +536,7 @@ class FireflyValidator extends Validator } /** - * @param $value + * @param mixed $value * * @return bool */ @@ -549,7 +548,6 @@ class FireflyValidator extends Validator $type = $existingAccount->accountType; $ignore = $existingAccount->id; - /** @var Collection $set */ $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore) ->where('name', $value) ->first(); @@ -568,9 +566,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -602,6 +600,13 @@ class FireflyValidator extends Validator return true; } + /** + * @param mixed $value + * @param mixed $parameters + * @param mixed $something + * + * @return bool + */ public function validateUniqueExistingWebhook($value, $parameters, $something): bool { $existingId = (int)($something[0] ?? 0); @@ -614,7 +619,7 @@ class FireflyValidator extends Validator if (auth()->check()) { // get existing webhook value: if (0 !== $existingId) { - /** @var Webhook $webhook */ + /** @var Webhook|null $webhook */ $webhook = auth()->user()->webhooks()->find($existingId); if (null === $webhook) { return false; @@ -645,15 +650,15 @@ class FireflyValidator extends Validator /** * - * Validate an object and its unicity. Checks for encryption / encrypted values as well. + * Validate an object and its uniqueness. Checks for encryption / encrypted values as well. * * parameter 0: the table * parameter 1: the field * parameter 2: an id to ignore (when editing) * - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -667,7 +672,7 @@ class FireflyValidator extends Validator * ID field, set that field to be the $exclude. */ $data = $this->getData(); - if (!isset($parameters[2]) && isset($data['id']) && (int)$data['id'] > 0) { + if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int)$data['id'] > 0) { $exclude = (int)$data['id']; } // get entries from table @@ -686,9 +691,9 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * * @return bool */ @@ -707,11 +712,11 @@ class FireflyValidator extends Validator } /** - * @param $attribute - * @param $value - * @param $parameters + * @param mixed $attribute + * @param mixed $value + * @param mixed $parameters * - * TODO this method does not need a for loop + * TODO this method does not need a for loop * * @return bool */ @@ -738,8 +743,8 @@ class FireflyValidator extends Validator } /** - * @param $value - * @param $parameters + * @param mixed $value + * @param mixed $parameters * * @return bool */ diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php index 2e8043eb55..a8dac63d20 100644 --- a/app/Validation/GroupValidation.php +++ b/app/Validation/GroupValidation.php @@ -123,12 +123,19 @@ trait GroupValidation */ private function validateJournalId(Validator $validator, int $index, array $transaction, TransactionGroup $transactionGroup): void { - $journalId = $transaction['transaction_journal_id'] ?? null; + $journalId = 0; + if (array_key_exists('transaction_journal_id', $transaction)) { + $journalId = $transaction['transaction_journal_id']; + } Log::debug(sprintf('Now in validateJournalId(%d, %d)', $index, $journalId)); + if (0 === $journalId) { + Log::debug('Submitted 0, will accept to be used in a new transaction.'); - $journalId = null === $journalId ? null : (int)$journalId; - $count = $transactionGroup->transactionJournals()->where('id', $journalId)->count(); - if (null === $journalId || (null !== $journalId && 0 !== $journalId && 0 === $count)) { + return; + } + $count = $transactionGroup->transactionJournals()->where('transaction_journals.id', $journalId)->count(); + if (null === $journalId || 0 === $count) { + Log::warning(sprintf('Transaction group #%d has %d journals with ID %d', $transactionGroup->id, $count, $journalId)); Log::warning('Invalid submission: Each split must have transaction_journal_id (either valid ID or 0).'); $validator->errors()->add(sprintf('transactions.%d.source_name', $index), (string)trans('validation.need_id_in_edit')); } diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index 3fa05d77cd..dd4f1d6dbc 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -59,7 +59,7 @@ trait RecurrenceValidation if (null !== $recurrence) { Log::debug('There is a recurrence in the route.'); // ok so we have a recurrence should be able to extract type somehow. - /** @var RecurrenceTransaction $first */ + /** @var RecurrenceTransaction|null $first */ $first = $recurrence->recurrenceTransactions()->first(); if (null !== $first) { $transactionType = $first->transactionType ? $first->transactionType->type : 'withdrawal'; @@ -91,7 +91,7 @@ trait RecurrenceValidation continue; } // validate source account. - $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : null; + $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; $sourceName = $transaction['source_name'] ?? null; $validSource = $accountValidator->validateSource($sourceId, $sourceName, null); @@ -103,7 +103,7 @@ trait RecurrenceValidation return; } // validate destination account - $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null; + $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; $destinationName = $transaction['destination_name'] ?? null; $validDestination = $accountValidator->validateDestination($destinationId, $destinationName, null); // do something with result: diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index 2ea32dae7b..6dd17d06ed 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -100,9 +100,9 @@ trait TransactionValidation $accountValidator->setTransactionType($transactionType); // validate source account. - $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : null; - $sourceName = isset($transaction['source_name']) ? (string)$transaction['source_name'] : null; - $sourceIban = isset($transaction['source_iban']) ? (string)$transaction['source_iban'] : null; + $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; + $sourceName = array_key_exists('source_name', $transaction) ? (string)$transaction['source_name'] : null; + $sourceIban = array_key_exists('source_iban', $transaction) ? (string)$transaction['source_iban'] : null; $validSource = $accountValidator->validateSource($sourceId, $sourceName, $sourceIban); // do something with result: @@ -113,9 +113,9 @@ trait TransactionValidation return; } // validate destination account - $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null; - $destinationName = isset($transaction['destination_name']) ? (string)$transaction['destination_name'] : null; - $destinationIban = isset($transaction['destination_iban']) ? (string)$transaction['destination_iban'] : null; + $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; + $destinationName = array_key_exists('destination_name', $transaction) ? (string)$transaction['destination_name'] : null; + $destinationIban = array_key_exists('destination_iban', $transaction) ? (string)$transaction['destination_iban'] : null; $validDestination = $accountValidator->validateDestination($destinationId, $destinationName, $destinationIban); // do something with result: if (false === $validDestination) { @@ -155,10 +155,11 @@ trait TransactionValidation Log::debug('Now validating single account update in validateSingleUpdate()'); // if no account types are given, just skip the check. - if (!isset($transaction['source_id']) - && !isset($transaction['source_name']) - && !isset($transaction['destination_id']) - && !isset($transaction['destination_name'])) { + if ( + !array_key_exists('source_id', $transaction) + && !array_key_exists('source_name', $transaction) + && !array_key_exists('destination_id', $transaction) + && !array_key_exists('destination_name', $transaction)) { Log::debug('No account data has been submitted so will not validating account info.'); return; @@ -362,7 +363,7 @@ trait TransactionValidation if (0 === $journalId) { return 'invalid'; } - /** @var TransactionJournal $journal */ + /** @var TransactionJournal|null $journal */ $journal = TransactionJournal::with(['transactionType'])->find($journalId); if (null !== $journal) { return strtolower($journal->transactionType->type); diff --git a/bootstrap/app.php b/bootstrap/app.php index f7a7e500df..3b5d3d0789 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -33,7 +33,7 @@ use Illuminate\Contracts\View\Factory as ViewFactory; | */ -bcscale(12); +bcscale(24); if (!function_exists('envNonEmpty')) { /** diff --git a/changelog.md b/changelog.md index 0735635f43..918098d7ae 100644 --- a/changelog.md +++ b/changelog.md @@ -2,7 +2,23 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). -## Unreleased +## 5.5.4 (API 1.5.2) 2021-04-09 + +Firefly III features a new *experimental* layout that I'm currently building. You can enable it by setting environment variable `FIREFLY_III_LAYOUT=v2`. Check out [GitHub](https://github.com/firefly-iii/firefly-iii/issues/4618) for the announcement and status updates. This release features an update API version. Check out [the difference](https://github.com/firefly-iii/api-docs-generator/compare/1.5.1...1.5.2). + +### Fixed +- [Issue 4593](https://github.com/firefly-iii/firefly-iii/issues/4593) Could not change or update recurring repetition data. +- [Issue 4596](https://github.com/firefly-iii/firefly-iii/issues/4596) The error handler mailer mails about too many things. +- [Issue 4603](https://github.com/firefly-iii/firefly-iii/issues/4603) Call to bad RSA method. +- [Issue 4607](https://github.com/firefly-iii/firefly-iii/issues/4607) Bad code in set source / set destination rule actions meant that it would not fire in some cases. + +### Security +- [Issue 4616](https://github.com/firefly-iii/firefly-iii/issues/4616) Firefly III has some extra security-related headers. + +### API +- [Issue 4600](https://github.com/firefly-iii/firefly-iii/issues/4600) Sometimes empty amounts would not be properly picked up by the API. +- New endpoint to bulk update transactions. +- The chart API endpoint includes the time in the labels. ## 5.5.3 (API 1.5.1) 2021-04-03 @@ -28,6 +44,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). This release features an update API version. Check out [the difference](https://github.com/firefly-iii/api-docs-generator/compare/1.5.0...1.5.1). + - All endpoints that used to deliver dates (`2021-04-27`) will now deliver date time strings (`2021-04-27T16:43:12+02:00`). - [Issue 4566](https://github.com/firefly-iii/firefly-iii/issues/4566) Some API end points did not deliver the promised data. diff --git a/composer.lock b/composer.lock index 8c4bfc64dd..f966a75292 100644 --- a/composer.lock +++ b/composer.lock @@ -1642,16 +1642,16 @@ }, { "name": "laravel/framework", - "version": "v8.35.1", + "version": "v8.36.2", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "d118c0df39e7524131176aaf76493eae63a8a602" + "reference": "0debd8ad6b5aa1f61ccc73910adf049af4ca0444" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/d118c0df39e7524131176aaf76493eae63a8a602", - "reference": "d118c0df39e7524131176aaf76493eae63a8a602", + "url": "https://api.github.com/repos/laravel/framework/zipball/0debd8ad6b5aa1f61ccc73910adf049af4ca0444", + "reference": "0debd8ad6b5aa1f61ccc73910adf049af4ca0444", "shasum": "" }, "require": { @@ -1806,20 +1806,20 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2021-03-30T21:34:17+00:00" + "time": "2021-04-07T12:37:22+00:00" }, { "name": "laravel/passport", - "version": "v10.1.2", + "version": "v10.1.3", "source": { "type": "git", "url": "https://github.com/laravel/passport.git", - "reference": "9f1a5d56eb609250104afc38cf407f7c2520cda3" + "reference": "a5e4471dd99b7638ab5ca3ecab6cd87cf37eb410" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/passport/zipball/9f1a5d56eb609250104afc38cf407f7c2520cda3", - "reference": "9f1a5d56eb609250104afc38cf407f7c2520cda3", + "url": "https://api.github.com/repos/laravel/passport/zipball/a5e4471dd99b7638ab5ca3ecab6cd87cf37eb410", + "reference": "a5e4471dd99b7638ab5ca3ecab6cd87cf37eb410", "shasum": "" }, "require": { @@ -1883,7 +1883,7 @@ "issues": "https://github.com/laravel/passport/issues", "source": "https://github.com/laravel/passport" }, - "time": "2021-03-02T16:40:00+00:00" + "time": "2021-04-06T14:30:45+00:00" }, { "name": "laravel/ui", @@ -3268,16 +3268,16 @@ }, { "name": "phpseclib/phpseclib", - "version": "3.0.6", + "version": "3.0.7", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "906a5fafabe5e6ba51ef3dc65b2722a677908837" + "reference": "d369510df0ebd5e1a5d0fe3d4d23c55fa87a403d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/906a5fafabe5e6ba51ef3dc65b2722a677908837", - "reference": "906a5fafabe5e6ba51ef3dc65b2722a677908837", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/d369510df0ebd5e1a5d0fe3d4d23c55fa87a403d", + "reference": "d369510df0ebd5e1a5d0fe3d4d23c55fa87a403d", "shasum": "" }, "require": { @@ -3359,7 +3359,7 @@ ], "support": { "issues": "https://github.com/phpseclib/phpseclib/issues", - "source": "https://github.com/phpseclib/phpseclib/tree/3.0.6" + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.7" }, "funding": [ { @@ -3375,7 +3375,7 @@ "type": "tidelift" } ], - "time": "2021-03-10T13:58:31+00:00" + "time": "2021-04-06T14:00:11+00:00" }, { "name": "pragmarx/google2fa", @@ -3560,23 +3560,22 @@ }, { "name": "predis/predis", - "version": "v1.1.6", + "version": "v1.1.7", "source": { "type": "git", "url": "https://github.com/predis/predis.git", - "reference": "9930e933c67446962997b05201c69c2319bf26de" + "reference": "b240daa106d4e02f0c5b7079b41e31ddf66fddf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/predis/predis/zipball/9930e933c67446962997b05201c69c2319bf26de", - "reference": "9930e933c67446962997b05201c69c2319bf26de", + "url": "https://api.github.com/repos/predis/predis/zipball/b240daa106d4e02f0c5b7079b41e31ddf66fddf8", + "reference": "b240daa106d4e02f0c5b7079b41e31ddf66fddf8", "shasum": "" }, "require": { "php": ">=5.3.9" }, "require-dev": { - "cweagans/composer-patches": "^1.6", "phpunit/phpunit": "~4.8" }, "suggest": { @@ -3584,18 +3583,6 @@ "ext-phpiredis": "Allows faster serialization and deserialization of the Redis protocol" }, "type": "library", - "extra": { - "composer-exit-on-patch-failure": true, - "patches": { - "phpunit/phpunit-mock-objects": { - "Fix PHP 7 and 8 compatibility": "./tests/phpunit_mock_objects.patch" - }, - "phpunit/phpunit": { - "Fix PHP 7 compatibility": "./tests/phpunit_php7.patch", - "Fix PHP 8 compatibility": "./tests/phpunit_php8.patch" - } - } - }, "autoload": { "psr-4": { "Predis\\": "src/" @@ -3627,7 +3614,7 @@ ], "support": { "issues": "https://github.com/predis/predis/issues", - "source": "https://github.com/predis/predis/tree/v1.1.6" + "source": "https://github.com/predis/predis/tree/v1.1.7" }, "funding": [ { @@ -3635,7 +3622,7 @@ "type": "github" } ], - "time": "2020-09-11T19:18:05+00:00" + "time": "2021-04-04T19:34:46+00:00" }, { "name": "psr/container", @@ -7194,16 +7181,16 @@ }, { "name": "barryvdh/laravel-debugbar", - "version": "v3.5.2", + "version": "v3.5.5", "source": { "type": "git", "url": "https://github.com/barryvdh/laravel-debugbar.git", - "reference": "cae0a8d1cb89b0f0522f65e60465e16d738e069b" + "reference": "6420113d90bb746423fa70b9940e9e7c26ebc121" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/barryvdh/laravel-debugbar/zipball/cae0a8d1cb89b0f0522f65e60465e16d738e069b", - "reference": "cae0a8d1cb89b0f0522f65e60465e16d738e069b", + "url": "https://api.github.com/repos/barryvdh/laravel-debugbar/zipball/6420113d90bb746423fa70b9940e9e7c26ebc121", + "reference": "6420113d90bb746423fa70b9940e9e7c26ebc121", "shasum": "" }, "require": { @@ -7263,7 +7250,7 @@ ], "support": { "issues": "https://github.com/barryvdh/laravel-debugbar/issues", - "source": "https://github.com/barryvdh/laravel-debugbar/tree/v3.5.2" + "source": "https://github.com/barryvdh/laravel-debugbar/tree/v3.5.5" }, "funding": [ { @@ -7271,7 +7258,7 @@ "type": "github" } ], - "time": "2021-01-06T14:21:44+00:00" + "time": "2021-04-07T11:19:20+00:00" }, { "name": "barryvdh/laravel-ide-helper", @@ -8657,16 +8644,16 @@ }, { "name": "nunomaduro/larastan", - "version": "v0.7.1", + "version": "v0.7.2", "source": { "type": "git", "url": "https://github.com/nunomaduro/larastan.git", - "reference": "bbbe09ec16a565e6423878bd17fc4355fa0d0a4c" + "reference": "cb7fa0b5af3738772e3568c0a0c7a080851e281d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nunomaduro/larastan/zipball/bbbe09ec16a565e6423878bd17fc4355fa0d0a4c", - "reference": "bbbe09ec16a565e6423878bd17fc4355fa0d0a4c", + "url": "https://api.github.com/repos/nunomaduro/larastan/zipball/cb7fa0b5af3738772e3568c0a0c7a080851e281d", + "reference": "cb7fa0b5af3738772e3568c0a0c7a080851e281d", "shasum": "" }, "require": { @@ -8681,7 +8668,7 @@ "illuminate/support": "^6.0 || ^7.0 || ^8.0 || ^9.0", "mockery/mockery": "^0.9 || ^1.0", "php": "^7.2 || ^8.0", - "phpstan/phpstan": "0.12.81", + "phpstan/phpstan": "^0.12.83", "symfony/process": "^4.3 || ^5.0" }, "require-dev": { @@ -8730,7 +8717,7 @@ ], "support": { "issues": "https://github.com/nunomaduro/larastan/issues", - "source": "https://github.com/nunomaduro/larastan/tree/v0.7.1" + "source": "https://github.com/nunomaduro/larastan/tree/v0.7.2" }, "funding": [ { @@ -8750,7 +8737,7 @@ "type": "patreon" } ], - "time": "2021-03-19T09:41:48+00:00" + "time": "2021-04-08T10:51:16+00:00" }, { "name": "openlss/lib-array2xml", @@ -9143,16 +9130,16 @@ }, { "name": "phpstan/phpstan", - "version": "0.12.81", + "version": "0.12.83", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "0dd5b0ebeff568f7000022ea5f04aa86ad3124b8" + "reference": "4a967cec6efb46b500dd6d768657336a3ffe699f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/0dd5b0ebeff568f7000022ea5f04aa86ad3124b8", - "reference": "0dd5b0ebeff568f7000022ea5f04aa86ad3124b8", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4a967cec6efb46b500dd6d768657336a3ffe699f", + "reference": "4a967cec6efb46b500dd6d768657336a3ffe699f", "shasum": "" }, "require": { @@ -9183,7 +9170,7 @@ "description": "PHPStan - PHP Static Analysis Tool", "support": { "issues": "https://github.com/phpstan/phpstan/issues", - "source": "https://github.com/phpstan/phpstan/tree/0.12.81" + "source": "https://github.com/phpstan/phpstan/tree/0.12.83" }, "funding": [ { @@ -9199,7 +9186,7 @@ "type": "tidelift" } ], - "time": "2021-03-08T22:03:02+00:00" + "time": "2021-04-03T15:35:45+00:00" }, { "name": "phpstan/phpstan-deprecation-rules", @@ -9729,12 +9716,12 @@ "source": { "type": "git", "url": "https://github.com/Roave/SecurityAdvisories.git", - "reference": "0a55b3eacf6b4a0fdc6ec9d01e00285ca9942b2b" + "reference": "07d2f0c0e6553fd7433f2eb7d043260d3bfd351d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/0a55b3eacf6b4a0fdc6ec9d01e00285ca9942b2b", - "reference": "0a55b3eacf6b4a0fdc6ec9d01e00285ca9942b2b", + "url": "https://api.github.com/repos/Roave/SecurityAdvisories/zipball/07d2f0c0e6553fd7433f2eb7d043260d3bfd351d", + "reference": "07d2f0c0e6553fd7433f2eb7d043260d3bfd351d", "shasum": "" }, "conflict": { @@ -9778,7 +9765,7 @@ "doctrine/doctrine-module": "<=0.7.1", "doctrine/mongodb-odm": ">=1,<1.0.2", "doctrine/mongodb-odm-bundle": ">=2,<3.0.1", - "doctrine/orm": ">=2,<2.4.8|>=2.5,<2.5.1", + "doctrine/orm": ">=2,<2.4.8|>=2.5,<2.5.1|>=2.8.3,<2.8.4", "dolibarr/dolibarr": "<11.0.4", "dompdf/dompdf": ">=0.6,<0.6.2", "drupal/core": ">=7,<7.74|>=8,<8.8.11|>=8.9,<8.9.9|>=9,<9.0.8", @@ -9845,7 +9832,7 @@ "magento/magento1ee": ">=1,<1.14.4.3", "magento/product-community-edition": ">=2,<2.2.10|>=2.3,<2.3.2-p.2", "marcwillmann/turn": "<0.3.3", - "mautic/core": "<2.16.5|>=3,<3.2.4|= 2.13.1", + "mautic/core": "<3.3.2|= 2.13.1", "mediawiki/core": ">=1.27,<1.27.6|>=1.29,<1.29.3|>=1.30,<1.30.2|>=1.31,<1.31.9|>=1.32,<1.32.6|>=1.32.99,<1.33.3|>=1.33.99,<1.34.3|>=1.34.99,<1.35", "mittwald/typo3_forum": "<1.2.1", "monolog/monolog": ">=1.8,<1.12", @@ -9879,6 +9866,7 @@ "phpmyadmin/phpmyadmin": "<4.9.6|>=5,<5.0.3", "phpoffice/phpexcel": "<1.8.2", "phpoffice/phpspreadsheet": "<1.16", + "phpseclib/phpseclib": "<2.0.31|>=3,<3.0.7", "phpunit/phpunit": ">=4.8.19,<4.8.28|>=5.0.10,<5.6.3", "phpwhois/phpwhois": "<=4.2.5", "phpxmlrpc/extras": "<0.6.1", @@ -9889,6 +9877,7 @@ "prestashop/contactform": ">1.0.1,<4.3", "prestashop/gamification": "<2.3.2", "prestashop/productcomments": ">=4,<4.2.1", + "prestashop/ps_emailsubscription": "<2.6.1", "prestashop/ps_facetedsearch": "<3.4.1", "privatebin/privatebin": "<1.2.2|>=1.3,<1.3.2", "propel/propel": ">=2-alpha.1,<=2-alpha.7", @@ -10058,7 +10047,7 @@ "type": "tidelift" } ], - "time": "2021-03-29T21:01:39+00:00" + "time": "2021-04-07T21:01:39+00:00" }, { "name": "sebastian/cli-parser", diff --git a/config/firefly.php b/config/firefly.php index 6152fd714f..971585fe7a 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -99,8 +99,8 @@ return [ 'webhooks' => false, ], - 'version' => '5.5.3', - 'api_version' => '1.5.1', + 'version' => '5.5.4', + 'api_version' => '1.5.2', 'db_version' => 16, 'maxUploadSize' => 1073741824, // 1 GB 'send_error_message' => env('SEND_ERROR_MESSAGE', true), @@ -113,6 +113,7 @@ return [ 'demo_password' => env('DEMO_PASSWORD', ''), 'fixer_api_key' => env('FIXER_API_KEY', ''), 'mapbox_api_key' => env('MAPBOX_API_KEY', ''), + 'enable_external_map' => env('ENABLE_EXTERNAL_MAP', false), 'trusted_proxies' => env('TRUSTED_PROXIES', ''), 'send_report_journals' => envNonEmpty('SEND_REPORT_JOURNALS', true), 'tracker_site_id' => env('TRACKER_SITE_ID', ''), @@ -122,14 +123,13 @@ return [ 'login_provider' => envNonEmpty('LOGIN_PROVIDER', 'eloquent'), 'authentication_guard' => envNonEmpty('AUTHENTICATION_GUARD', 'web'), 'custom_logout_uri' => envNonEmpty('CUSTOM_LOGOUT_URI', ''), - 'cer_provider' => envNonEmpty('CER_PROVIDER', 'fixer'), - 'ipinfo_token' => env('IPINFO_TOKEN',''), + 'ipinfo_token' => env('IPINFO_TOKEN', ''), 'update_endpoint' => 'https://version.firefly-iii.org/index.json', 'send_telemetry' => env('SEND_TELEMETRY', false), 'allow_webhooks' => env('ALLOW_WEBHOOKS', false), 'telemetry_endpoint' => 'https://telemetry.firefly-iii.org', 'layout' => envNonEmpty('FIREFLY_III_LAYOUT', 'v1'), - 'update_minimum_age' => 6, + 'update_minimum_age' => 7, 'default_location' => [ 'longitude' => env('MAP_DEFAULT_LONG', '5.916667'), 'latitude' => env('MAP_DEFAULT_LAT', '51.983333'), @@ -207,9 +207,11 @@ return [ 'application/vnd.oasis.opendocument.database', 'application/vnd.oasis.opendocument.image', ], - 'list_length' => 10, + 'list_length' => 10, // to be removed if v1 is cancelled. 'bill_periods' => ['weekly', 'monthly', 'quarterly', 'half-year', 'yearly'], + 'interest_periods' => ['weekly', 'monthly', 'quarterly', 'half-year', 'yearly'], 'accountRoles' => ['defaultAsset', 'sharedAsset', 'savingAsset', 'ccAsset', 'cashWalletAsset'], + 'valid_liabilities' => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], 'ccTypes' => [ 'monthlyFull' => 'Full payment every month', ], @@ -330,14 +332,6 @@ return [ 'zh_TW' => ['name_locale' => 'Chinese Traditional', 'name_english' => 'Chinese Traditional'], 'zh_CN' => ['name_locale' => 'Chinese Simplified', 'name_english' => 'Chinese Simplified'], ], - 'transactionTypesByWhat' => [ - 'expenses' => ['Withdrawal'], - 'withdrawal' => ['Withdrawal'], - 'revenue' => ['Deposit'], - 'deposit' => ['Deposit'], - 'transfer' => ['Transfer'], - 'transfers' => ['Transfer'], - ], 'transactionTypesByType' => [ 'expenses' => ['Withdrawal'], 'withdrawal' => ['Withdrawal'], @@ -849,4 +843,8 @@ return [ Webhook::DELIVERY_JSON => 'DELIVERY_JSON', ], ], + 'can_have_virtual_amounts' => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD], + 'valid_asset_fields' => ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'], + 'valid_cc_fields' => ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'], + 'valid_account_fields' => ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth'], ]; diff --git a/database/factories/FireflyIII/Models/AccountFactory.php b/database/factories/FireflyIII/Models/AccountFactory.php deleted file mode 100644 index dc7c13b670..0000000000 --- a/database/factories/FireflyIII/Models/AccountFactory.php +++ /dev/null @@ -1,99 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace Database\Factories\FireflyIII\Models; - -use FireflyIII\Models\Account; -use Illuminate\Database\Eloquent\Factories\Factory; - -/** - * Class AccountFactory - */ -class AccountFactory extends Factory -{ - - /** - * The name of the factory's corresponding model. - * - * @var string - */ - protected $model = Account::class; - - /** - * @return AccountFactory - */ - public function asset() - { - return $this->state( - function () { - return [ - 'account_type_id' => 3, - ]; - } - ); - } - - /** - * @inheritDoc - */ - public function definition() - { - return [ - 'user_id' => 1, - 'account_type_id' => 1, - 'name' => $this->faker->words(3, true), - 'virtual_balance' => '0', - 'active' => 1, - 'encrypted' => 0, - 'order' => 1, - ]; - } - - /** - * @return AccountFactory - */ - public function expense() - { - return $this->state( - function () { - return [ - 'account_type_id' => 4, - ]; - } - ); - } - - /** - * @return AccountFactory - */ - public function initialBalance() - { - return $this->state( - function () { - return [ - 'account_type_id' => 6, - ]; - } - ); - } -} diff --git a/database/factories/FireflyIII/Models/TransactionJournalFactory.php b/database/factories/FireflyIII/Models/TransactionJournalFactory.php deleted file mode 100644 index 20cb16769b..0000000000 --- a/database/factories/FireflyIII/Models/TransactionJournalFactory.php +++ /dev/null @@ -1,123 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace Database\Factories\FireflyIII\Models; - -use FireflyIII\Models\Account; -use FireflyIII\Models\Transaction; -use FireflyIII\Models\TransactionJournal; -use Illuminate\Database\Eloquent\Factories\Factory; - -/** - * Class TransactionJournalFactory - */ -class TransactionJournalFactory extends Factory -{ - /** - * The name of the factory's corresponding model. - * - * @var string - */ - protected $model = TransactionJournal::class; - - /** - * @return Factory - */ - public function brokenOpeningBalance() - { - return $this->state( - function () { - return [ - 'transaction_type_id' => 4, - ]; - } - )->afterCreating( - function (TransactionJournal $journal) { - $ob1 = Account::factory(Account::class)->initialBalance()->create(); - $ob2 = Account::factory(Account::class)->initialBalance()->create(); - - Transaction::factory()->create( - [ - 'account_id' => $ob1->id, - 'transaction_journal_id' => $journal->id, - 'amount' => '5', - ] - ); - Transaction::factory()->create( - [ - 'account_id' => $ob2->id, - 'transaction_journal_id' => $journal->id, - 'amount' => '5', - ] - ); - - } - ); - } - - /** - * Define the model's default state. - * - * @return array - */ - public function definition() - { - return [ - 'user_id' => 1, - 'transaction_type_id' => 1, - 'description' => $this->faker->words(3, true), - 'tag_count' => 0, - 'date' => $this->faker->date('Y-m-d'), - ]; - } - - /** - * @return Factory - */ - public function openingBalance() - { - return $this - ->state(fn() => ['transaction_type_id' => 4]) - ->afterCreating( - function (TransactionJournal $journal) { - // fix factory - $obAccount = Account::factory(Account::class)->initialBalance()->create(); - $assetAccount = Account::factory(Account::class)->asset()->create(); - Transaction::factory()->create( - [ - 'account_id' => $obAccount->id, - 'transaction_journal_id' => $journal->id, - 'amount' => '5', - ] - ); - Transaction::factory()->create( - [ - 'account_id' => $assetAccount->id, - 'transaction_journal_id' => $journal->id, - 'amount' => '-5', - ] - ); - } - ); - } -} diff --git a/database/migrations/2020_11_12_070604_changes_for_v550.php b/database/migrations/2020_11_12_070604_changes_for_v550.php index dc0c3cedde..5c5902df4f 100644 --- a/database/migrations/2020_11_12_070604_changes_for_v550.php +++ b/database/migrations/2020_11_12_070604_changes_for_v550.php @@ -120,8 +120,10 @@ class ChangesForV550 extends Migration // update budget / transaction journal table. Schema::table( 'budget_transaction_journal', function (Blueprint $table) { - $table->integer('budget_limit_id', false, true)->nullable()->default(null)->after('budget_id'); - $table->foreign('budget_limit_id', 'budget_id_foreign')->references('id')->on('budget_limits')->onDelete('set null'); + if (!Schema::hasColumn('budget_transaction_journal', 'budget_limit_id')) { + $table->integer('budget_limit_id', false, true)->nullable()->default(null)->after('budget_id'); + $table->foreign('budget_limit_id', 'budget_id_foreign')->references('id')->on('budget_limits')->onDelete('set null'); + } } ); @@ -130,63 +132,73 @@ class ChangesForV550 extends Migration Schema::table( 'budget_limits', static function (Blueprint $table) { - $table->string('period', 12)->nullable(); - $table->boolean('generated')->default(false); + if (!Schema::hasColumn('budget_limits', 'period')) { + $table->string('period', 12)->nullable(); + } + if (!Schema::hasColumn('budget_limits', 'generated')) { + $table->boolean('generated')->default(false); + } } ); // new webhooks table - Schema::create( - 'webhooks', - static function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('user_id', false, true); - $table->string('title', 512)->index(); - $table->string('secret', 32)->index(); - $table->boolean('active')->default(true); - $table->unsignedSmallInteger('trigger', false); - $table->unsignedSmallInteger('response', false); - $table->unsignedSmallInteger('delivery', false); - $table->string('url', 1024); - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); - $table->unique(['user_id', 'title']); - } - ); + if (!Schema::hasTable('webhooks')) { + Schema::create( + 'webhooks', + static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('user_id', false, true); + $table->string('title', 512)->index(); + $table->string('secret', 32)->index(); + $table->boolean('active')->default(true); + $table->unsignedSmallInteger('trigger', false); + $table->unsignedSmallInteger('response', false); + $table->unsignedSmallInteger('delivery', false); + $table->string('url', 1024); + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->unique(['user_id', 'title']); + } + ); + } // new webhook_messages table - Schema::create( - 'webhook_messages', - static function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->boolean('sent')->default(false); - $table->boolean('errored')->default(false); + if (!Schema::hasTable('webhook_messages')) { + Schema::create( + 'webhook_messages', + static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->boolean('sent')->default(false); + $table->boolean('errored')->default(false); - $table->integer('webhook_id', false, true); - $table->string('uuid', 64); - $table->longText('message'); + $table->integer('webhook_id', false, true); + $table->string('uuid', 64); + $table->longText('message'); - $table->foreign('webhook_id')->references('id')->on('webhooks')->onDelete('cascade'); - } - ); + $table->foreign('webhook_id')->references('id')->on('webhooks')->onDelete('cascade'); + } + ); + } - Schema::create( - 'webhook_attempts', - static function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('webhook_message_id', false, true); - $table->unsignedSmallInteger('status_code')->default(0); + if (!Schema::hasTable('webhook_attempts')) { + Schema::create( + 'webhook_attempts', + static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('webhook_message_id', false, true); + $table->unsignedSmallInteger('status_code')->default(0); - $table->longText('logs')->nullable(); - $table->longText('response')->nullable(); + $table->longText('logs')->nullable(); + $table->longText('response')->nullable(); - $table->foreign('webhook_message_id')->references('id')->on('webhook_messages')->onDelete('cascade'); - } - ); + $table->foreign('webhook_message_id')->references('id')->on('webhook_messages')->onDelete('cascade'); + } + ); + } } } diff --git a/database/seeders/AccountTypeSeeder.php b/database/seeders/AccountTypeSeeder.php index c34fb4f663..f22d029426 100644 --- a/database/seeders/AccountTypeSeeder.php +++ b/database/seeders/AccountTypeSeeder.php @@ -51,7 +51,7 @@ class AccountTypeSeeder extends Seeder try { AccountType::create(['type' => $type]); } catch (PDOException $e) { - // dont care. + // @ignoreException } } } diff --git a/database/seeders/LinkTypeSeeder.php b/database/seeders/LinkTypeSeeder.php index 702abb3f61..00ee9fee54 100644 --- a/database/seeders/LinkTypeSeeder.php +++ b/database/seeders/LinkTypeSeeder.php @@ -63,7 +63,7 @@ class LinkTypeSeeder extends Seeder try { LinkType::create($type); } catch (PDOException $e) { - // dont care + // @ignoreException } } } diff --git a/database/seeders/PermissionSeeder.php b/database/seeders/PermissionSeeder.php index ab965073b5..7db4e44406 100644 --- a/database/seeders/PermissionSeeder.php +++ b/database/seeders/PermissionSeeder.php @@ -49,7 +49,7 @@ class PermissionSeeder extends Seeder try { Role::create($role); } catch (PDOException $e) { - // dont care + // @ignoreException } } } diff --git a/database/seeders/TransactionCurrencySeeder.php b/database/seeders/TransactionCurrencySeeder.php index 2e83a1f129..0b68c6588f 100644 --- a/database/seeders/TransactionCurrencySeeder.php +++ b/database/seeders/TransactionCurrencySeeder.php @@ -81,7 +81,7 @@ class TransactionCurrencySeeder extends Seeder try { TransactionCurrency::create($currency); } catch (PDOException $e) { - // dont care + // @ignoreException } } } diff --git a/database/seeders/TransactionTypeSeeder.php b/database/seeders/TransactionTypeSeeder.php index adab1d38c8..dc0bf3ea06 100644 --- a/database/seeders/TransactionTypeSeeder.php +++ b/database/seeders/TransactionTypeSeeder.php @@ -46,7 +46,7 @@ class TransactionTypeSeeder extends Seeder try { TransactionType::create(['type' => $type]); } catch (PDOException $e) { - // dont care + // @ignoreException } } } diff --git a/frontend/mix-manifest.json b/frontend/mix-manifest.json index ba9d3b9680..188b6465ac 100644 --- a/frontend/mix-manifest.json +++ b/frontend/mix-manifest.json @@ -1,7 +1,9 @@ { "/public/js/dashboard.js": "/public/js/dashboard.js", "/public/js/accounts/index.js": "/public/js/accounts/index.js", + "/public/js/accounts/delete.js": "/public/js/accounts/delete.js", "/public/js/accounts/show.js": "/public/js/accounts/show.js", + "/public/js/accounts/create.js": "/public/js/accounts/create.js", "/public/js/transactions/create.js": "/public/js/transactions/create.js", "/public/js/transactions/edit.js": "/public/js/transactions/edit.js", "/public/js/transactions/index.js": "/public/js/transactions/index.js", diff --git a/frontend/src/app.scss b/frontend/src/app.scss index 5dfc89ce09..d5b017f480 100644 --- a/frontend/src/app.scss +++ b/frontend/src/app.scss @@ -17,9 +17,6 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see+ {{ $t('form.permDeleteWarning') }} +
++ {{ $t('form.account_areYouSure_js', {'name': this.accountName}) }} +
++ + {{ $tc('form.also_delete_piggyBanks_js', piggyBankCount, {count: piggyBankCount}) }} + + + {{ $tc('form.also_delete_transactions_js', transactionCount, {count: transactionCount}) }} + +
++ {{ $tc('firefly.save_transactions_by_moving_js', transactionCount) }} +
++ +
+ ++ +
+ ++ + {{ error }}
`s get reset. However, we also reset the\n// bottom margin to use `rem` units instead of `em`.\np {\n margin-top: 0;\n margin-bottom: $paragraph-margin-bottom;\n}\n\n// Abbreviations\n//\n// 1. Duplicate behavior to the data-* attribute for our tooltip plugin\n// 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.\n// 3. Add explicit cursor to indicate changed behavior.\n// 4. Remove the bottom border in Firefox 39-.\n// 5. Prevent the text-decoration to be skipped.\n\nabbr[title],\nabbr[data-original-title] { // 1\n text-decoration: underline; // 2\n text-decoration: underline dotted; // 2\n cursor: help; // 3\n border-bottom: 0; // 4\n text-decoration-skip-ink: none; // 5\n}\n\naddress {\n margin-bottom: 1rem;\n font-style: normal;\n line-height: inherit;\n}\n\nol,\nul,\ndl {\n margin-top: 0;\n margin-bottom: 1rem;\n}\n\nol ol,\nul ul,\nol ul,\nul ol {\n margin-bottom: 0;\n}\n\ndt {\n font-weight: $dt-font-weight;\n}\n\ndd {\n margin-bottom: .5rem;\n margin-left: 0; // Undo browser default\n}\n\nblockquote {\n margin: 0 0 1rem;\n}\n\nb,\nstrong {\n font-weight: $font-weight-bolder; // Add the correct font weight in Chrome, Edge, and Safari\n}\n\nsmall {\n @include font-size(80%); // Add the correct font size in all browsers\n}\n\n//\n// Prevent `sub` and `sup` elements from affecting the line height in\n// all browsers.\n//\n\nsub,\nsup {\n position: relative;\n @include font-size(75%);\n line-height: 0;\n vertical-align: baseline;\n}\n\nsub { bottom: -.25em; }\nsup { top: -.5em; }\n\n\n//\n// Links\n//\n\na {\n color: $link-color;\n text-decoration: $link-decoration;\n background-color: transparent; // Remove the gray background on active links in IE 10.\n\n @include hover() {\n color: $link-hover-color;\n text-decoration: $link-hover-decoration;\n }\n}\n\n// And undo these styles for placeholder links/named anchors (without href).\n// It would be more straightforward to just use a[href] in previous block, but that\n// causes specificity issues in many other styles that are too complex to fix.\n// See https://github.com/twbs/bootstrap/issues/19402\n\na:not([href]):not([class]) {\n color: inherit;\n text-decoration: none;\n\n @include hover() {\n color: inherit;\n text-decoration: none;\n }\n}\n\n\n//\n// Code\n//\n\npre,\ncode,\nkbd,\nsamp {\n font-family: $font-family-monospace;\n @include font-size(1em); // Correct the odd `em` font sizing in all browsers.\n}\n\npre {\n // Remove browser default top margin\n margin-top: 0;\n // Reset browser default of `1em` to use `rem`s\n margin-bottom: 1rem;\n // Don't allow content to break outside\n overflow: auto;\n // Disable auto-hiding scrollbar in IE & legacy Edge to avoid overlap,\n // making it impossible to interact with the content\n -ms-overflow-style: scrollbar;\n}\n\n\n//\n// Figures\n//\n\nfigure {\n // Apply a consistent margin strategy (matches our type styles).\n margin: 0 0 1rem;\n}\n\n\n//\n// Images and content\n//\n\nimg {\n vertical-align: middle;\n border-style: none; // Remove the border on images inside links in IE 10-.\n}\n\nsvg {\n // Workaround for the SVG overflow bug in IE10/11 is still required.\n // See https://github.com/twbs/bootstrap/issues/26878\n overflow: hidden;\n vertical-align: middle;\n}\n\n\n//\n// Tables\n//\n\ntable {\n border-collapse: collapse; // Prevent double borders\n}\n\ncaption {\n padding-top: $table-cell-padding;\n padding-bottom: $table-cell-padding;\n color: $table-caption-color;\n text-align: left;\n caption-side: bottom;\n}\n\n// 1. Removes font-weight bold by inheriting\n// 2. Matches default `