diff --git a/app/Console/Commands/LegacyBudgetGroupShift.php b/app/Console/Commands/LegacyBudgetGroupShift.php index 5c6704fd..7695ff8d 100644 --- a/app/Console/Commands/LegacyBudgetGroupShift.php +++ b/app/Console/Commands/LegacyBudgetGroupShift.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\Schema; use App\Models\Legacy\LegacyBudgetGroup; use App\Models\Legacy\LegacyBudgetItem; use App\Models\Legacy\LegacyBudgetPlan; @@ -17,12 +18,12 @@ class LegacyBudgetGroupShift extends Command public function handle(): int { - return \DB::transaction(function (): int { - $latestPlan = LegacyBudgetPlan::orderBy('id', 'desc')->limit(1)->sole(); + return DB::transaction(function (): int { + $latestPlan = LegacyBudgetPlan::orderByDesc('id')->limit(1)->sole(); $budgetGroups = LegacyBudgetGroup::where('hhp_id', $latestPlan->id) ->where('id', '>=', $this->argument('new_group_id')); $this->info('The following amount of other groups will be shifted back: '.$budgetGroups->count()); - \Schema::disableForeignKeyConstraints(); + Schema::disableForeignKeyConstraints(); // this is so hacky ... $budgetGroups->update(['id' => DB::raw('-(id + 1)')]); LegacyBudgetGroup::where('id', '<', 0)->update(['id' => DB::raw('-id')]); @@ -36,7 +37,7 @@ public function handle(): int ]); $newGroup->id = $this->argument('new_group_id'); $newGroup->save(); - \Schema::enableForeignKeyConstraints(); + Schema::enableForeignKeyConstraints(); return self::SUCCESS; }); diff --git a/app/Console/Commands/LegacyBudgetItemBatchShift.php b/app/Console/Commands/LegacyBudgetItemBatchShift.php index ca58e02a..c4566bf9 100644 --- a/app/Console/Commands/LegacyBudgetItemBatchShift.php +++ b/app/Console/Commands/LegacyBudgetItemBatchShift.php @@ -2,6 +2,8 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Facades\DB; use Illuminate\Console\Command; use Spatie\Regex\Regex; @@ -41,8 +43,8 @@ public function handle(): int $this->info('Transforming '.count($switch).' Legacy Titles'); - return \DB::transaction(function () use ($switch): int { - \Schema::disableForeignKeyConstraints(); + return DB::transaction(function () use ($switch): int { + Schema::disableForeignKeyConstraints(); foreach ($switch as [$oldId, $newId]) { $res = $this->call('legacy:budget-id-shift', [ 'old_id' => $oldId, @@ -54,7 +56,7 @@ public function handle(): int $this->fail("Failed subprocess $oldId->$newId. Aborting & Roling back..."); } } - \Schema::enableForeignKeyConstraints(); + Schema::enableForeignKeyConstraints(); return self::SUCCESS; }); diff --git a/app/Console/Commands/LegacyBudgetItemShift.php b/app/Console/Commands/LegacyBudgetItemShift.php index 98d3a53a..b51a52c9 100644 --- a/app/Console/Commands/LegacyBudgetItemShift.php +++ b/app/Console/Commands/LegacyBudgetItemShift.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\DB; use App\Models\Legacy\Booking; use App\Models\Legacy\LegacyBudgetItem; use App\Models\Legacy\ProjectPost; @@ -32,7 +33,7 @@ class LegacyBudgetItemShift extends Command */ public function handle(): int { - return \DB::transaction(function (): int { + return DB::transaction(function (): int { $old_id = $this->argument('old_id'); $new_id = $this->argument('new_id'); diff --git a/app/Console/Commands/LegacyDeleteBudgetPlan.php b/app/Console/Commands/LegacyDeleteBudgetPlan.php index 8bfdbdca..6b19362d 100644 --- a/app/Console/Commands/LegacyDeleteBudgetPlan.php +++ b/app/Console/Commands/LegacyDeleteBudgetPlan.php @@ -2,6 +2,8 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Facades\DB; use App\Models\Legacy\LegacyBudgetItem; use App\Models\Legacy\LegacyBudgetPlan; use Illuminate\Console\Command; @@ -36,12 +38,12 @@ public function handle(): void return; } - \DB::transaction(function () use ($hhp, $groups, $title): void { - \Schema::disableForeignKeyConstraints(); + DB::transaction(function () use ($hhp, $groups, $title): void { + Schema::disableForeignKeyConstraints(); $title->delete(); $groups->delete(); $hhp->delete(); - \Schema::enableForeignKeyConstraints(); + Schema::enableForeignKeyConstraints(); $this->info('Plan, Groups and Bugets are deleted successfully!'); }); diff --git a/app/Console/Commands/LegacyMigrateEncryption.php b/app/Console/Commands/LegacyMigrateEncryption.php index 2051eb7b..41d2aad9 100644 --- a/app/Console/Commands/LegacyMigrateEncryption.php +++ b/app/Console/Commands/LegacyMigrateEncryption.php @@ -2,6 +2,8 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Str; use App\Models\Legacy\ChatMessage; use App\Models\Legacy\Expense; use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException; @@ -51,13 +53,13 @@ public function handle(): int // old prefix $text = substr($text, strlen('$enc$')); $text = ChatHandler::legacyDecryptMessage($text, Env::get('CHAT_PRIVATE_KEY')); - $message->text = \Crypt::encryptString($text); + $message->text = Crypt::encryptString($text); $message->save(); $count++; } elseif ($message->type === -1) { // not used productive anymore, was "private message" $text = ChatHandler::legacyDecryptMessage($text, Env::get('CHAT_PRIVATE_KEY')); - $message->text = \Crypt::encryptString($text); + $message->text = Crypt::encryptString($text); $message->save(); $count++; } @@ -72,11 +74,11 @@ public function handle(): int Expense::all()->each(function ($expense) use (&$count): void { $cryptIban = $expense->getAttribute('zahlung_iban'); try { - \Crypt::decryptString($cryptIban); + Crypt::decryptString($cryptIban); } catch (DecryptException) { $iban = AuslagenHandler2::legacyDecryptStr($cryptIban); - $expense->setAttribute('zahlung_iban', \Crypt::encryptString($iban)); - $expense->etag = \Str::random(32); + $expense->setAttribute('zahlung_iban', Crypt::encryptString($iban)); + $expense->etag = Str::random(32); $expense->save(); $count++; } diff --git a/app/Console/Commands/LegacyMigrateFilesToStorage.php b/app/Console/Commands/LegacyMigrateFilesToStorage.php index c8c28bd2..39788838 100644 --- a/app/Console/Commands/LegacyMigrateFilesToStorage.php +++ b/app/Console/Commands/LegacyMigrateFilesToStorage.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\Storage; use App\Models\Legacy\ExpenseReceipt; use App\Models\Legacy\FileInfo; use Illuminate\Console\Command; @@ -39,8 +40,8 @@ public function handle(): void if (empty($data->diskpath)) { $data->diskpath = $path; } - if (! \Storage::has($path)) { - \Storage::put($path, $pdfData); + if (! Storage::has($path)) { + Storage::put($path, $pdfData); } if ($this->option('delete') === true) { $data->data = null; diff --git a/app/Console/Commands/StuFisHealth.php b/app/Console/Commands/StuFisHealth.php index 399c4ac4..52727668 100644 --- a/app/Console/Commands/StuFisHealth.php +++ b/app/Console/Commands/StuFisHealth.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use Illuminate\Support\Facades\DB; use Illuminate\Console\Command; class StuFisHealth extends Command @@ -27,7 +28,7 @@ public function handle(): void { $output = collect([ 'version' => config('stufis.version', ''), - 'database-prefix' => \DB::connection()->getConfig('prefix'), + 'database-prefix' => DB::connection()->getConfig('prefix'), ]); if ($this->option('json')) { $this->output->writeln(json_encode($output, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)); diff --git a/app/Exports/Datev/DatevExport.php b/app/Exports/Datev/DatevExport.php index 843dacea..4709f533 100644 --- a/app/Exports/Datev/DatevExport.php +++ b/app/Exports/Datev/DatevExport.php @@ -8,7 +8,7 @@ use App\Models\Legacy\Booking; use App\Models\Legacy\Expense; use App\Models\Legacy\FileInfo; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Date; diff --git a/app/Exports/Datev/DatevExportPreviewRow.php b/app/Exports/Datev/DatevExportPreviewRow.php index c5279e97..169b4c33 100644 --- a/app/Exports/Datev/DatevExportPreviewRow.php +++ b/app/Exports/Datev/DatevExportPreviewRow.php @@ -2,7 +2,7 @@ namespace App\Exports\Datev; -use Carbon\Carbon; +use Illuminate\Support\Carbon; /** * A single expense row for the DATEV export preview table — one expense = one ledger entry. diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 485a02f1..aa236fc5 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use Illuminate\Support\Facades\App; use App\Models\User; use App\Services\Auth\AuthService; use Illuminate\Http\RedirectResponse; @@ -19,7 +20,7 @@ public function login() public function callback(Request $request): RedirectResponse { - if (Auth::guest() && ! \App::runningUnitTests()) { + if (Auth::guest() && ! App::runningUnitTests()) { [$identifiers, $userAttributes] = $this->authService->userFromCallback($request); $user = User::updateOrCreate($identifiers, $userAttributes); diff --git a/app/Http/Controllers/Dev.php b/app/Http/Controllers/Dev.php index d92e3af9..d6932a32 100644 --- a/app/Http/Controllers/Dev.php +++ b/app/Http/Controllers/Dev.php @@ -2,15 +2,17 @@ namespace App\Http\Controllers; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\App; use App\Services\Auth\AuthService; class Dev extends Controller { public function groups() { - $groupsRaw = \App::get(AuthService::class)->userGroupsRaw(); - $groupMapping = \App::get(AuthService::class)->groupMapping(); - $groups = \Auth::user()?->getGroups(); + $groupsRaw = App::get(AuthService::class)->userGroupsRaw(); + $groupMapping = App::get(AuthService::class)->groupMapping(); + $groups = Auth::user()?->getGroups(); return view('components.dump', ['dump' => [ 'groups-raw' => $groupsRaw, diff --git a/app/Http/Controllers/Legacy/DeleteExpenses.php b/app/Http/Controllers/Legacy/DeleteExpenses.php index 5c80de76..0cdf32de 100644 --- a/app/Http/Controllers/Legacy/DeleteExpenses.php +++ b/app/Http/Controllers/Legacy/DeleteExpenses.php @@ -2,6 +2,8 @@ namespace App\Http\Controllers\Legacy; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use App\Models\Legacy\Expense; use App\Models\Legacy\ExpenseReceipt; @@ -18,17 +20,15 @@ public function __invoke(int $expense_id) // authorize user $userPerm = - \Auth::user()->can('budget-officer', User::class) - || $project->creator->id === \Auth::user()->id - || explode(';', (string) $expense->created)[1] === \Auth::user()->username; + Auth::user()->can('budget-officer', User::class) + || $project->creator->id === Auth::user()->id + || explode(';', (string) $expense->created)[1] === Auth::user()->username; // authorize state $deletableState = ! in_array(explode(';', (string) $expense->state)[0], ['instructed', 'booked'], true); - if ($userPerm === false || $deletableState === false) { - abort(403); - } + abort_if($userPerm === false || $deletableState === false, 403); // to make sure to delete everything and not only parts - \DB::beginTransaction(); + DB::beginTransaction(); $reciepts = $expense->receipts; $reciepts->each(function (ExpenseReceipt $receipt): void { // delete all posts @@ -49,9 +49,9 @@ public function __invoke(int $expense_id) // clean up storage if DB is successfully cleaned DB::afterCommit(function () use ($expense_id): void { - \Storage::deleteDirectory("auslagen/{$expense_id}/"); + Storage::deleteDirectory("auslagen/{$expense_id}/"); }); - \DB::commit(); + DB::commit(); return to_route('legacy.dashboard', ['sub' => 'mygremium']); } diff --git a/app/Http/Controllers/Legacy/DeleteProject.php b/app/Http/Controllers/Legacy/DeleteProject.php index f933c003..c0e31d7d 100644 --- a/app/Http/Controllers/Legacy/DeleteProject.php +++ b/app/Http/Controllers/Legacy/DeleteProject.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\Legacy; +use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use App\Models\Legacy\Project; use App\Models\User; @@ -13,13 +14,11 @@ public function __invoke(int $project_id) $project = Project::findOrFail($project_id); // authorize - $userPerm = \Auth::user()->can('budget-officer', User::class) - || $project->creator->id === \Auth::user()->id; + $userPerm = Auth::user()->can('budget-officer', User::class) + || $project->creator->id === Auth::user()->id; $dataPerm = $project->expenses()->count() === 0; - if ($userPerm === false || $dataPerm === false) { - abort(403); - } + abort_if($userPerm === false || $dataPerm === false, 403); // delete $project->posts()->delete(); diff --git a/app/Http/Controllers/Legacy/LegacyController.php b/app/Http/Controllers/Legacy/LegacyController.php index ef71dbbb..8a45b884 100644 --- a/app/Http/Controllers/Legacy/LegacyController.php +++ b/app/Http/Controllers/Legacy/LegacyController.php @@ -2,6 +2,8 @@ namespace App\Http\Controllers\Legacy; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Auth; use App\Exceptions\LegacyJsonException; use App\Exceptions\LegacyRedirectException; use App\Http\Controllers\Controller; @@ -83,7 +85,7 @@ private function resolveSectionTabs(Request $request): ?array ['Haushaltsverantwortliche*r', 'scale', 'legacy.todo.hv'], ['Kassenverantwortliche*r', 'calculator', 'legacy.todo.kv'], ]; - if (\Auth::user()->can('finance', \Auth::user())) { + if (Auth::user()->can('finance', Auth::user())) { $items[] = ['Überweisungen', 'banknotes', 'legacy.todo.kv.bank']; } @@ -172,7 +174,7 @@ public function belegePdf(int $project_id, int $auslagen_id, int $version, ?stri { // file was generated and requested by the iframe if ($file_name !== null) { - return \Storage::response( + return Storage::response( "auslagen/$auslagen_id/belege-pdf-v$version.pdf", $file_name ); @@ -199,7 +201,7 @@ public function zahlungsanweisungPdf(int $project_id, int $auslagen_id, int $ver { // file was generated and requested by the iframe call if ($file_name !== null) { - return \Storage::response( + return Storage::response( "/auslagen/$auslagen_id/zahlungsanweisung-v$version.pdf", $file_name ); @@ -225,8 +227,8 @@ public function zahlungsanweisungPdf(int $project_id, int $auslagen_id, int $ver public function deliverFile($auslagen_id, $fileHash, $fileName): StreamedResponse { $path = "/auslagen/$auslagen_id/$fileHash.pdf"; - if (\Storage::exists($path)) { - return \Storage::response($path, $fileName); + if (Storage::exists($path)) { + return Storage::response($path, $fileName); } throw new FileNotFoundException("Datei $path konnte nicht gefunden werden"); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 92db3638..769c3095 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use Illuminate\Support\Facades\Auth; use Closure; use Illuminate\Auth\Middleware\Authenticate as Middleware; use Illuminate\Http\Request; @@ -17,7 +18,7 @@ public function handle($request, Closure $next, ...$guards): Response $this->authenticate($request, $guards); // adds to parent: only user with the login or admin group pass - $groups = \Auth::user()->getGroups(); + $groups = Auth::user()->getGroups(); if ($groups->contains('login') || $groups->contains('admin')) { return $next($request); } diff --git a/app/Http/Middleware/VersionChangeNotification.php b/app/Http/Middleware/VersionChangeNotification.php index 54f102f8..875db213 100644 --- a/app/Http/Middleware/VersionChangeNotification.php +++ b/app/Http/Middleware/VersionChangeNotification.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use Illuminate\Support\Facades\Auth; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; @@ -16,7 +17,7 @@ class VersionChangeNotification */ public function handle(Request $request, Closure $next): Response { - if (($user = \Auth::user()) !== null) { + if (($user = Auth::user()) !== null) { $lastVersion = $user->version; if ($lastVersion !== config('stufis.version')) { Session::put('message.text', __('general.version_notification.text')); diff --git a/app/Listeners/LogModelChange.php b/app/Listeners/LogModelChange.php index e4ede994..047267ca 100644 --- a/app/Listeners/LogModelChange.php +++ b/app/Listeners/LogModelChange.php @@ -2,6 +2,7 @@ namespace App\Listeners; +use Illuminate\Support\Facades\Auth; use App\Events\UpdatingModel; use App\Models\Changelog; @@ -30,7 +31,7 @@ public function handle(UpdatingModel $modelChange): void 'type' => $model::class, 'type_id' => $model->getKey(), 'previous_data' => $changes, - 'user_id' => \Auth::user()->id, + 'user_id' => Auth::user()->id, ]); } } diff --git a/app/Models/BudgetItem.php b/app/Models/BudgetItem.php index e92400ea..c14745b5 100644 --- a/app/Models/BudgetItem.php +++ b/app/Models/BudgetItem.php @@ -125,7 +125,7 @@ public function budgetPlan(): BelongsTo public function orderedChildren(): HasMany { - return $this->hasMany(self::class, 'parent_id')->orderBy('position', 'asc'); + return $this->hasMany(self::class, 'parent_id')->orderBy('position'); } #[\Override] diff --git a/app/Models/BudgetPlan.php b/app/Models/BudgetPlan.php index d2626532..287cd540 100644 --- a/app/Models/BudgetPlan.php +++ b/app/Models/BudgetPlan.php @@ -4,7 +4,7 @@ use App\Models\Enums\BudgetPlanState; use App\Models\Enums\BudgetType; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Database\Factories\BudgetPlanFactory; use Eloquent; use Illuminate\Database\Eloquent\Builder; diff --git a/app/Models/Legacy/LegacyBudgetPlan.php b/app/Models/Legacy/LegacyBudgetPlan.php index 51c867e6..51071c19 100644 --- a/app/Models/Legacy/LegacyBudgetPlan.php +++ b/app/Models/Legacy/LegacyBudgetPlan.php @@ -2,7 +2,7 @@ namespace App\Models\Legacy; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; @@ -62,7 +62,7 @@ public function budgetItems(): HasManyThrough public static function latest(): \Eloquent|static { - return self::orderBy('id', 'desc')->first(); + return self::orderByDesc('id')->first(); } public static function findByDate(?Carbon $date = null): ?static diff --git a/app/Models/Legacy/Project.php b/app/Models/Legacy/Project.php index 3791127f..60fbadd4 100644 --- a/app/Models/Legacy/Project.php +++ b/app/Models/Legacy/Project.php @@ -7,7 +7,7 @@ use App\Models\Setting; use App\Models\User; use App\States\Project\ProjectState; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Cknow\Money\Money; use Database\Factories\Legacy\ProjectFactory; use Illuminate\Database\Eloquent\Builder; diff --git a/app/Services/Auth/LocalAuthService.php b/app/Services/Auth/LocalAuthService.php index 59816392..1e559fc2 100644 --- a/app/Services/Auth/LocalAuthService.php +++ b/app/Services/Auth/LocalAuthService.php @@ -2,6 +2,7 @@ namespace App\Services\Auth; +use Illuminate\Support\Facades\Auth; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Response; use Illuminate\Support\Collection; @@ -27,7 +28,7 @@ public function userFromCallback(Request $request): array #[\Override] public function userCommittees(): Collection { - return match (\Auth::user()->username) { + return match (Auth::user()->username) { 'user' => collect(['Students Council']), 'hhv', 'kv' => collect(['Financial Department']), 'revision' => collect(), @@ -48,7 +49,7 @@ public function allCommittees(): Collection #[\Override] public function userGroupsRaw(): Collection { - return match (\Auth::user()->username) { + return match (Auth::user()->username) { 'user-no-login' => collect(), 'user', 'external' => collect(['login']), 'hhv' => collect(['login', 'ref-finanzen', 'ref-finanzen-hv', 'ref-finanzen-belege']), diff --git a/app/Services/Auth/OidcAuthService.php b/app/Services/Auth/OidcAuthService.php index 78fdf8bc..264d1bf2 100644 --- a/app/Services/Auth/OidcAuthService.php +++ b/app/Services/Auth/OidcAuthService.php @@ -2,6 +2,7 @@ namespace App\Services\Auth; +use Illuminate\Support\Facades\Session; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Response; use Illuminate\Support\Collection; @@ -94,7 +95,7 @@ public function groupMapping(): Collection #[\Override] public function afterLogout(): RedirectResponse { - \Session::flush(); + Session::flush(); return redirect()->to(config('services.oidc.logout_url')); } diff --git a/app/Services/Auth/StumvAuthService.php b/app/Services/Auth/StumvAuthService.php index c4545971..20fc7824 100644 --- a/app/Services/Auth/StumvAuthService.php +++ b/app/Services/Auth/StumvAuthService.php @@ -2,6 +2,8 @@ namespace App\Services\Auth; +use Illuminate\Support\Facades\Session; +use Illuminate\Support\Facades\App; use GuzzleHttp\Client; use Http; use Illuminate\Http\Client\PendingRequest; @@ -34,7 +36,7 @@ public function userFromCallback(Request $request): array { $driver = Socialite::driver('stumv'); // if we have a local dev instance of stumv there is no need to verify ssl certs - if (\App::isLocal()) { + if (App::isLocal()) { $driver = $driver->setHttpClient(new Client(['verify' => false])); } $user = $driver->user(); @@ -71,13 +73,13 @@ public function userFromCallback(Request $request): array #[\Override] public function userCommittees(): Collection { - return \Session::remember('stumv.comittees', fn () => $this->api()->get('/api/my/committees')->collect()); + return Session::remember('stumv.comittees', fn () => $this->api()->get('/api/my/committees')->collect()); } #[\Override] public function userGroupsRaw(): Collection { - return \Session::remember('stumv.groups', fn () => $this->api()->get('/api/my/groups')->collect()); + return Session::remember('stumv.groups', fn () => $this->api()->get('/api/my/groups')->collect()); } #[\Override] @@ -89,7 +91,7 @@ public function groupMapping(): Collection #[\Override] public function afterLogout() { - \Session::flush(); + Session::flush(); return redirect(to: config('services.stumv.host'). config('services.stumv.logout_path') diff --git a/database/factories/BudgetPlanFactory.php b/database/factories/BudgetPlanFactory.php index 671b81e0..778ee7ac 100644 --- a/database/factories/BudgetPlanFactory.php +++ b/database/factories/BudgetPlanFactory.php @@ -4,7 +4,7 @@ use App\Models\BudgetItem; use App\Models\Enums\BudgetPlanState; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; class BudgetPlanFactory extends Factory diff --git a/database/factories/Legacy/BankTransactionFactory.php b/database/factories/Legacy/BankTransactionFactory.php index ce63c01c..541c6588 100644 --- a/database/factories/Legacy/BankTransactionFactory.php +++ b/database/factories/Legacy/BankTransactionFactory.php @@ -4,7 +4,7 @@ use App\Models\Legacy\BankAccount; use App\Models\Legacy\BankTransaction; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Eloquent\Factories\Factory; class BankTransactionFactory extends Factory diff --git a/database/migrations/2024_07_02_154915_single_keys_for_eloquent.php b/database/migrations/2024_07_02_154915_single_keys_for_eloquent.php index 4d906915..c859d406 100644 --- a/database/migrations/2024_07_02_154915_single_keys_for_eloquent.php +++ b/database/migrations/2024_07_02_154915_single_keys_for_eloquent.php @@ -25,7 +25,7 @@ public function up(): void // schema changes are not transaction-able DB::transaction(function () { - $lastId = BankAccount::orderBy('id', 'desc') + $lastId = BankAccount::orderByDesc('id') ->limit(1)->pluck('id')->first(default: 0); $newId = $lastId + 1; // migrate the old negative keys diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 765d3f79..67467c61 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -2,6 +2,7 @@ namespace Database\Seeders; +use Illuminate\Support\Facades\App; use Illuminate\Database\Seeder; use Illuminate\Foundation\Testing\WithFaker; @@ -17,18 +18,18 @@ public function run(): void // \App\Models\User::factory(10)->create(); // BudgetPlan::factory(5)->populate()->create(); - if (\App::runningUnitTests()) { + if (App::runningUnitTests()) { $this->call(DemoDataSeeder::class); $this->call(LocalSeeder::class); $this->call(TestSeeder::class); } - if (\App::isLocal()) { + if (App::isLocal()) { $this->call(DemoDataSeeder::class); $this->call(LocalSeeder::class); } - if (\App::isProduction()) { + if (App::isProduction()) { if (config('stufis.realm') === 'demo') { $this->call(DemoDataSeeder::class); } diff --git a/database/seeders/DemoDataSeeder.php b/database/seeders/DemoDataSeeder.php index 9a00ea0f..3e7ff72a 100644 --- a/database/seeders/DemoDataSeeder.php +++ b/database/seeders/DemoDataSeeder.php @@ -2,12 +2,12 @@ namespace Database\Seeders; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Process; -use Storage; +use Illuminate\Support\Facades\Storage; class DemoDataSeeder extends Seeder { @@ -16,9 +16,7 @@ class DemoDataSeeder extends Seeder */ public function run(): void { - if (App::isProduction() && config('stufis.realm') !== 'demo') { - throw new \InvalidArgumentException('Realm is not demo but we are in production, aborting for your safety'); - } + throw_if(App::isProduction() && config('stufis.realm') !== 'demo', new \InvalidArgumentException('Realm is not demo but we are in production, aborting for your safety')); $today = Carbon::today(); diff --git a/database/seeders/DevFeatureSeeder.php b/database/seeders/DevFeatureSeeder.php index 3fa8d76e..a7e1bb8b 100644 --- a/database/seeders/DevFeatureSeeder.php +++ b/database/seeders/DevFeatureSeeder.php @@ -3,7 +3,7 @@ namespace Database\Seeders; use App\Models\FiscalYear; -use Carbon\Carbon; +use Illuminate\Support\Carbon; use Illuminate\Database\Seeder; class DevFeatureSeeder extends Seeder diff --git a/database/seeders/LocalSeeder.php b/database/seeders/LocalSeeder.php index 4f60fa91..986626d7 100644 --- a/database/seeders/LocalSeeder.php +++ b/database/seeders/LocalSeeder.php @@ -2,34 +2,35 @@ namespace Database\Seeders; +use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class LocalSeeder extends Seeder { public function run(): void { - \DB::table('user')->insert([ + DB::table('user')->insert([ 'name' => 'Demo User', 'username' => 'user-no-login', 'email' => 'user@example.com', 'provider' => 'local', 'provider_uid' => 'user', ]); - \DB::table('user')->insert([ + DB::table('user')->insert([ 'name' => 'Demo User', 'username' => 'user', 'email' => 'user@example.com', 'provider' => 'local', 'provider_uid' => 'user', ]); - \DB::table('user')->insert([ + DB::table('user')->insert([ 'name' => 'Demo Cash Officer', 'username' => 'kv', 'email' => 'kv@example.com', 'provider' => 'local', 'provider_uid' => 'kv', ]); - \DB::table('user')->insert([ + DB::table('user')->insert([ 'name' => 'Demo Budget Officer', 'username' => 'hhv', 'email' => 'hhv@example.com', @@ -37,7 +38,7 @@ public function run(): void 'provider_uid' => 'hhv', ]); - \DB::table('user')->insert([ + DB::table('user')->insert([ 'name' => 'The Admin', 'username' => 'admin', 'email' => 'admin@example.com', diff --git a/database/seeders/ProductionSeeder.php b/database/seeders/ProductionSeeder.php index d854d3fb..a7879938 100644 --- a/database/seeders/ProductionSeeder.php +++ b/database/seeders/ProductionSeeder.php @@ -2,13 +2,14 @@ namespace Database\Seeders; +use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class ProductionSeeder extends Seeder { public function run(): void { - \DB::table('konto_type')->insert([ + DB::table('konto_type')->insert([ 'name' => 'Kasse', 'short' => 'K', 'manually_enterable' => true, diff --git a/legacy/lib/booking/BookingHandler.php b/legacy/lib/booking/BookingHandler.php index 3c62e2e5..ede9b2ad 100644 --- a/legacy/lib/booking/BookingHandler.php +++ b/legacy/lib/booking/BookingHandler.php @@ -56,9 +56,7 @@ private function setBookingTabs($active, $active_hhp_id): void private function renderCSV(): void { - if (! isset($this->routeInfo['hhp-id'])) { - throw new LegacyDieException(400, 'hhp-id nicht gesetzt'); - } + throw_unless(isset($this->routeInfo['hhp-id']), new LegacyDieException(400, 'hhp-id nicht gesetzt')); [$kontoTypes, $data] = $this->fetchBookingHistoryDataFromDB($this->routeInfo['hhp-id']); $csvData = []; $header = [ @@ -110,17 +108,13 @@ private function renderCSV(): void private function renderFullBookingZip(): void { - if (! isset($this->routeInfo['hhp-id'])) { - throw new LegacyDieException(400, 'hhp-id nicht gesetzt'); - } + throw_unless(isset($this->routeInfo['hhp-id']), new LegacyDieException(400, 'hhp-id nicht gesetzt')); $zip = new ZipArchive; $zipFileName = 'HHA.zip'; $zipFilePath = tempnam(sys_get_temp_dir(), 'HHA'); - if (($ret = $zip->open($zipFilePath, ZipArchive::OVERWRITE)) !== true) { - throw new LegacyDieException(500, 'Zip kann nicht erstellt werden.', 'ErrorCode: '.$ret); - } + throw_if(($ret = $zip->open($zipFilePath, ZipArchive::OVERWRITE)) !== true, new LegacyDieException(500, 'Zip kann nicht erstellt werden.', 'ErrorCode: '.$ret)); [$kontoTypes, $data] = $this->fetchBookingHistoryDataFromDB( $this->routeInfo['hhp-id'], diff --git a/legacy/lib/booking/HHPHandler.php b/legacy/lib/booking/HHPHandler.php index 592ad8a6..0e6cb7ba 100644 --- a/legacy/lib/booking/HHPHandler.php +++ b/legacy/lib/booking/HHPHandler.php @@ -456,11 +456,9 @@ private function renderTitelDetails(): void ['titel_nr', 'titel_name'], ['id' => $titel_id] ); - if (count($titel) === 0) { - throw new LegacyDieException(404, "Titel $titel_id kann nicht gefunden werden"); - } else { - $titel = $titel[0]; - } + throw_if(count($titel) === 0, new LegacyDieException(404, "Titel $titel_id kann nicht gefunden werden")); + + $titel = $titel[0]; $this->renderHeadline( 'HHP seit '.$this->formatDateToMonthYear( $hhp['von'] diff --git a/legacy/lib/booking/konto/FintsConnectionHandler.php b/legacy/lib/booking/konto/FintsConnectionHandler.php index 481797e3..f9f4345e 100644 --- a/legacy/lib/booking/konto/FintsConnectionHandler.php +++ b/legacy/lib/booking/konto/FintsConnectionHandler.php @@ -87,9 +87,7 @@ public function login(): bool // resume execution if any $resumableAction = $this->resumableAction(); if ($resumableAction instanceof DialogInitialization) { - if (! $resumableAction->isDone()) { - throw new NeedsTanException($resumableAction, 'Tan wird zum Login benötigt'); - } + throw_unless($resumableAction->isDone(), new NeedsTanException($resumableAction, 'Tan wird zum Login benötigt')); $this->setCache('logged-in', true); $this->saveAction(); @@ -200,9 +198,7 @@ public function getSepaAccount($iban): SEPAAccount if (count($filtered) > 1) { HTMLPageRenderer::addFlash(BT::TYPE_WARNING, 'Es existieren mehrere Kontos mit der selben IBAN, bitte kontaktiere einen Administrator', $filtered); } - if (count($filtered) === 0) { - throw new InvalidArgumentException("Iban $iban nicht vorhanden"); - } + throw_if(count($filtered) === 0, new InvalidArgumentException("Iban $iban nicht vorhanden")); return array_values($filtered)[0]; } @@ -219,9 +215,7 @@ public function getSepaAccounts(): array } $action = $this->resumableAction(); if ($action instanceof GetSEPAAccounts) { - if (! $action->isDone()) { - throw new NeedsTanException($action); - } + throw_unless($action->isDone(), new NeedsTanException($action)); } else { $this->logger->info('Fetch SEPA Accounts', ['credId' => $this->credentialId]); $action = GetSEPAAccounts::create(); @@ -335,9 +329,7 @@ public static function load(int $credentialId): self throw new LegacyDieException(500, 'found multiple DB entries'); } - if (! self::hasPassword($credentialId)) { - throw new LegacyDieException(400, "Bank Passwort für Credentials $credentialId benötigt"); - } + throw_unless(self::hasPassword($credentialId), new LegacyDieException(400, "Bank Passwort für Credentials $credentialId benötigt")); $username = $res['bank_username']; $credentials = Credentials::create($username, self::getPassword($credentialId)); @@ -370,10 +362,8 @@ private function execute(BaseAction $action): void try { $this->finTs->execute($action); $this->saveAction($action); - if ($action->needsTan()) { - // TODO decoupled tan stuff here - throw new NeedsTanException($action); - } + // TODO decoupled tan stuff here + throw_if($action->needsTan(), new NeedsTanException($action)); } catch (CurlException|ServerException $e) { $this->logger->error('Aktion nicht ausgeführt', ['exception' => $e]); ErrorHandler::handleException($e, 'Verbindung zur Bank gestört - Aktion nicht ausgeführt'); @@ -442,9 +432,7 @@ public function setTanMode(int $tanModeId, ?string $tanMediumName = null): bool { try { $tanMode = $this->finTs->getTanModes()[$tanModeId]; - if ($tanMediumName === null && $tanMode->needsTanMedium()) { - throw new InvalidArgumentException('Tan Medium wird benötigt'); - } + throw_if($tanMediumName === null && $tanMode->needsTanMedium(), new InvalidArgumentException('Tan Medium wird benötigt')); $this->saveAction(); $this->logger->info('Set TAN Mode', ['credId' => $this->credentialId, 'tanMode' => $tanModeId, 'tanMedium' => $tanMediumName]); } catch (CurlException|ServerException $e) { diff --git a/legacy/lib/booking/konto/FintsController.php b/legacy/lib/booking/konto/FintsController.php index f3ac4623..f267616c 100644 --- a/legacy/lib/booking/konto/FintsController.php +++ b/legacy/lib/booking/konto/FintsController.php @@ -2,6 +2,7 @@ namespace booking\konto; +use Illuminate\Support\Facades\Auth; use App\Exceptions\LegacyRedirectException; use booking\konto\tan\FlickerGenerator; use Fhp\Model\StatementOfAccount\Statement; @@ -105,7 +106,7 @@ protected function actionViewCredentials(): void 'tan_mode_name', 'tan_medium_name', ], - ['owner_id' => \Auth::user()->id], + ['owner_id' => Auth::user()->id], [['type' => 'inner', 'table' => 'konto_bank', 'on' => ['konto_bank.id', 'konto_credentials.bank_id']]] ); echo HtmlButton::make() @@ -270,9 +271,7 @@ protected function actionLogin(): void if (FintsConnectionHandler::hasPassword($credentialId)) { // pw set $success = $this->fintsHandler->login(); // throws if Tan needed - if ($success) { - throw new LegacyRedirectException(redirect()->route('legacy.konto.credentials')); - } + throw_if($success, new LegacyRedirectException(redirect()->route('legacy.konto.credentials'))); } // if no pw or wrong one if (! FintsConnectionHandler::hasPassword($credentialId)) { diff --git a/legacy/lib/booking/konto/tan/DataElement.php b/legacy/lib/booking/konto/tan/DataElement.php index 11946ea6..b84ffccb 100644 --- a/legacy/lib/booking/konto/tan/DataElement.php +++ b/legacy/lib/booking/konto/tan/DataElement.php @@ -25,9 +25,7 @@ public static function parseNextBlock($challenge): array } $length = (int) substr($challenge, 0, 2); $data = substr($challenge, 2, $length); - if (strlen($data) !== $length) { - throw new InvalidArgumentException('Parsing went wromg'); - } + throw_if(strlen($data) !== $length, new InvalidArgumentException('Parsing went wromg')); $rest = substr($challenge, 2 + $length); return [$rest, new self($data)]; diff --git a/legacy/lib/booking/konto/tan/FlickerGenerator.php b/legacy/lib/booking/konto/tan/FlickerGenerator.php index fb14b6e8..789a183e 100644 --- a/legacy/lib/booking/konto/tan/FlickerGenerator.php +++ b/legacy/lib/booking/konto/tan/FlickerGenerator.php @@ -28,18 +28,14 @@ private function parseChallenge(): void // length of whole challenge (without lc) max 255 | encoding: base 10 $lc = (int) substr($reducedChallenge, 0, 3); $reducedChallenge = substr($reducedChallenge, 3); - if (strlen($reducedChallenge) !== $lc) { - throw new \InvalidArgumentException('Wrong length of TAN Challenge - only Version 1.4 supported'); - } + throw_if(strlen($reducedChallenge) !== $lc, new \InvalidArgumentException('Wrong length of TAN Challenge - only Version 1.4 supported')); [$reducedChallenge, $this->startCode] = StartCode::parseNextBlock($reducedChallenge); [$reducedChallenge, $this->de1] = DataElement::parseNextBlock($reducedChallenge); [$reducedChallenge, $this->de2] = DataElement::parseNextBlock($reducedChallenge); [$reducedChallenge, $this->de3] = DataElement::parseNextBlock($reducedChallenge); - if (! empty($reducedChallenge)) { - throw new \InvalidArgumentException("Challenge has unexpected ending $reducedChallenge"); - } + throw_unless(empty($reducedChallenge), new \InvalidArgumentException("Challenge has unexpected ending $reducedChallenge")); } private function calcXorChecksum(): string diff --git a/legacy/lib/booking/konto/tan/StartCode.php b/legacy/lib/booking/konto/tan/StartCode.php index 0fbf88ed..3d8871ad 100644 --- a/legacy/lib/booking/konto/tan/StartCode.php +++ b/legacy/lib/booking/konto/tan/StartCode.php @@ -26,9 +26,7 @@ public static function parseNextBlock($challenge): array public function __construct(array $ctrlBytes, string $data) { - if ($ctrlBytes !== ['01']) { - throw new \InvalidArgumentException('Other versions then 1.4 are not supported'); - } + throw_if($ctrlBytes !== ['01'], new \InvalidArgumentException('Other versions then 1.4 are not supported')); parent::__construct($data); $this->controlBytes = $ctrlBytes; $this->headerHighBit = '1'; diff --git a/legacy/lib/forms/RestHandler.php b/legacy/lib/forms/RestHandler.php index accb64d4..7a38e67f 100644 --- a/legacy/lib/forms/RestHandler.php +++ b/legacy/lib/forms/RestHandler.php @@ -19,6 +19,7 @@ namespace forms; +use Illuminate\Support\Facades\App; use App\Exceptions\LegacyDieException; use App\Models\Legacy\BankTransaction; use App\Models\Legacy\LegacyBudgetPlan; @@ -44,10 +45,8 @@ class RestHandler extends EscFunc public function handlePost(?array $routeInfo = null): void { - if (! \App::runningUnitTests()) { - if (! isset($_POST['nonce']) || $_POST['nonce'] !== csrf_token() || isset($_POST['nononce'])) { - throw new LegacyDieException(400, 'Das Formular ist nicht gültig, bitte lade die Seite neu'); - } + if (! App::runningUnitTests()) { + throw_if(! isset($_POST['nonce']) || $_POST['nonce'] !== csrf_token() || isset($_POST['nononce']), new LegacyDieException(400, 'Das Formular ist nicht gültig, bitte lade die Seite neu')); } unset($_POST['nonce']); @@ -187,7 +186,7 @@ public function saveNewKasseEntry(): void DBConnector::getInstance()->dbInsert('konto', $fields); } else { $last = BankTransaction::where('konto_id', '=', $fields['konto_id']) - ->orderBy('id', 'desc') + ->orderByDesc('id') ->first()?->toArray(); if (abs($last['saldo'] + $fields['value'] - $fields['saldo']) < 0.01) { @@ -769,11 +768,9 @@ private function updateKonto($routeInfo): void $auth->requireGroup('ref-finanzen-kv'); $ret = true; - if (! DBConnector::getInstance()->dbBegin()) { - throw new LegacyDieException(500, + throw_unless(DBConnector::getInstance()->dbBegin(), new LegacyDieException(500, 'Kann keine Verbindung zur SQL-Datenbank aufbauen. Bitte versuche es später erneut!' - ); - } + )); [$success, $msg_xmlrpc, $allZahlungen] = HibiscusXMLRPCConnector::getInstance()->fetchAllUmsatz(); if ($success === false) { diff --git a/legacy/lib/forms/projekte/ProjektHandler.php b/legacy/lib/forms/projekte/ProjektHandler.php index 486462cb..a12c6ccd 100644 --- a/legacy/lib/forms/projekte/ProjektHandler.php +++ b/legacy/lib/forms/projekte/ProjektHandler.php @@ -2,6 +2,7 @@ namespace forms\projekte; +use Illuminate\Support\Facades\Auth; use App\Exceptions\LegacyDieException; use App\Models\Legacy\Project; use App\States\Project\ProjectState; @@ -17,9 +18,7 @@ class ProjektHandler public function __construct($pathInfo) { self::initStaticVars(); - if (! isset($pathInfo['action'])) { - throw new LegacyDieException(400, 'Aktion nicht gesetzt'); - } + throw_unless(isset($pathInfo['action']), new LegacyDieException(400, 'Aktion nicht gesetzt')); $this->action = $pathInfo['action']; if ($this->action === 'create' || ! isset($pathInfo['pid'])) { $this->data = self::$emptyData; @@ -69,6 +68,6 @@ public static function getStateStringFromName(string $statename) public function isOwner(): bool { - return isset($this->data['creator_id']) && \Auth::user()->id === $this->data['creator_id']; + return isset($this->data['creator_id']) && Auth::user()->id === $this->data['creator_id']; } } diff --git a/legacy/lib/forms/projekte/StateHandler.php b/legacy/lib/forms/projekte/StateHandler.php index ba0c08ba..e232d50f 100644 --- a/legacy/lib/forms/projekte/StateHandler.php +++ b/legacy/lib/forms/projekte/StateHandler.php @@ -54,9 +54,7 @@ public function __construct($parentTableName, $allStates, $transitions, $validat { $this->owners = $owners; $this->parentTableName = $parentTableName; - if (! is_array($allStates) || ! is_array($transitions)) { - throw new InvalidArgumentException('Keine Arrays in States / Transitions übergeben!'); - } + throw_if(! is_array($allStates) || ! is_array($transitions), new InvalidArgumentException('Keine Arrays in States / Transitions übergeben!')); if ($start === null || empty($start)) { if (isset($allStates['draft'])) { @@ -84,9 +82,7 @@ public function __construct($parentTableName, $allStates, $transitions, $validat } elseif (! is_callable($postTransitionHooks[$state])) { throw new InvalidArgumentException("Validator zu $state ist keine Funktion!"); } - if (! isset($transitions[$state])) { - throw new InvalidArgumentException("Cannot find state '$state' in \$transition array as key"); - } + throw_unless(isset($transitions[$state]), new InvalidArgumentException("Cannot find state '$state' in \$transition array as key")); } $this->transitions = $transitions; $this->validations = $validations; @@ -107,15 +103,9 @@ public function getStates(): array */ public function transitionTo($newState) { - if (! $this->isExitingState($newState)) { - throw new IllegalStateException("$newState nicht bekannt!"); - } - if (! $this->isTransitionableTo($newState)) { - throw new IllegalTransitionException("$this->actualState nicht in $newState überführbar - Daten fehlen!"); - } - if (! $this->isAllowedToTransitionTo($newState)) { - throw new IllegalTransitionException("$this->actualState nicht in $newState überführbar - nicht die passenden Rechte!"); - } + throw_unless($this->isExitingState($newState), new IllegalStateException("$newState nicht bekannt!")); + throw_unless($this->isTransitionableTo($newState), new IllegalTransitionException("$this->actualState nicht in $newState überführbar - Daten fehlen!")); + throw_unless($this->isAllowedToTransitionTo($newState), new IllegalTransitionException("$this->actualState nicht in $newState überführbar - nicht die passenden Rechte!")); $oldState = $this->actualState; $this->actualState = $newState; if (isset($this->postTransitionHooks[$oldState])) { diff --git a/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php b/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php index 2348e01a..c448bc72 100644 --- a/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php +++ b/legacy/lib/forms/projekte/auslagen/AuslagenHandler2.php @@ -2,6 +2,9 @@ namespace forms\projekte\auslagen; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Str; use App\Exceptions\LegacyDieException; use App\Models\LegalBasis; use Exception; @@ -735,7 +738,7 @@ public function isOwner(): bool $owner = explode(';', $this->auslagen_data['created']); $owner = $owner[1]; - return \Auth::user()->username === $owner; + return Auth::user()->username === $owner; } /** @@ -1118,7 +1121,7 @@ private function post_createupdate(): void 'last_change' => (string) ($newInfo['date']), 'last_change_by' => "{$newInfo['user']};{$newInfo['realname']}", 'version' => (int) $this->auslagen_data['version'] + 1, - 'etag' => \Str::random(32), + 'etag' => Str::random(32), ]; // insert/update in db if ($this->auslagen_data['id']) { @@ -1368,7 +1371,7 @@ private function post_filedelete(): void 'last_change' => ($newInfo['date']), 'last_change_by' => "{$newInfo['user']};{$newInfo['realname']}", 'version' => (int) $this->auslagen_data['version'] + 1, - 'etag' => \Str::random(32), + 'etag' => Str::random(32), ] ); // remove from laravell storage @@ -1482,7 +1485,7 @@ public function state_change(string $newState, string $etag): bool try { $set = [ 'version' => $this->auslagen_data['version'] + 1, - 'etag' => \Str::random(32), + 'etag' => Str::random(32), ]; } catch (Exception $e) { return false; @@ -1559,7 +1562,7 @@ public function generate_belege_pdf(): void { $filePath = "/auslagen/{$this->auslagen_id}/belege-pdf-v{$this->auslagen_data['version']}.pdf"; // nothing to do if this version of the file already exists - if (\Storage::exists($filePath)) { + if (Storage::exists($filePath)) { return; } // clean up old versions of the summary to make sure there are no leftovers from deleted files @@ -1588,7 +1591,7 @@ public function generate_belege_pdf(): void // belegPage macro then renders just the cover sheet to staple the original onto, // instead of dereferencing a null file. Same for a file missing on disk. $files[$key.'.pdf'] = ($beleg['file'] - ? \Storage::get("auslagen/{$this->auslagen_id}/{$beleg['file']['hashname']}.pdf") + ? Storage::get("auslagen/{$this->auslagen_id}/{$beleg['file']['hashname']}.pdf") : null) ?? ''; } $tex = new LatexGenerator; @@ -1622,7 +1625,7 @@ public function generate_belege_pdf(): void 'belegeFiles' => $belegeFiles, ], $files); if ($pdf !== null) { - \Storage::put($filePath, $pdf); + Storage::put($filePath, $pdf); return; } @@ -1632,7 +1635,7 @@ public function generate_belege_pdf(): void public function generate_zahlungsanweisung_pdf(): void { $fileName = "/auslagen/{$this->auslagen_id}/zahlungsanweisung-v{$this->auslagen_data['version']}.pdf"; - if (\Storage::exists($fileName)) { + if (Storage::exists($fileName)) { return; } @@ -1708,7 +1711,7 @@ public function generate_zahlungsanweisung_pdf(): void ]); if ($pdf !== null) { - \Storage::put($fileName, $pdf); + Storage::put($fileName, $pdf); return; } @@ -1752,9 +1755,7 @@ public static function legacyDecryptStr(string $str): string */ public function render(): void { - if ($this->error) { - throw new LegacyDieException(404, $this->error); - } + throw_if($this->error, new LegacyDieException(404, $this->error)); $this->renderAuslagenerstattung(); } @@ -2290,9 +2291,7 @@ private function _render_beleg_sums(float $in, float $out, $label = ''): void */ public function render_beleg_container(array $belege, bool $editable = true, string $label = ''): void { - if (! isset($this->projekt_data['posten'])) { - abort(420, __('errors.project.no-budgets')); - } + abort_unless(isset($this->projekt_data['posten']), 420, __('errors.project.no-budgets')); if ($label) { echo ''; } ?> diff --git a/legacy/lib/framework/ArrayHelper.php b/legacy/lib/framework/ArrayHelper.php index 302f3cee..02c2891f 100644 --- a/legacy/lib/framework/ArrayHelper.php +++ b/legacy/lib/framework/ArrayHelper.php @@ -57,9 +57,7 @@ public static function convolve_keys(array $a, string $delimiter = ':'): array public static function remove(array &$array, int|string $key): mixed { - if (! isset($array[$key])) { - throw new \InvalidArgumentException('Key not found'); - } + throw_unless(isset($array[$key]), new \InvalidArgumentException('Key not found')); $el = $array[$key]; unset($array[$key]); diff --git a/legacy/lib/framework/CryptoHandler.php b/legacy/lib/framework/CryptoHandler.php index 6629c108..509a8482 100644 --- a/legacy/lib/framework/CryptoHandler.php +++ b/legacy/lib/framework/CryptoHandler.php @@ -62,9 +62,7 @@ private function __construct() {} */ public static function generateRandomString($length): ?string { - if (! is_int($length)) { - throw new \Exception('Invalid argument type. Integer expected.'); - } + throw_unless(is_int($length), new \Exception('Invalid argument type. Integer expected.')); return bin2hex(random_bytes($length)); } diff --git a/legacy/lib/framework/DBConnector.php b/legacy/lib/framework/DBConnector.php index 62382a05..49eaa8ef 100644 --- a/legacy/lib/framework/DBConnector.php +++ b/legacy/lib/framework/DBConnector.php @@ -2,6 +2,7 @@ namespace framework; +use Illuminate\Support\Facades\Auth; use App\Exceptions\LegacyDieException; use framework\render\HTMLPageRenderer; use Illuminate\Support\Facades\DB; @@ -575,7 +576,7 @@ public function getUser(): array return $this->user; } - $user = \Auth::user()?->toArray(); + $user = Auth::user()?->toArray(); $user['fullname'] = $user['name']; $this->user = $user; @@ -636,9 +637,7 @@ public function dbFetchAll( } foreach ($tables as $table) { - if (! isset($this->scheme[$table])) { - throw new LegacyDieException(500, "Unkown table $table"); - } + throw_unless(isset($this->scheme[$table]), new LegacyDieException(500, "Unkown table $table")); } // fill with everything if empty @@ -680,64 +679,48 @@ public function dbFetchAll( // check join $validJoinOnOperators = ['=', '<', '>', '<>', '<=', '>=']; foreach (array_keys($joins) as $nr) { - if (! isset($joins[$nr]['table'])) { - throw new LegacyDieException(500, "no Jointable set in '".$nr."' use !"); - } elseif (! array_key_exists($joins[$nr]['table'], $this->scheme)) { - throw new LegacyDieException(500, 'Unknown Table '.$joins[$nr]['table']); - } elseif (isset($joins[$nr]['type']) && ! in_array( + throw_unless(isset($joins[$nr]['table']), new LegacyDieException(500, "no Jointable set in '".$nr."' use !")); + + throw_unless(array_key_exists($joins[$nr]['table'], $this->scheme), new LegacyDieException(500, 'Unknown Table '.$joins[$nr]['table'])); + + throw_if(isset($joins[$nr]['type']) && ! in_array( strtolower($joins[$nr]['type']), ['inner', 'left', 'natural', 'right'] - )) { - throw new LegacyDieException(500, 'Unknown Join type '.$joins[$nr]['type']); - } + ), new LegacyDieException(500, 'Unknown Join type '.$joins[$nr]['type'])); if (! isset($joins[$nr]['on'])) { $joins[$nr]['on'] = []; } - if (! is_array($joins[$nr]['on'])) { - throw new LegacyDieException(500, "on '{$joins[$nr]['on']}' has to be an array!"); - } + throw_unless(is_array($joins[$nr]['on']), new LegacyDieException(500, "on '{$joins[$nr]['on']}' has to be an array!")); if (count($joins[$nr]['on']) === 2 && ! is_array($joins[$nr]['on'][0])) { $joins[$nr]['on'] = [$joins[$nr]['on']]; // if only 1 "on" set bring it into an array-form } foreach ($joins[$nr]['on'] as $pair) { - if (! is_array($pair)) { - throw new LegacyDieException(500, "Join on '$pair' is not an array"); - } - if (count($pair) !== 2) { - throw new LegacyDieException(500, 'unvalid joinon pair:'.implode(', ', $pair)); - } + throw_unless(is_array($pair), new LegacyDieException(500, "Join on '$pair' is not an array")); + throw_if(count($pair) !== 2, new LegacyDieException(500, 'unvalid joinon pair:'.implode(', ', $pair))); } if (isset($joins[$nr]['operator'])) { if (! is_array($joins[$nr]['operator'])) { $joins[$nr]['operator'] = [$joins[$nr]['operator']]; } foreach ($joins[$nr]['operator'] as $op) { - if (! in_array($op, $validJoinOnOperators, true)) { - throw new LegacyDieException(500, "unallowed join operator '$op' in {$nr}th join"); - } + throw_unless(in_array($op, $validJoinOnOperators, true), new LegacyDieException(500, "unallowed join operator '$op' in {$nr}th join")); } } else { $joins[$nr]['operator'] = array_fill(0, count($joins[$nr]['on']), '='); } - if (count($joins[$nr]['on']) !== count($joins[$nr]['operator'])) { - throw new LegacyDieException(500, + throw_if(count($joins[$nr]['on']) !== count($joins[$nr]['operator']), new LegacyDieException(500, 'not same amount of on-pairs('.count($joins[$nr]['on']).') and operators ('.count( $joins[$nr]['operator'] ).')!' - ); - } + )); } foreach ($sort as $field => $value) { - if (! in_array($field, $this->validFields, true)) { - throw new LegacyDieException(500, "Unkown column $field in ORDER"); - } + throw_unless(in_array($field, $this->validFields, true), new LegacyDieException(500, "Unkown column $field in ORDER")); } foreach ($groupBy as $field) { - if (! in_array($field, $this->validFields, true)) { - throw new LegacyDieException(500, "Unkown column $field in GROUP"); - } + throw_unless(in_array($field, $this->validFields, true), new LegacyDieException(500, "Unkown column $field in GROUP")); } // @@ -896,9 +879,7 @@ private function buildWhereSql($where): array } foreach ($where as $whereGroup) { foreach ($whereGroup as $field => $value) { - if (! in_array($field, $this->validFields, true)) { - throw new LegacyDieException(500, "Unkown column $field in WHERE"); - } + throw_unless(in_array($field, $this->validFields, true), new LegacyDieException(500, "Unkown column $field in WHERE")); } } $w = []; @@ -928,9 +909,7 @@ private function buildWhereSql($where): array $k = $this->dbPrefix.$k; } if (is_array($v)) { - if (! in_array(strtolower($v[0]), $validWhereOperators)) { - throw new LegacyDieException(500, "Unknown where operator $v[0]"); - } + throw_unless(in_array(strtolower($v[0]), $validWhereOperators), new LegacyDieException(500, "Unknown where operator $v[0]")); if (is_array($v[1])) { switch (strtolower($v[0])) { case 'not in': @@ -940,9 +919,7 @@ private function buildWhereSql($where): array break; case 'between': $wg[] = $this->quoteIdent($k)." $v[0] ? AND ?"; - if (count($v[1]) !== 2) { - throw new LegacyDieException(500, 'To many values for '.$v[0]); - } + throw_if(count($v[1]) !== 2, new LegacyDieException(500, 'To many values for '.$v[0])); break; default: throw new LegacyDieException(500, 'unknown identifier '.$v[0]); @@ -1023,9 +1000,7 @@ private function quoteIdent(array|string $field, $aggregateConst = 0): array|str */ public function dbInsert(string $table, array $fields): string { - if (! isset($this->scheme[$table])) { - throw new LegacyDieException(500, "Unkown table $table"); - } + throw_unless(isset($this->scheme[$table]), new LegacyDieException(500, "Unkown table $table")); // if (isset($fields["id"])) unset($fields["id"]); $fields = array_intersect_key($fields, $this->scheme[$table]); @@ -1058,9 +1033,7 @@ public function dbInsert(string $table, array $fields): string */ public function dbInsertMultiple(string $table, array $fieldSchema, array ...$multiFields): string { - if (! isset($this->scheme[$table])) { - throw new LegacyDieException(500, "Unknown table $table"); - } + throw_unless(isset($this->scheme[$table]), new LegacyDieException(500, "Unknown table $table")); $fieldSchema = array_flip(array_intersect_key(array_flip($fieldSchema), $this->scheme[$table])); $sql = 'INSERT '.$this->dbPrefix."$table (".implode( @@ -1070,12 +1043,10 @@ public function dbInsertMultiple(string $table, array $fieldSchema, array ...$mu $values = []; foreach ($multiFields as $fields) { $fields = array_intersect_key($fields, array_flip($fieldSchema)); - if (count($fields) !== count($fieldSchema)) { - throw new LegacyDieException(500, 'Ein Datenfehler ist aufgetreten - Falsche Dimension', [ + throw_if(count($fields) !== count($fieldSchema), new LegacyDieException(500, 'Ein Datenfehler ist aufgetreten - Falsche Dimension', [ 'ist' => $fields, 'soll' => $fieldSchema, - ]); - } + ])); $values[] = array_values($fields); } @@ -1157,9 +1128,7 @@ public function dbRollBack(): bool */ public function dbUpdate(string $table, array $filter, array $fields, bool $debugDump = false): int { - if (! isset($this->scheme[$table])) { - throw new LegacyDieException(500, "Unkown table $table"); - } + throw_unless(isset($this->scheme[$table]), new LegacyDieException(500, "Unkown table $table")); $filter = array_intersect_key( $filter, @@ -1168,12 +1137,8 @@ public function dbUpdate(string $table, array $filter, array $fields, bool $debu ); // only fetch using id and url // $fields = array_diff_key(array_intersect_key($fields, $this->scheme[$table]), array_flip($this->validFields)); # do not update filter fields $fields = array_intersect_key($fields, array_flip($this->validFields)); - if (count($filter) === 0) { - throw new LegacyDieException(500, 'No filter fields given.'); - } - if (count($fields) === 0) { - throw new LegacyDieException(500, 'No fields given.'); - } + throw_if(count($filter) === 0, new LegacyDieException(500, 'No filter fields given.')); + throw_if(count($fields) === 0, new LegacyDieException(500, 'No fields given.')); $u = []; foreach ($fields as $k => $v) { $u[] = $this->quoteIdent($k).' = ?'; @@ -1190,9 +1155,7 @@ public function dbUpdate(string $table, array $filter, array $fields, bool $debu if ($debugDump) { dump($sql, $values); } - if ($ret === false) { - throw new LegacyDieException(500, "DB Update in $table failed", $query->errorInfo()); - } + throw_if($ret === false, new LegacyDieException(500, "DB Update in $table failed", $query->errorInfo())); return $query->rowCount(); } @@ -1204,26 +1167,22 @@ public function dbUpdate(string $table, array $filter, array $fields, bool $debu */ public function dbDelete(string $table, array $filter): int { - if (! isset($this->scheme[$table])) { - throw new LegacyDieException( + throw_unless(isset($this->scheme[$table]), new LegacyDieException( 500, 'Ein Datenbankfehler ist aufgetreten', "Deletion of table entries from $table not possible, table name unknown" - ); - } + )); [$whereSql, $values] = $this->buildWhereSql($filter); $sql = 'DELETE FROM '.$this->dbPrefix.$table.$whereSql; $query = $this->pdo->prepare($sql); $ret = $query->execute($values); - if ($ret === false) { - throw new LegacyDieException( + throw_if($ret === false, new LegacyDieException( 500, 'Ein Datenbank Fehler ist aufgetreten', "Deletion of table $table not possible:".PHP_EOL.print_r($query->errorInfo(), true).PHP_EOL.$sql.print_r($values, true) - ); - } + )); return $query->rowCount(); } diff --git a/legacy/lib/framework/auth/AuthHandler.php b/legacy/lib/framework/auth/AuthHandler.php index 53b21b38..240e8856 100644 --- a/legacy/lib/framework/auth/AuthHandler.php +++ b/legacy/lib/framework/auth/AuthHandler.php @@ -3,7 +3,7 @@ namespace framework\auth; use App\Exceptions\LegacyDieException; -use Auth; +use Illuminate\Support\Facades\Auth; use framework\Singleton; /** @@ -28,9 +28,7 @@ public static function getInstance(): static */ public function requireGroup(array|string $groups): void { - if (! $this->hasGroup($groups)) { - throw new LegacyDieException(403, 'Fehlende Zugangsberechtigung', $groups); - } + throw_unless($this->hasGroup($groups), new LegacyDieException(403, 'Fehlende Zugangsberechtigung', $groups)); } public function getUserMailinglists(): array diff --git a/legacy/lib/framework/render/EscFunc.php b/legacy/lib/framework/render/EscFunc.php index c36b6b4e..29e4342b 100644 --- a/legacy/lib/framework/render/EscFunc.php +++ b/legacy/lib/framework/render/EscFunc.php @@ -2,7 +2,7 @@ namespace framework\render; -use Carbon\Carbon; +use Illuminate\Support\Carbon; abstract class EscFunc { diff --git a/legacy/lib/framework/render/Renderer.php b/legacy/lib/framework/render/Renderer.php index 29540a43..43b1027c 100644 --- a/legacy/lib/framework/render/Renderer.php +++ b/legacy/lib/framework/render/Renderer.php @@ -97,8 +97,7 @@ static function (&$val) use ($defaultFunction) { if (empty($content)) { continue; } - if (count(reset($content)) !== $paramSum && count($keys) !== $paramSum) { - throw new LegacyDieException(500, + throw_if(count(reset($content)) !== $paramSum && count($keys) !== $paramSum, new LegacyDieException(500, "In Gruppe '$groupName' passt Spaltenzahl (".count( reset($content) ).') bzw. Key Anzahl ('.count( @@ -106,8 +105,7 @@ static function (&$val) use ($defaultFunction) { ).") nicht zur benötigten Parameterzahl $paramSum \n es wurden ".count( $escapeFunctions ).' Funktionen übergeben '.$diff.' wurde(n) hinzugefügt.' - ); - } + )); } if (count($keys) === 0) { @@ -291,9 +289,7 @@ protected function renderNonce(): void */ protected function renderAlert($strongMsg, $msg, string $type = self::ALERT_SUCCESS): void { - if (! in_array($type, [self::ALERT_SUCCESS, self::ALERT_INFO, self::ALERT_WARNING, self::ALERT_DANGER])) { - throw new LegacyDieException(500, 'Falscher Datentyp in renderAlert()'); - } + throw_unless(in_array($type, [self::ALERT_SUCCESS, self::ALERT_INFO, self::ALERT_WARNING, self::ALERT_DANGER]), new LegacyDieException(500, 'Falscher Datentyp in renderAlert()')); if (is_array($msg)) { $msg = $this->arrayToListEscapeFunction($msg); } ?> @@ -367,9 +363,7 @@ protected function renderHHPSelector($routeInfo, $urlPrefix = URIBASE, $urlSuffi [], ['von' => false] ); - if (! isset($hhps) || empty($hhps)) { - throw new LegacyDieException(500, 'Konnte keine Haushaltspläne finden'); - } + throw_if(! isset($hhps) || empty($hhps), new LegacyDieException(500, 'Konnte keine Haushaltspläne finden')); if (! isset($routeInfo['hhp-id'])) { foreach (array_reverse($hhps, true) as $id => $hhp) { if ($hhp['state'] === 'final') { diff --git a/tests/Pest/Accounting/CsvImportTest.php b/tests/Pest/Accounting/CsvImportTest.php index 9f5a4139..5b4c085d 100644 --- a/tests/Pest/Accounting/CsvImportTest.php +++ b/tests/Pest/Accounting/CsvImportTest.php @@ -50,7 +50,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) test('show last transactions', function (): void { $lastTransactions = []; BankAccount::all()->each(function ($account) use (&$lastTransactions): void { - $tmp = $account->bankTransactions()->orderBy('id', 'desc')->first(); + $tmp = $account->bankTransactions()->orderByDesc('id')->first(); if ($tmp) { $lastTransactions[$account->id] = $tmp; } @@ -107,7 +107,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) })->with('csv imports'); test('parse csv win encoding', function ($header, $data): void { - $acc = BankAccount::orderBy('id', 'desc')->first(); + $acc = BankAccount::orderByDesc('id')->first(); $csvFile = testFile('csv-import/test-correct-semicolon-win-enc.csv'); Livewire::actingAs(cashOfficer()) @@ -231,7 +231,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) test('if csv import is saved', function (): void { - $acc = BankAccount::orderBy('id', 'desc')->first(); + $acc = BankAccount::orderByDesc('id')->first(); $transactionAmount = BankTransaction::where('konto_id', '=', $acc->id)->count(); expect($transactionAmount)->toBe(0); @@ -269,7 +269,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) test('if mapping was saved and loaded', function (): void { - $acc = BankAccount::orderBy('id', 'desc')->first(); + $acc = BankAccount::orderByDesc('id')->first(); $transactionAmount = BankTransaction::where('konto_id', '=', $acc->id)->count(); expect($transactionAmount)->toBe(5); @@ -291,7 +291,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) test('csv upload with correct saldo check', function (): void { // same csv again has saldo errors - $acc = BankAccount::orderBy('id', 'desc')->firstOrFail(); + $acc = BankAccount::orderByDesc('id')->firstOrFail(); $transactionAmount = BankTransaction::where('konto_id', '=', $acc->id)->count(); expect($transactionAmount)->toBe(5); @@ -395,7 +395,7 @@ function mapSemicolonFixture($wire, bool $withSaldo = true) ->assertHasNoErrors(); expect(BankTransaction::where('konto_id', $acc->id)->count())->toBe(6) - ->and(BankTransaction::where('konto_id', $acc->id)->orderBy('id', 'desc')->first()->saldo)->toBe('18474.22'); + ->and(BankTransaction::where('konto_id', $acc->id)->orderByDesc('id')->first()->saldo)->toBe('18474.22'); }); test('comma-separated csv is detected and parsed', function (): void {