From 135b2985606f086fcd606367a0233b3d306ccd4b Mon Sep 17 00:00:00 2001 From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:17:30 -0400 Subject: [PATCH] alpha cleanup --- .oxlintrc.json | 7 + .../Eggs/Scripts/UpdateInstallScript.php | 4 +- app/Actions/Eggs/UpdateEgg.php | 4 +- .../Eggs/Variables/UpdateEggVariable.php | 4 +- app/Actions/Servers/UpdateServerStartup.php | 10 +- .../Eggs/UpdatesEggInstallScripts.php | 2 +- app/Contracts/Eggs/UpdatesEggVariables.php | 2 +- app/Contracts/Eggs/UpdatesEggs.php | 2 +- app/Exceptions/DisplayException.php | 9 +- app/Extensions/DynamicDatabaseConnection.php | 5 + app/Facades/Alert.php | 24 - .../Api/Admin/Eggs/EggController.php | 4 +- .../Api/Admin/Eggs/EggScriptController.php | 4 +- .../Api/Admin/Eggs/EggVariableController.php | 4 +- .../Api/Admin/Servers/ExternalController.php | 5 +- .../Admin/Servers/ServerMountController.php | 5 +- .../Api/Admin/Users/ExternalController.php | 5 +- .../Servers/ExternalServerController.php | 5 +- .../Users/ExternalUserController.php | 5 +- .../Api/Client/Servers/BackupController.php | 9 +- .../RequireTwoFactorAuthentication.php | 3 - app/Models/ApiKey.php | 7 - app/Models/AuditLog.php | 48 -- app/Models/Backup.php | 1 - app/Services/Backups/BackupListService.php | 23 - app/Services/Daemon/ServerClient.php | 5 - .../Databases/DatabaseHostGateway.php | 14 +- app/Services/Extensions/ExtensionManager.php | 22 - .../Extensions/ExtensionRepository.php | 5 - app/Services/Servers/EnvironmentService.php | 10 - app/Services/Servers/MountListService.php | 20 - app/Services/Servers/ServerFinderService.php | 15 - app/Services/Users/UserFinderService.php | 15 - app/Support/Alerts/AlertsMessageBag.php | 82 --- composer.json | 2 +- config/app.php | 2 - package.json | 2 +- packages/sdk/README.md | 55 +- pint.json | 1 + resources/lang/en/auth.php | 1 - resources/scripts/api/activity.spec.ts | 63 +++ .../api/admin/extensions/queries.spec.ts | 90 +++ resources/scripts/api/http.spec.ts | 77 +++ .../elements/SubNavigation.spec.tsx | 165 ++++++ .../Actions/Servers/DeleteServerTest.php | 34 ++ .../Servers/UpdateServerStartupTest.php | 53 +- .../DynamicDatabaseConnectionTest.php | 37 ++ tests/Support/Fakes/FakeDaemonServer.php | 8 +- .../Support/Fakes/FakeDatabaseHostGateway.php | 17 - .../Extensions/ExtensionRepositoryTest.php | 19 +- tools/oxlint/rules/lint.spec.ts | 45 +- tools/oxlint/rules/rules/design-tokens.ts | 19 +- .../rules/rules/generated-api-imports.ts | 20 +- .../rules/rules/generated-api-mutations.ts | 9 +- .../rules/rules/no-known-value-widening.ts | 6 +- .../rules/rules/no-widen-then-assert.ts | 187 ++++--- tools/oxlint/rules/shared/dictionary-types.ts | 515 ++++++++++-------- tools/oxlint/rules/shared/literals.ts | 9 + tools/phpstan/rules/extension.neon | 1 - tools/phpstan/rules/install.php | 1 - tools/phpstan/rules/phpunit.xml | 3 + .../rules/src/Rules/NoChainedVarTagsRule.php | 4 +- .../NoForbiddenTermsInSymbolNamesRule.php | 2 +- .../src/Rules/NoInstanceofOnMixedRule.php | 2 +- .../NoKnownValueWideningPropertyRule.php | 2 +- .../Rules/NoKnownValueWideningReturnRule.php | 2 +- .../rules/src/Rules/NoMixedParametersRule.php | 4 +- .../rules/src/Rules/NoMixedReturnsRule.php | 4 +- .../src/Rules/NoMixedTypeAliasesRule.php | 2 +- .../src/Rules/NoObjectParametersRule.php | 4 +- .../Rules/NoUnsafeDictionaryPropertyRule.php | 2 +- .../src/Rules/NoUnsafeDictionaryTypeRule.php | 6 +- .../rules/src/Rules/NoWidenThenAssertRule.php | 4 +- .../RequireSafetyCommentForAssertionRule.php | 2 +- .../rules/src/Support/TypeAliasDocblock.php | 2 +- .../tests/Integration/PackageCoverageTest.php | 6 +- .../Rules/NoChainedAssertionsRuleTest.php | 16 +- .../tests/Rules/NoChainedVarTagsRuleTest.php | 16 +- .../Rules/NoClassLoadingMocksRuleTest.php | 14 +- .../NoConditionalEmptyArraySpreadRuleTest.php | 14 +- .../NoForbiddenTermsInSymbolNamesRuleTest.php | 14 +- .../Rules/NoInstanceofOnMixedRuleTest.php | 16 +- .../NoKnownValueWideningReturnRuleTest.php | 16 +- .../Rules/NoKnownValueWideningRuleTest.php | 16 +- .../tests/Rules/NoMixedParametersRuleTest.php | 4 +- .../tests/Rules/NoMixedReturnsRuleTest.php | 22 +- .../Rules/NoMixedTypeAliasesRuleTest.php | 16 +- .../Rules/NoObjectParametersRuleTest.php | 22 +- .../Rules/NoServiceConstructionRuleTest.php | 14 +- .../NoUnsafeDictionaryPropertyRuleTest.php | 16 +- .../Rules/NoUnsafeDictionaryTypeRuleTest.php | 24 +- .../tests/Rules/NoWidenThenAssertRuleTest.php | 16 +- ...quireSafetyCommentForAssertionRuleTest.php | 16 +- 93 files changed, 1231 insertions(+), 919 deletions(-) delete mode 100644 app/Facades/Alert.php delete mode 100644 app/Models/AuditLog.php delete mode 100644 app/Services/Backups/BackupListService.php delete mode 100644 app/Services/Extensions/ExtensionManager.php delete mode 100644 app/Services/Servers/MountListService.php delete mode 100644 app/Services/Servers/ServerFinderService.php delete mode 100644 app/Services/Users/UserFinderService.php delete mode 100644 app/Support/Alerts/AlertsMessageBag.php create mode 100644 resources/scripts/api/activity.spec.ts create mode 100644 resources/scripts/api/admin/extensions/queries.spec.ts create mode 100644 resources/scripts/api/http.spec.ts create mode 100644 resources/scripts/components/elements/SubNavigation.spec.tsx create mode 100644 tests/Integration/Extensions/DynamicDatabaseConnectionTest.php create mode 100644 tools/oxlint/rules/shared/literals.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 38f5affa2..c4ce9f86c 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -298,6 +298,13 @@ "typescript/no-redundant-type-constituents": "off", "typescript/no-empty-object-type": "error" } + }, + { + // ESTree literals are discriminated only by the runtime type of `value`; this helper is that decoder. + "files": ["tools/oxlint/rules/shared/literals.ts"], + "rules": { + "rules/no-runtime-typeof": "off" + } } ] } diff --git a/app/Actions/Eggs/Scripts/UpdateInstallScript.php b/app/Actions/Eggs/Scripts/UpdateInstallScript.php index ac5e22dca..7b348e50b 100644 --- a/app/Actions/Eggs/Scripts/UpdateInstallScript.php +++ b/app/Actions/Eggs/Scripts/UpdateInstallScript.php @@ -19,7 +19,7 @@ final class UpdateInstallScript implements UpdatesEggInstallScripts * * @throws InvalidCopyFromException */ - public function update(Egg $egg, array $data): void + public function update(Egg $egg, array $data): Egg { $copyFrom = JsonValueGuard::nullableInteger(Arr::get($data, 'copy_script_from')); if ($copyFrom !== null && ! Egg::query()->scriptSources()->whereKey($copyFrom)->exists()) { @@ -33,5 +33,7 @@ final class UpdateInstallScript implements UpdatesEggInstallScripts 'script_container' => JsonValueGuard::string(Arr::get($data, 'script_container')), 'copy_script_from' => $copyFrom, ]); + + return $egg; } } diff --git a/app/Actions/Eggs/UpdateEgg.php b/app/Actions/Eggs/UpdateEgg.php index 742a90f41..c12e486f7 100644 --- a/app/Actions/Eggs/UpdateEgg.php +++ b/app/Actions/Eggs/UpdateEgg.php @@ -14,12 +14,14 @@ final class UpdateEgg implements UpdatesEggs * * @param EggCreationData $data */ - public function update(Egg $egg, array $data): void + public function update(Egg $egg, array $data): Egg { // TODO(dane): Once the admin UI is done being reworked and this is exposed // in said UI, remove this so that you can actually update the denylist. unset($data['file_denylist']); $egg->update($data); + + return $egg; } } diff --git a/app/Actions/Eggs/Variables/UpdateEggVariable.php b/app/Actions/Eggs/Variables/UpdateEggVariable.php index 794860261..2ed97a93b 100644 --- a/app/Actions/Eggs/Variables/UpdateEggVariable.php +++ b/app/Actions/Eggs/Variables/UpdateEggVariable.php @@ -14,8 +14,10 @@ final class UpdateEggVariable implements UpdatesEggVariables * * @param EggVariableData $data */ - public function update(EggVariable $variable, array $data): void + public function update(EggVariable $variable, array $data): EggVariable { $variable->update($data); + + return $variable; } } diff --git a/app/Actions/Servers/UpdateServerStartup.php b/app/Actions/Servers/UpdateServerStartup.php index 276ec9d2b..5704663f3 100644 --- a/app/Actions/Servers/UpdateServerStartup.php +++ b/app/Actions/Servers/UpdateServerStartup.php @@ -7,6 +7,7 @@ namespace Pterodactyl\Actions\Servers; use Illuminate\Support\Facades\DB; use LogicException; use Pterodactyl\Contracts\Servers\ChangesServerEgg; +use Pterodactyl\Contracts\Servers\UpdatesServerDockerImage; use Pterodactyl\Contracts\Servers\UpdatesServerStartup; use Pterodactyl\Models\Egg; use Pterodactyl\Models\Server; @@ -20,6 +21,7 @@ final readonly class UpdateServerStartup implements UpdatesServerStartup public function __construct( private VariableValidatorService $validatorService, private ChangesServerEgg $eggs, + private UpdatesServerDockerImage $dockerImage, ) {} /** @@ -56,8 +58,14 @@ final readonly class UpdateServerStartup implements UpdatesServerStartup $server->fill([ 'startup' => $data['startup'] ?? $server->startup, 'skip_scripts' => $data['skip_scripts'] ?? isset($data['skip_scripts']), - 'image' => $data['docker_image'] ?? $server->image, ])->save(); + + // Image changes go through their own contract so extensions wrapping + // it see this path too. Skip it when the image is unchanged. + $image = $data['docker_image'] ?? null; + if ($image !== null && $image !== $server->image) { + $server = $this->dockerImage->update($server, $image); + } } // Use fresh() rather than refresh(). refresh() reloads every loaded diff --git a/app/Contracts/Eggs/UpdatesEggInstallScripts.php b/app/Contracts/Eggs/UpdatesEggInstallScripts.php index c85bfaf21..6b454f491 100644 --- a/app/Contracts/Eggs/UpdatesEggInstallScripts.php +++ b/app/Contracts/Eggs/UpdatesEggInstallScripts.php @@ -16,5 +16,5 @@ interface UpdatesEggInstallScripts * * @throws InvalidCopyFromException */ - public function update(Egg $egg, array $data): void; + public function update(Egg $egg, array $data): Egg; } diff --git a/app/Contracts/Eggs/UpdatesEggVariables.php b/app/Contracts/Eggs/UpdatesEggVariables.php index 943db36c5..1f400505f 100644 --- a/app/Contracts/Eggs/UpdatesEggVariables.php +++ b/app/Contracts/Eggs/UpdatesEggVariables.php @@ -13,5 +13,5 @@ interface UpdatesEggVariables * * @param EggVariableData $data */ - public function update(EggVariable $variable, array $data): void; + public function update(EggVariable $variable, array $data): EggVariable; } diff --git a/app/Contracts/Eggs/UpdatesEggs.php b/app/Contracts/Eggs/UpdatesEggs.php index 02d22c351..3807b7790 100644 --- a/app/Contracts/Eggs/UpdatesEggs.php +++ b/app/Contracts/Eggs/UpdatesEggs.php @@ -13,5 +13,5 @@ interface UpdatesEggs * * @param EggCreationData $data */ - public function update(Egg $egg, array $data): void; + public function update(Egg $egg, array $data): Egg; } diff --git a/app/Exceptions/DisplayException.php b/app/Exceptions/DisplayException.php index 91c4deeb5..bd3210f1d 100644 --- a/app/Exceptions/DisplayException.php +++ b/app/Exceptions/DisplayException.php @@ -10,7 +10,6 @@ use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\Exceptions; use Illuminate\Support\Facades\Log; -use Pterodactyl\Facades\Alert; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Throwable; @@ -51,9 +50,9 @@ class DisplayException extends PterodactylException implements HttpExceptionInte } /** - * Render the exception to the user by adding a flashed message to the session - * and then redirecting them back to the page that they came from. If the - * request originated from an API hit, return the error in JSONAPI spec format. + * Render the exception by redirecting the user back to the page that they came + * from. If the request originated from an API hit, return the error in JSONAPI + * spec format. */ public function render(Request $request): JsonResponse|RedirectResponse { @@ -61,8 +60,6 @@ class DisplayException extends PterodactylException implements HttpExceptionInte return response()->json(ApiErrorResponse::toArray($this), $this->getStatusCode(), $this->getHeaders()); } - Alert::danger($this->getMessage())->flash(); - return back()->withInput(); } diff --git a/app/Extensions/DynamicDatabaseConnection.php b/app/Extensions/DynamicDatabaseConnection.php index 331dc259f..5921815a8 100644 --- a/app/Extensions/DynamicDatabaseConnection.php +++ b/app/Extensions/DynamicDatabaseConnection.php @@ -7,6 +7,7 @@ namespace Pterodactyl\Extensions; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Facades\DB; use Pterodactyl\Models\DatabaseHost; class DynamicDatabaseConnection @@ -38,5 +39,9 @@ class DynamicDatabaseConnection 'charset' => self::DB_CHARSET, 'collation' => self::DB_COLLATION, ]); + + // The manager caches resolved connections by name, so drop the previous host's + // connection or the next DB::connection() call keeps talking to it. + DB::purge($connection); } } diff --git a/app/Facades/Alert.php b/app/Facades/Alert.php deleted file mode 100644 index 1e5922c99..000000000 --- a/app/Facades/Alert.php +++ /dev/null @@ -1,24 +0,0 @@ -> getMessages() - */ -class Alert extends Facade -{ - protected static function getFacadeAccessor(): string - { - return AlertsMessageBag::class; - } -} diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggController.php b/app/Http/Controllers/Api/Admin/Eggs/EggController.php index 4964fd6d9..76b8c93bd 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggController.php @@ -112,14 +112,14 @@ class EggController extends AdminApiController #[ResponseFromTransformer(EggTransformer::class, Egg::class, description: 'Egg updated.', resourceKey: 'egg')] public function update(UpdateEggRequest $request, UpdatesEggs $eggs, Egg $egg): array { - $eggs->update($egg, $request->payload()); + $egg = $eggs->update($egg, $request->payload()); Activity::event('admin:egg.update') ->subject($egg) ->property('name', $egg->name) ->log(); - return Fractal::item($egg->refresh()) + return Fractal::item($egg) ->transformWith($this->getTransformer(EggTransformer::class)) ->toResponseArray(); } diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php b/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php index e89c7c210..6bd30808b 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggScriptController.php @@ -61,14 +61,14 @@ class EggScriptController extends AdminApiController $data = $request->validated(); JsonValueGuard::assertPayload9($data); - $scripts->update($egg, $data); + $egg = $scripts->update($egg, $data); Activity::event('admin:egg.scripts') ->subject($egg) ->property('name', $egg->name) ->log(); - return Fractal::item($egg->refresh()) + return Fractal::item($egg) ->transformWith($this->getTransformer(EggTransformer::class)) ->toResponseArray(); } diff --git a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php index 75b4d6174..2228af8e7 100644 --- a/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php +++ b/app/Http/Controllers/Api/Admin/Eggs/EggVariableController.php @@ -76,9 +76,7 @@ class EggVariableController extends AdminApiController #[ResponseFromTransformer(EggVariableTransformer::class, EggVariable::class, description: 'Egg variable updated.', resourceKey: 'egg_variable')] public function update(UpdateVariableRequest $request, UpdatesEggVariables $variables, Egg $egg, EggVariable $variable): array { - $variables->update($variable, $request->payload()); - - $variable = $variable->refresh(); + $variable = $variables->update($variable, $request->payload()); Activity::event('admin:egg-variable.update') ->subject($egg, $variable) diff --git a/app/Http/Controllers/Api/Admin/Servers/ExternalController.php b/app/Http/Controllers/Api/Admin/Servers/ExternalController.php index 171ecc23d..cd65a1c35 100644 --- a/app/Http/Controllers/Api/Admin/Servers/ExternalController.php +++ b/app/Http/Controllers/Api/Admin/Servers/ExternalController.php @@ -12,7 +12,6 @@ use Pterodactyl\Facades\Fractal; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Servers\GetServersRequest; use Pterodactyl\Models\Server; -use Pterodactyl\Services\Servers\ServerFinderService; use Pterodactyl\Transformers\Api\Admin\ServerTransformer; #[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')] @@ -26,9 +25,9 @@ class ExternalController extends AdminApiController */ #[Endpoint('Get server by external ID', 'Returns a single server by external identifier.')] #[ResponseFromTransformer(ServerTransformer::class, Server::class, description: 'Server returned.', factoryStates: ['withRelationships'], resourceKey: 'server')] - public function __invoke(GetServersRequest $request, ServerFinderService $finder, string $external_id): array + public function __invoke(GetServersRequest $request, string $external_id): array { - $server = $finder->byExternalId($external_id); + $server = Server::query()->where('external_id', $external_id)->firstOrFail(); return Fractal::item($server) ->transformWith($this->getTransformer(ServerTransformer::class)) diff --git a/app/Http/Controllers/Api/Admin/Servers/ServerMountController.php b/app/Http/Controllers/Api/Admin/Servers/ServerMountController.php index 3e3b7f5d6..9e04ad8aa 100644 --- a/app/Http/Controllers/Api/Admin/Servers/ServerMountController.php +++ b/app/Http/Controllers/Api/Admin/Servers/ServerMountController.php @@ -19,7 +19,6 @@ use Pterodactyl\Http\Requests\Api\Admin\Servers\GetServerMountsRequest; use Pterodactyl\Http\Requests\Api\Admin\Servers\StoreServerMountRequest; use Pterodactyl\Models\Mount; use Pterodactyl\Models\Server; -use Pterodactyl\Services\Servers\MountListService; use Pterodactyl\Support\JsonValueGuard; use Pterodactyl\Transformers\Api\Admin\MountTransformer; use Symfony\Component\HttpKernel\Exception\HttpException; @@ -61,11 +60,11 @@ class ServerMountController extends AdminApiController #[Endpoint('List server mounts', 'Returns mount definitions that are eligible for a server, including whether each mount is attached.')] #[ScribeResponse(self::SERVER_MOUNT_LIST_EXAMPLE, description: 'Eligible server mounts returned.')] #[ScribeResponse(self::INSTALL_STATE_ERROR, status: 403, description: 'The server is not installed.')] - public function index(GetServerMountsRequest $request, MountListService $listing, Server $server): array + public function index(GetServerMountsRequest $request, Server $server): array { $this->assertServerInstalled($server); - $mounts = $listing->handle($server); + $mounts = Mount::query()->availableToServer($server)->get(); $mountedIds = $server->mounts->pluck('id')->all(); diff --git a/app/Http/Controllers/Api/Admin/Users/ExternalController.php b/app/Http/Controllers/Api/Admin/Users/ExternalController.php index 52d05d4d2..efbe906b5 100644 --- a/app/Http/Controllers/Api/Admin/Users/ExternalController.php +++ b/app/Http/Controllers/Api/Admin/Users/ExternalController.php @@ -12,7 +12,6 @@ use Pterodactyl\Facades\Fractal; use Pterodactyl\Http\Controllers\Api\Admin\AdminApiController; use Pterodactyl\Http\Requests\Api\Admin\Users\GetUsersRequest; use Pterodactyl\Models\User; -use Pterodactyl\Services\Users\UserFinderService; use Pterodactyl\Transformers\Api\Admin\UserTransformer; #[Group('Admin API', 'Root administrator endpoints for managing panel configuration and resources.')] @@ -26,9 +25,9 @@ class ExternalController extends AdminApiController */ #[Endpoint('Get user by external ID', 'Returns a single panel user by external identifier.')] #[ResponseFromTransformer(UserTransformer::class, User::class, description: 'User returned.', resourceKey: 'user')] - public function __invoke(GetUsersRequest $request, UserFinderService $finder, string $external_id): array + public function __invoke(GetUsersRequest $request, string $external_id): array { - $user = $finder->byExternalId($external_id); + $user = User::query()->where('external_id', $external_id)->firstOrFail(); return Fractal::item($user) ->transformWith($this->getTransformer(UserTransformer::class)) diff --git a/app/Http/Controllers/Api/Application/Servers/ExternalServerController.php b/app/Http/Controllers/Api/Application/Servers/ExternalServerController.php index ee327625c..0a2f22381 100644 --- a/app/Http/Controllers/Api/Application/Servers/ExternalServerController.php +++ b/app/Http/Controllers/Api/Application/Servers/ExternalServerController.php @@ -12,7 +12,6 @@ use Pterodactyl\Facades\Fractal; use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController; use Pterodactyl\Http\Requests\Api\Application\Servers\GetExternalServerRequest; use Pterodactyl\Models\Server; -use Pterodactyl\Services\Servers\ServerFinderService; use Pterodactyl\Transformers\Api\Application\ServerTransformer; #[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')] @@ -26,9 +25,9 @@ class ExternalServerController extends ApplicationApiController */ #[Endpoint('Get server by external ID', 'Returns a single server by its external identifier.')] #[ResponseFromTransformer(ServerTransformer::class, Server::class, factoryStates: ['withRelationships'], resourceKey: 'server')] - public function index(GetExternalServerRequest $request, ServerFinderService $finder, string $external_id): array + public function index(GetExternalServerRequest $request, string $external_id): array { - $server = $finder->byExternalId($external_id); + $server = Server::query()->where('external_id', $external_id)->firstOrFail(); return Fractal::item($server) ->transformWith($this->getTransformer(ServerTransformer::class)) diff --git a/app/Http/Controllers/Api/Application/Users/ExternalUserController.php b/app/Http/Controllers/Api/Application/Users/ExternalUserController.php index 7871f33e8..e22945be1 100644 --- a/app/Http/Controllers/Api/Application/Users/ExternalUserController.php +++ b/app/Http/Controllers/Api/Application/Users/ExternalUserController.php @@ -12,7 +12,6 @@ use Pterodactyl\Facades\Fractal; use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController; use Pterodactyl\Http\Requests\Api\Application\Users\GetExternalUserRequest; use Pterodactyl\Models\User; -use Pterodactyl\Services\Users\UserFinderService; use Pterodactyl\Transformers\Api\Application\UserTransformer; #[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')] @@ -26,9 +25,9 @@ class ExternalUserController extends ApplicationApiController */ #[Endpoint('Get user by external ID', 'Returns a single panel user by its external identifier.')] #[ResponseFromTransformer(UserTransformer::class, User::class, resourceKey: 'user')] - public function index(GetExternalUserRequest $request, UserFinderService $finder, string $external_id): array + public function index(GetExternalUserRequest $request, string $external_id): array { - $user = $finder->byExternalId($external_id); + $user = User::query()->where('external_id', $external_id)->firstOrFail(); return Fractal::item($user) ->transformWith($this->getTransformer(UserTransformer::class)) diff --git a/app/Http/Controllers/Api/Client/Servers/BackupController.php b/app/Http/Controllers/Api/Client/Servers/BackupController.php index 6a9fb775c..30659993e 100644 --- a/app/Http/Controllers/Api/Client/Servers/BackupController.php +++ b/app/Http/Controllers/Api/Client/Servers/BackupController.php @@ -30,7 +30,6 @@ use Pterodactyl\Http\Requests\Api\Client\Servers\Backups\ToggleBackupLockRequest use Pterodactyl\Http\Requests\Api\Client\Servers\Backups\ViewBackupRequest; use Pterodactyl\Models\Backup; use Pterodactyl\Models\Server; -use Pterodactyl\Services\Backups\BackupListService; use Pterodactyl\Transformers\Api\Client\BackupTransformer; use Spatie\Fractalistic\Exceptions\InvalidTransformation; use Spatie\Fractalistic\Exceptions\NoTransformerSpecified; @@ -68,16 +67,14 @@ class BackupController extends ClientApiController #[QueryParam('page', 'integer', 'The page number to return.', required: false, example: 1)] #[QueryParam('per_page', 'integer', 'Number of backups to return per page. The maximum is 50.', required: false, example: 20)] #[ResponseFromTransformer(BackupTransformer::class, Backup::class, description: 'Server backups returned.', collection: true, resourceKey: 'backup', paginate: [IlluminatePaginatorAdapter::class, 20], meta: ['backup_count' => 1])] - public function index(ListBackupsRequest $request, BackupListService $listing, Server $server): array + public function index(ListBackupsRequest $request, Server $server): array { $validated = $request->payload(); - $result = $listing->handle($server, $validated['per_page']); - - return Fractal::collection($result['backups']) + return Fractal::collection($server->backups()->paginate($validated['per_page'])) ->transformWith($this->getTransformer(BackupTransformer::class)) ->addMeta([ - 'backup_count' => $result['backup_count'], + 'backup_count' => $server->backups()->nonFailed()->count(), ]) ->toResponseArray(); } diff --git a/app/Http/Middleware/RequireTwoFactorAuthentication.php b/app/Http/Middleware/RequireTwoFactorAuthentication.php index 9cab49a9e..6cd40bc45 100644 --- a/app/Http/Middleware/RequireTwoFactorAuthentication.php +++ b/app/Http/Middleware/RequireTwoFactorAuthentication.php @@ -8,7 +8,6 @@ use Closure; use Illuminate\Http\Request; use Illuminate\Support\Str; use Pterodactyl\Exceptions\Http\TwoFactorAuthRequiredException; -use Pterodactyl\Facades\Alert; use Pterodactyl\Http\Concerns\ResolvesRequestContext; use Symfony\Component\HttpFoundation\Response; @@ -66,8 +65,6 @@ class RequireTwoFactorAuthentication // For API calls return an exception which gets rendered nicely in the API response. throw_if($request->isJson() || Str::startsWith($uri, '/api/'), TwoFactorAuthRequiredException::class); - Alert::danger(trans('auth.2fa_must_be_enabled'))->flash(); - return redirect()->to($this->redirectRoute); } } diff --git a/app/Models/ApiKey.php b/app/Models/ApiKey.php index ad4f93640..ba00f49f4 100644 --- a/app/Models/ApiKey.php +++ b/app/Models/ApiKey.php @@ -94,15 +94,8 @@ class ApiKey extends Model implements HasAbilities public const int TYPE_ACCOUNT = 1; - /* @deprecated */ public const int TYPE_APPLICATION = 2; - /* @deprecated */ - public const int TYPE_DAEMON_USER = 3; - - /* @deprecated */ - public const int TYPE_DAEMON_APPLICATION = 4; - /** * The length of API key identifiers. */ diff --git a/app/Models/AuditLog.php b/app/Models/AuditLog.php deleted file mode 100644 index 86827d962..000000000 --- a/app/Models/AuditLog.php +++ /dev/null @@ -1,48 +0,0 @@ - - */ - protected function casts(): array - { - return [ - 'is_system' => 'bool', - 'device' => 'array', - 'metadata' => 'array', - ]; - } - - /** - * @return BelongsTo - */ - public function user(): BelongsTo - { - return $this->belongsTo(User::class); - } - - /** - * @return BelongsTo - */ - public function server(): BelongsTo - { - return $this->belongsTo(Server::class); - } -} diff --git a/app/Models/Backup.php b/app/Models/Backup.php index 9155d284f..a577b77af 100644 --- a/app/Models/Backup.php +++ b/app/Models/Backup.php @@ -32,7 +32,6 @@ use Pterodactyl\Models\Traits\HasRealtimeIdentifier; * @property CarbonImmutable $updated_at * @property CarbonImmutable|null $deleted_at * @property Server $server - * @property AuditLog[] $audits */ #[Attributes\Identifiable('bkup')] #[Guarded(['id', 'created_at', 'updated_at', 'deleted_at'])] diff --git a/app/Services/Backups/BackupListService.php b/app/Services/Backups/BackupListService.php deleted file mode 100644 index 90740a8fb..000000000 --- a/app/Services/Backups/BackupListService.php +++ /dev/null @@ -1,23 +0,0 @@ -, backup_count: int} - */ - public function handle(Server $server, int $perPage): array - { - return [ - 'backups' => $server->backups()->paginate($perPage), - 'backup_count' => $server->backups()->nonFailed()->count(), - ]; - } -} diff --git a/app/Services/Daemon/ServerClient.php b/app/Services/Daemon/ServerClient.php index cd39a70db..d10c3ff29 100644 --- a/app/Services/Daemon/ServerClient.php +++ b/app/Services/Daemon/ServerClient.php @@ -74,11 +74,6 @@ final readonly class ServerClient $this->connection->request('POST', "/api/servers/{$this->uuid}/reinstall"); } - public function requestArchive(): void - { - $this->connection->request('POST', "/api/servers/{$this->uuid}/archive"); - } - public function power(string $action): Response { return $this->connection->request('POST', "/api/servers/{$this->uuid}/power", ['json' => ['action' => $action]]); diff --git a/app/Services/Databases/DatabaseHostGateway.php b/app/Services/Databases/DatabaseHostGateway.php index 6ca818c8c..bcf4c2e4f 100644 --- a/app/Services/Databases/DatabaseHostGateway.php +++ b/app/Services/Databases/DatabaseHostGateway.php @@ -14,24 +14,12 @@ class DatabaseHostGateway { public const string DEFAULT_CONNECTION_NAME = 'dynamic'; - private string $connection = self::DEFAULT_CONNECTION_NAME; - - /** - * Set the connection name to execute statements against. - */ - public function setConnection(string $connection): self - { - $this->connection = $connection; - - return $this; - } - /** * Return the connection to execute statements against. */ public function getConnection(): string { - return $this->connection; + return self::DEFAULT_CONNECTION_NAME; } /** diff --git a/app/Services/Extensions/ExtensionManager.php b/app/Services/Extensions/ExtensionManager.php deleted file mode 100644 index ad5e0d332..000000000 --- a/app/Services/Extensions/ExtensionManager.php +++ /dev/null @@ -1,22 +0,0 @@ -settings('')`. - * - * @deprecated use the Pterodactyl\Facades\Extensions facade: `Extensions::settings('')` - */ -class ExtensionManager -{ - public function __construct(private readonly ExtensionRepository $extensions) {} - - /** @deprecated use `Extensions::settings('')` */ - public function settings(string $identifier): ExtensionSettings - { - return $this->extensions->settings($identifier); - } -} diff --git a/app/Services/Extensions/ExtensionRepository.php b/app/Services/Extensions/ExtensionRepository.php index 2340bea50..59ebb116b 100644 --- a/app/Services/Extensions/ExtensionRepository.php +++ b/app/Services/Extensions/ExtensionRepository.php @@ -196,11 +196,6 @@ class ExtensionRepository rescue(fn () => $this->events->dispatch(new ExtensionLoadFailed($identifier, $phase, $reason, $exception))); } - public function clearError(string $identifier): void - { - $this->clearErrors([$identifier]); - } - /** @param list $identifiers */ public function clearErrors(array $identifiers): void { diff --git a/app/Services/Servers/EnvironmentService.php b/app/Services/Servers/EnvironmentService.php index 86c51fe92..a052450df 100644 --- a/app/Services/Servers/EnvironmentService.php +++ b/app/Services/Servers/EnvironmentService.php @@ -24,16 +24,6 @@ class EnvironmentService $this->additional[$key] = $closure; } - /** - * Return the dynamically added additional keys. - * - * @return array - */ - public function getEnvironmentKeys(): array - { - return $this->additional; - } - /** * Take all of the environment variables configured for this server and return * them in an easy to process format. diff --git a/app/Services/Servers/MountListService.php b/app/Services/Servers/MountListService.php deleted file mode 100644 index d8b35b6aa..000000000 --- a/app/Services/Servers/MountListService.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ - public function handle(Server $server): Collection - { - return Mount::query()->availableToServer($server)->get(); - } -} diff --git a/app/Services/Servers/ServerFinderService.php b/app/Services/Servers/ServerFinderService.php deleted file mode 100644 index ced869df2..000000000 --- a/app/Services/Servers/ServerFinderService.php +++ /dev/null @@ -1,15 +0,0 @@ -where('external_id', $externalId)->firstOrFail(); - } -} diff --git a/app/Services/Users/UserFinderService.php b/app/Services/Users/UserFinderService.php deleted file mode 100644 index 79de8b625..000000000 --- a/app/Services/Users/UserFinderService.php +++ /dev/null @@ -1,15 +0,0 @@ -where('external_id', $externalId)->firstOrFail(); - } -} diff --git a/app/Support/Alerts/AlertsMessageBag.php b/app/Support/Alerts/AlertsMessageBag.php deleted file mode 100644 index 477abeebf..000000000 --- a/app/Support/Alerts/AlertsMessageBag.php +++ /dev/null @@ -1,82 +0,0 @@ -message('success', $message); - } - - public function danger(string $message): self - { - return $this->message('danger', $message); - } - - public function warning(string $message): self - { - return $this->message('warning', $message); - } - - public function info(string $message): self - { - return $this->message('info', $message); - } - - public function flash(): self - { - if ($this->type === null || $this->message === null) { - return $this; - } - - $messages = $this->getMessages(); - $messages[$this->type][] = $this->message; - - $this->session->flash(self::SESSION_KEY, $messages); - - return $this; - } - - /** - * @return array> - */ - public function getMessages(): array - { - $messages = $this->session->get(self::SESSION_KEY, []); - if (! is_array($messages)) { - return []; - } - - $normalized = []; - foreach ($messages as $type => $items) { - if (! is_string($type) || ! is_array($items) || ! array_is_list($items)) { - continue; - } - - $normalized[$type] = array_values(array_filter($items, is_string(...))); - } - - return $normalized; - } - - private function message(string $type, string $message): self - { - $this->type = $type; - $this->message = $message; - - return $this; - } -} diff --git a/composer.json b/composer.json index 5e82379e6..9581f3378 100644 --- a/composer.json +++ b/composer.json @@ -88,7 +88,7 @@ "pint --parallel --cache-file=.pint.cache app bootstrap/app.php bootstrap/tests.php config database routes tests" ], "test:lint": [ - "pint --test --parallel --cache-file=.pint.cache app bootstrap/app.php bootstrap/tests.php config database routes tests", + "pint --test --parallel --cache-file=.pint.cache app bootstrap/app.php bootstrap/tests.php config database routes tests tools/phpstan", "rector --dry-run" ], "test:types": "phpstan analyse -c phpstan-rules.neon --memory-limit=2G", diff --git a/config/app.php b/config/app.php index 743639df1..7ac991524 100644 --- a/config/app.php +++ b/config/app.php @@ -5,7 +5,6 @@ declare(strict_types=1); use Carbon\Carbon; use Illuminate\Support\Facades\Facade; use Pterodactyl\Facades\Activity; -use Pterodactyl\Facades\Alert; use Pterodactyl\Facades\LogBatch; use Pterodactyl\Facades\LogTarget; @@ -169,7 +168,6 @@ return [ */ 'aliases' => Facade::defaultAliases()->merge([ - 'Alert' => Alert::class, 'Carbon' => Carbon::class, // Custom Facades diff --git a/package.json b/package.json index 08d690b43..239f99a69 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,7 @@ "test": "vitest run", "test:watch": "vitest", "tsc": "tsc --noEmit && tsc --project tools/oxlint/rules && npm --prefix packages/hello-world run typecheck", - "lint": "oxfmt --check resources/scripts packages/hello-world tools/oxlint && oxlint --type-aware resources/scripts packages/hello-world/src/client", + "lint": "oxfmt --check resources/scripts packages/hello-world tools/oxlint && oxlint --type-aware resources/scripts packages/hello-world/src/client tools/oxlint", "api:generate": "openapi-ts", "extension:api:generate": "node scripts/generate-extension-api.mjs", "api:refresh": "PTERODACTYL_EXTENSIONS_ENABLED=false composer docs:openapi:verify && npm run api:generate", diff --git a/packages/sdk/README.md b/packages/sdk/README.md index b69c8d25e..dc7a62373 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -2,7 +2,7 @@ Build extensions for the Pterodactyl panel (v2+). This package provides: -- **Types** for the runtime API — the actual implementation is provided *by the panel* +- **Types** for the runtime API. The implementation is provided *by the panel* through its import map, so your built extension never bundles the SDK, React, or TanStack Query: it shares the panel's own instances. - **The Vite build preset** (`@pterodactyl/sdk/vite`) that keeps those modules external @@ -34,7 +34,7 @@ import { defineExtensionConfig } from '@pterodactyl/sdk/vite'; export default defineExtensionConfig({ entry: 'src/client/index.tsx' }); ``` -`vite build` → `dist/client.js`, referenced from your `extension.json`: +`vite build` emits `dist/client.js`, referenced from your `extension.json`: ```json { @@ -72,19 +72,19 @@ minor versions, removals are majors. Screen IDs, paths, navigation, and permissions live in `ui.screens` in the manifest. A screen's `permission` list names the subuser permissions needed to open it and is only accepted on `server` screens; account and admin screens are open to every signed-in user and every root admin respectively. Register each declared screen with `screens.register(id, importer)` during synchronous `setup`. Paths use a static first segment and may include named parameters such as `votes/$tab` (the panel reserves `$id`); duplicate paths, duplicate parameter patterns, and core route collisions reject the offending extension. Screen components receive a `data` prop (`ScreenComponentProps`) with the current `pathname`, `search`, and `params`, so `votes/$tab` reads its value from `data.params.tab`. -The panel renders before optional bundles finish importing. Each extension commits atomically when ready; slot display order follows the configured extension order. Screens show local loading state while their bundle or chunk loads. Slots have individual Suspense and error boundaries, and SDK websocket callbacks are isolated and attributed to their mod. Native extensions still execute in the panel's JavaScript environment; boundaries are not a sandbox and cannot interrupt synchronous code. +The panel renders before optional bundles finish importing. Each extension commits atomically when ready; slot display order follows the configured extension order. Screens show local loading state while their bundle or chunk loads. Slots have individual Suspense and error boundaries, and SDK websocket callbacks are isolated and attributed to their mod. Native extensions execute in the panel's JavaScript environment; boundaries are not a sandbox and cannot interrupt synchronous code. Recoverable render/query failures offer Retry. Failed screen chunks offer an explicit page reload because resetting an error boundary cannot evict a rejected browser module. Enabling, disabling, updating, or changing frontend configuration takes effect on the next full page load; reload after management changes. Already evaluated JavaScript is not unloaded dynamically. ## Types and shared dependencies -The panel currently supports the React 19.3 client API. Server-only caching APIs, development-only `captureOwnerStack`, and unstable cache-refresh APIs are not part of the shared React facade. React, React DOM, JSX runtime, Query, and SDK entry points stay external through the Vite preset. +The panel supports the React 19.3 client API. Server-only caching APIs, development-only `captureOwnerStack`, and unstable cache-refresh APIs are not part of the shared React facade. React, React DOM, JSX runtime, Query, and SDK entry points stay external through the Vite preset. SDK declarations are generated from the runtime public surface with `npm run sdk:generate` at the panel root. `npm run sdk:check` checks reproducibility and compiles a packed-package consumer, including negative type cases. Component props, form fields, and `useCurrentServer(server => server.attributes.name)` preserve their actual types. SDK peer dependencies include the existing libraries referenced by those declarations; use SDK form hooks/components to share the panel's bound form contexts. Declare screen metadata in the manifest and register each implementation by ID with `screens.register`. Build extensions against the SDK version used by the panel. -A `file:` dependency on `packages/sdk` is a link into the panel checkout. TypeScript follows links to their real location by default, so the SDK declarations would take React, TanStack Query and the other peers from the panel's `node_modules` while your code takes them from yours; when the versions differ, `useQuery(serverFileContentQueryOptions(...))` fails on two unrelated `QueryClient` types. Scaffolded extensions set `"preserveSymlinks": true` in `tsconfig.json`, which resolves the SDK's peers from the extension, the same way the Vitest preset does at runtime. Add that option to an extension scaffolded earlier and remove any `paths` entries for `react`, `@tanstack/react-query` or `lucide-react`. An SDK installed from a tarball or registry needs neither. +A `file:` dependency on `packages/sdk` is a link into the panel checkout. TypeScript follows links to their real location by default, so the SDK declarations would take React, TanStack Query and the other peers from the panel's `node_modules` while your code takes them from yours; when the versions differ, `useQuery(serverFileContentQueryOptions(...))` fails on two unrelated `QueryClient` types. Scaffolded extensions set `"preserveSymlinks": true` in `tsconfig.json`, which resolves the SDK's peers from the extension, the same way the Vitest preset does at runtime. Do not add `paths` entries for `react`, `@tanstack/react-query` or `lucide-react`. An SDK installed from a tarball or registry needs neither option. ## Resource hooks and native data @@ -263,8 +263,8 @@ A provider reads its settings with `$this->settings()`. Code outside the provide a controller or a job, uses the `Pterodactyl\Facades\Extensions` facade: `Extensions::settings('billing')` returns the same settings, and `Extensions::isAvailable('billing')` tells whether an extension is enabled and running. -`app(ExtensionManager::class)->settings('billing')`, which earlier scaffolds suggested, -still works but is deprecated. +Both return an `ExtensionSettings`: `get($key, $default)`, `set($key, $value)`, and +`setSecret($key, $value)`, which stores the value encrypted. Backend settings support `forUser($user)` and `forServer($server)`. Mark secrets with `->secret()` to encrypt storage, mask admin output as `********`, and prohibit frontend @@ -375,8 +375,11 @@ failed provisioning is cleaned up, suspension fires only for a change Wings acce ### Wrapping core actions `wrapAction($contract, $decorator)` runs extension code around any action contract under -`Pterodactyl\Contracts\` that the panel binds. The decorator receives the implementation that -would otherwise be used and returns an implementation of the same contract: +`Pterodactyl\Contracts\` that the panel binds per caller (not as a shared singleton). The +wrapper runs around every call to that contract, including the calls core makes internally, +such as `DeleteServer` dropping databases through `DeletesDatabases`. The decorator receives +the implementation that would otherwise be used and returns an implementation of the same +contract: ```php $this->wrapAction(DeletesServers::class, fn (DeletesServers $inner): DeletesServers => new PurgeDnsRecords($inner, $this->app->make(DnsRecords::class))); @@ -403,14 +406,19 @@ final class PurgeDnsRecords implements DeletesServers } ``` -A few core actions call out only after their own transaction commits, so wrappers of the -nested contracts run outside it. When creating a backup rotates out an old one, -`DeletesBackups` runs after the new backup is recorded and Wings has accepted it. During -server deletion, `DeletesDatabases` runs after the server and its database rows are -deleted, so the `Database` it receives no longer exists in the panel, and a failure is -reported instead of failing the deletion. The Wings call that starts a transfer also runs -after the transfer is recorded; if Wings rejects it, the transfer is marked failed through -`FailsTransfers`. +These core actions order their work as follows, and wrappers of the contracts they call +run outside their transactions: + +- `InitiatesBackups` creates the backup row in a transaction, then asks Wings to start the + backup. A backup Wings rejects is stored as failed. Backups rotated out to make room are + deleted through `DeletesBackups` only after Wings accepts the new one; a failed rotation + delete is reported, not thrown. +- `DeletesServers` deletes the panel rows in a transaction, then drops each remote database + through `DeletesDatabases`. The `Database` it passes is already deleted from the panel. A + failed drop is reported and the rest are dropped. +- `InitiatesTransfers` calls Wings after the transfer records commit. A transfer Wings + rejects is marked failed through `FailsTransfers`. +- `RotatesDatabasePasswords` finishes before the controller writes the activity log entry. The wrapper owns the call: it decides whether and when to invoke the inner action and must forward fluent options such as `withForce()` itself, returning itself. Whatever it @@ -422,6 +430,19 @@ resolves. Extensions wrap in load order, the last one outermost. The actions tha enable, disable, remove and configure extensions (`Contracts\Extensions\*`) and apply themes (`Contracts\Themes\*`) cannot be wrapped; asking for one fails the provider's boot. +Core controllers resolve these contracts, not the classes behind them. Renaming a server from the client API calls +`UpdatesServerDetails`. Toggling a backup lock from the admin API calls `TogglesBackupLocks`. +Deleting an allocation block calls `DeletesAllocations` once per allocation. Disabling +two-factor, by an admin or by the user, calls `DisablesTwoFactor`, which clears the TOTP +secret. Changing a Docker image calls `UpdatesServerDockerImage`, both from the client +endpoint and when an admin startup update (`UpdatesServerStartup`) sets the image. +`UpdatesEggs`, `UpdatesEggInstallScripts` and `UpdatesEggVariables` return the updated model. +Mounts (`CreatesMounts`, `UpdatesMounts`, `DeletesMounts`, `AttachesEggsToMounts`, +`AttachesNodesToMounts`, `DetachesEggsFromMounts`, `DetachesNodesFromMounts`), tags +(`CreatesTags`, `UpdatesTags`, `DeletesTags`), API keys (`UpdatesApiKeys`, `DeletesApiKeys`), +egg variable deletion (`DeletesEggVariables`) and the server install-status toggle +(`TogglesServerInstallStatus`) have contracts of their own as well. + Resolve the same contracts from the container to call core behaviour instead of reimplementing it. Beside the mutating actions, these read or complete on your behalf: diff --git a/pint.json b/pint.json index 15b3b9a32..3f39449dc 100644 --- a/pint.json +++ b/pint.json @@ -1,5 +1,6 @@ { "preset": "laravel", + "notPath": ["rules/tests/Rules/data", "rules/tests/Integration/data"], "rules": { "array_push": true, "backtick_to_shell_exec": true, diff --git a/resources/lang/en/auth.php b/resources/lang/en/auth.php index f4649a5b4..68c05ee0a 100644 --- a/resources/lang/en/auth.php +++ b/resources/lang/en/auth.php @@ -25,5 +25,4 @@ return [ 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', 'password_requirements' => 'Password must be at least 8 characters in length and should be unique to this site.', - '2fa_must_be_enabled' => 'The administrator has required that 2-Factor Authentication be enabled for your account in order to use the Panel.', ]; diff --git a/resources/scripts/api/activity.spec.ts b/resources/scripts/api/activity.spec.ts new file mode 100644 index 000000000..58efc0cbc --- /dev/null +++ b/resources/scripts/api/activity.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { activityLogQuery } from '@/api/activity'; + +describe('activityLogQuery', () => { + it('always includes the actor', () => { + expect(activityLogQuery()).toEqual({ include: 'actor' }); + expect(activityLogQuery({})).toEqual({ include: 'actor' }); + }); + + it('passes the page through', () => { + expect(activityLogQuery({ page: 3 })).toEqual({ include: 'actor', page: 3 }); + expect(activityLogQuery({ page: 0 })).toEqual({ include: 'actor', page: 0 }); + }); + + it('filters by event name', () => { + expect(activityLogQuery({ filters: { event: 'server:power.start' } })).toEqual({ + include: 'actor', + 'filter[event_name]': 'server:power.start', + }); + expect(activityLogQuery({ filters: { event: ['auth:fail', 'auth:success'] } })).toEqual({ + include: 'actor', + 'filter[event_name]': 'auth:fail,auth:success', + }); + }); + + it.each([null, ''])('omits an empty event filter (%j)', (event) => { + expect(activityLogQuery({ filters: { event } })).toEqual({ include: 'actor' }); + }); + + it('converts a numeric user filter to a number', () => { + expect(activityLogQuery({ filters: { user: '12' } })).toEqual({ include: 'actor', 'filter[user_id]': 12 }); + expect(activityLogQuery({ filters: { user: 7 } })).toEqual({ include: 'actor', 'filter[user_id]': 7 }); + }); + + it.each(['abc', '12abc', 'Infinity', '', null])('drops a non-numeric user filter (%j)', (user) => { + expect(activityLogQuery({ filters: { user } })).toEqual({ include: 'actor' }); + }); + + it.each([ + [-1, '-timestamp'], + ['desc', '-timestamp'], + [1, 'timestamp'], + ['asc', 'timestamp'], + ] as const)('maps sort %j to %s', (timestamp, sort) => { + expect(activityLogQuery({ sorts: { timestamp } })).toEqual({ include: 'actor', sort }); + }); + + it.each([0, null] as const)('omits an unknown sort (%j)', (timestamp) => { + expect(activityLogQuery({ sorts: { timestamp } })).toEqual({ include: 'actor' }); + }); + + it('combines every parameter', () => { + expect( + activityLogQuery({ page: 2, filters: { event: 'user:create', user: '5' }, sorts: { timestamp: 'asc' } }) + ).toEqual({ + include: 'actor', + page: 2, + 'filter[event_name]': 'user:create', + 'filter[user_id]': 5, + sort: 'timestamp', + }); + }); +}); diff --git a/resources/scripts/api/admin/extensions/queries.spec.ts b/resources/scripts/api/admin/extensions/queries.spec.ts new file mode 100644 index 000000000..4a686e74d --- /dev/null +++ b/resources/scripts/api/admin/extensions/queries.spec.ts @@ -0,0 +1,90 @@ +import { AxiosError, AxiosHeaders } from 'axios'; +import { describe, expect, it } from 'vitest'; +import { extensionReplacement } from './queries'; + +/** Conflict meta as the install endpoint sends it, loosened to cover malformed values. */ +type ConflictMeta = { + identifier?: string | number; + version?: string | null; + installed_version?: string | number; + enabled?: boolean | string; +}; + +type ConflictBody = null | { + errors?: string | readonly { code?: string; detail?: string; meta?: ConflictMeta | string }[]; +}; + +const failure = (status: number, data: ConflictBody) => { + const config = { headers: new AxiosHeaders() }; + + return new AxiosError('Request failed', AxiosError.ERR_BAD_REQUEST, config, undefined, { + status, + statusText: '', + headers: {}, + config, + data, + }); +}; + +const conflict = (meta: ConflictMeta | string) => + failure(409, { errors: [{ code: 'ExtensionAlreadyInstalled', meta }] }); + +describe('extensionReplacement', () => { + it('reads the installed extension from a 409', () => { + expect( + extensionReplacement( + conflict({ identifier: 'billing', version: '2.0.0', installed_version: '1.4.0', enabled: true }) + ) + ).toEqual({ id: 'billing', version: '2.0.0', installedVersion: '1.4.0', enabled: true }); + }); + + it('defaults the optional fields', () => { + expect(extensionReplacement(conflict({ identifier: 'billing', version: null }))).toEqual({ + id: 'billing', + version: '', + installedVersion: null, + enabled: false, + }); + }); + + it('only treats a literal true as enabled', () => { + expect( + extensionReplacement( + conflict({ identifier: 'billing', version: '2.0.0', installed_version: 3, enabled: 'true' }) + ) + ).toEqual({ id: 'billing', version: '2.0.0', installedVersion: null, enabled: false }); + }); + + it.each([new Error('boom'), 'conflict', null, undefined])('returns null for a non-axios cause (%s)', (cause) => { + expect(extensionReplacement(cause)).toBeNull(); + }); + + it('returns null for a status other than 409', () => { + expect( + extensionReplacement(failure(422, { errors: [{ meta: { identifier: 'x', version: '1' } }] })) + ).toBeNull(); + }); + + it('returns null for an axios error without a response', () => { + expect(extensionReplacement(new AxiosError('Network Error', AxiosError.ERR_NETWORK))).toBeNull(); + }); + + it.each([ + ['no body', null], + ['no errors', {}], + ['errors not an array', { errors: 'conflict' }], + ['empty errors', { errors: [] }], + ['no meta', { errors: [{ detail: 'Already installed.' }] }], + ['meta not an object', { errors: [{ meta: 'billing' }] }], + ])('returns null for a 409 with %s', (_label, data) => { + expect(extensionReplacement(failure(409, data))).toBeNull(); + }); + + it.each([ + ['no identifier', { version: '1.0.0' }], + ['no version', { identifier: 'billing' }], + ['non-string identifier', { identifier: 7, version: '1.0.0' }], + ])('returns null when meta has %s', (_label, meta) => { + expect(extensionReplacement(conflict(meta))).toBeNull(); + }); +}); diff --git a/resources/scripts/api/http.spec.ts b/resources/scripts/api/http.spec.ts new file mode 100644 index 000000000..89c819ac6 --- /dev/null +++ b/resources/scripts/api/http.spec.ts @@ -0,0 +1,77 @@ +import { AxiosError, AxiosHeaders } from 'axios'; +import { describe, expect, it } from 'vitest'; +import { httpErrorToHuman } from '@/api/http'; + +const FALLBACK = 'An unexpected error occurred.'; + +/** The bodies these cases send, including malformed ones the parser has to tolerate. */ +type ResponseBody = + | string + | null + | readonly string[] + | { errors?: readonly { detail?: string | number | { text: string } }[]; error?: string | number }; + +const failure = (data?: ResponseBody) => { + const config = { headers: new AxiosHeaders() }; + + return new AxiosError( + 'Request failed with status code 422', + AxiosError.ERR_BAD_REQUEST, + config, + undefined, + data === undefined ? undefined : { status: 422, statusText: '', headers: {}, config, data } + ); +}; + +describe('httpErrorToHuman', () => { + it('prefers the first JSON:API error detail', () => { + const error = failure({ errors: [{ detail: 'Name is required.' }, { detail: 'Other' }], error: 'Wings' }); + + expect(httpErrorToHuman(error)).toBe('Name is required.'); + }); + + it('parses a string body that holds JSON', () => { + expect(httpErrorToHuman(failure(JSON.stringify({ errors: [{ detail: 'From text.' }] })))).toBe('From text.'); + expect(httpErrorToHuman(failure(JSON.stringify({ error: 'Wings text.' })))).toBe('Wings text.'); + }); + + it('reads a Wings-style error body', () => { + expect(httpErrorToHuman(failure({ error: 'Disk is full.' }))).toBe('Disk is full.'); + }); + + it('falls back to the error message for a non-JSON string body', () => { + expect(httpErrorToHuman(failure('Bad Gateway'))).toBe('Request failed with status code 422'); + }); + + it('ignores a detail that is not a string', () => { + expect(httpErrorToHuman(failure({ errors: [{ detail: 42 }], error: 'Wings fallback.' }))).toBe( + 'Wings fallback.' + ); + expect(httpErrorToHuman(failure({ errors: [{ detail: { text: 'x' } }] }))).toBe( + 'Request failed with status code 422' + ); + }); + + it('ignores bodies without a recognised message', () => { + expect(httpErrorToHuman(failure({ errors: [] }))).toBe('Request failed with status code 422'); + expect(httpErrorToHuman(failure({ error: 500 }))).toBe('Request failed with status code 422'); + expect(httpErrorToHuman(failure(['not', 'an', 'object']))).toBe('Request failed with status code 422'); + }); + + it('uses the error message when there is no response or no data', () => { + expect(httpErrorToHuman(failure())).toBe('Request failed with status code 422'); + expect(httpErrorToHuman(failure(''))).toBe('Request failed with status code 422'); + expect(httpErrorToHuman(failure(null))).toBe('Request failed with status code 422'); + }); + + it('uses the message of a plain Error', () => { + expect(httpErrorToHuman(new Error('Network down'))).toBe('Network down'); + }); + + it.each([undefined, null, 'oops', 42, { detail: 'not an error' }])( + 'returns the generic fallback for non-Error cause %s', + (cause) => { + expect(httpErrorToHuman(cause)).toBe(FALLBACK); + } + ); +}); diff --git a/resources/scripts/components/elements/SubNavigation.spec.tsx b/resources/scripts/components/elements/SubNavigation.spec.tsx new file mode 100644 index 000000000..04555aeeb --- /dev/null +++ b/resources/scripts/components/elements/SubNavigation.spec.tsx @@ -0,0 +1,165 @@ +/** @vitest-environment jsdom */ +import { cleanup, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import SubNavigation from './SubNavigation'; + +interface Layout { + rowWidth: number; + moreWidth: number; + direction: 'row' | 'column'; +} + +interface Item { + label: string; + width: number; + core?: boolean; + active?: boolean; +} + +let layout: Layout; + +const rect = (left: number, width: number) => DOMRect.fromRect({ x: left, y: 0, width, height: 40 }); + +/** Lays the row's items out left to right at their `data-width`, starting at x = 0 with no padding. */ +function fakeRect(this: HTMLElement): DOMRect { + const parent = this.parentElement; + + if (parent?.dataset.testid === 'nav') { + return rect(0, layout.rowWidth); + } + + if (this.dataset.width === undefined) { + return rect(0, layout.moreWidth); + } + + let left = 0; + + for (let sibling = this.previousElementSibling; sibling instanceof HTMLElement;) { + left += Number(sibling.dataset.width ?? 0); + sibling = sibling.previousElementSibling; + } + + return rect(left, Number(this.dataset.width)); +} + +const renderNavigation = (items: Item[]) => + render( + + {items.map((item) => ( + + {item.label} + + ))} + + ); + +const overflowed = () => + screen + .getAllByRole('link') + .filter((link) => link.hasAttribute('data-overflowed')) + .map((link) => link.textContent); + +const moreToggle = () => screen.getByText('More').closest('span')!; + +describe('SubNavigation overflow', () => { + beforeEach(() => { + layout = { rowWidth: 400, moreWidth: 50, direction: 'row' }; + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + disconnect() {} + } + ); + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(fakeRect); + + const computedStyle = window.getComputedStyle.bind(window); + + vi.spyOn(window, 'getComputedStyle').mockImplementation((element) => { + const style = computedStyle(element); + + style.paddingLeft = '0px'; + style.paddingRight = '0px'; + style.marginLeft = '0px'; + style.flexDirection = layout.direction; + + return style; + }); + }); + + afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it('shows every item when they fit', () => { + renderNavigation([ + { label: 'Console', width: 100 }, + { label: 'Files', width: 100 }, + { label: 'Backups', width: 100 }, + ]); + + expect(overflowed()).toEqual([]); + expect(screen.getByTestId('nav')).not.toHaveAttribute('data-collapsed'); + expect(moreToggle().hidden).toBe(true); + }); + + it('keeps core and active items, then fills the rest in order', () => { + renderNavigation([ + { label: 'Console', width: 100, core: true }, + { label: 'Files', width: 100 }, + { label: 'Backups', width: 100 }, + { label: 'Startup', width: 100, active: true }, + { label: 'Settings', width: 40 }, + ]); + + // Budget is 400 - 50 = 350: Console + Startup + Files fill 300, Backups would exceed it, + // and filling stops there even though Settings alone would still fit. + expect(overflowed()).toEqual(['Backups', 'Settings']); + expect(screen.getByTestId('nav')).not.toHaveAttribute('data-collapsed'); + expect(moreToggle().hidden).toBe(false); + }); + + it('collapses when the core items alone exceed the budget', () => { + renderNavigation([ + { label: 'Console', width: 200, core: true }, + { label: 'Files', width: 200, core: true }, + { label: 'Backups', width: 100 }, + ]); + + expect(screen.getByTestId('nav')).toHaveAttribute('data-collapsed'); + expect(overflowed()).toEqual([]); + expect(moreToggle().hidden).toBe(true); + expect(screen.getByRole('button', { name: /Navigation/ })).toHaveAttribute('aria-expanded', 'false'); + }); + + it('names the collapsed toggle after the active item', () => { + renderNavigation([ + { label: 'Console', width: 300, core: true }, + { label: 'Files', width: 150, core: true, active: true }, + ]); + + expect(screen.getByTestId('nav')).toHaveAttribute('data-collapsed'); + expect(screen.getByRole('button', { name: /^Files$/ })).toHaveAttribute('aria-expanded', 'false'); + }); + + it('never overflows a column layout', () => { + layout.direction = 'column'; + renderNavigation([ + { label: 'Console', width: 300, core: true }, + { label: 'Files', width: 300 }, + { label: 'Backups', width: 300 }, + ]); + + expect(overflowed()).toEqual([]); + expect(screen.getByTestId('nav')).not.toHaveAttribute('data-collapsed'); + expect(moreToggle().hidden).toBe(true); + }); +}); diff --git a/tests/Integration/Actions/Servers/DeleteServerTest.php b/tests/Integration/Actions/Servers/DeleteServerTest.php index 4f23a9ad0..0430e5626 100644 --- a/tests/Integration/Actions/Servers/DeleteServerTest.php +++ b/tests/Integration/Actions/Servers/DeleteServerTest.php @@ -130,6 +130,40 @@ test('exception while deleting databases does not abort if force deleted', funct $this->assertDatabaseMissing('servers', ['id' => $server->id]); $this->assertDatabaseMissing('databases', ['id' => $db->id]); }); +test('databases on different hosts are each dropped on their own host', function (): void { + $server = $this->createServerModel(); + $first = DatabaseHost::factory()->create(); + $second = DatabaseHost::factory()->create(); + /** @var Database $a */ + $a = Database::factory()->create(['database_host_id' => $first->id, 'server_id' => $server->id]); + /** @var Database $b */ + $b = Database::factory()->create(['database_host_id' => $second->id, 'server_id' => $server->id]); + $server->refresh(); + + // Record which host the dynamic connection points at for each drop. Resolving the + // connection does not open a socket, so no real database host is needed. + $gateway = new class extends FakeDatabaseHostGateway + { + /** @var array */ + public array $hosts = []; + + public function dropDatabase(string $database): bool + { + $this->hosts[$database] = DB::connection($this->getConnection())->getConfig('host'); + + return parent::dropDatabase($database); + } + }; + $this->app->instance(DatabaseHostGateway::class, $gateway); + + try { + getService()->delete($server); + } finally { + DB::purge(DatabaseHostGateway::DEFAULT_CONNECTION_NAME); + } + + expect($gateway->hosts)->toBe([$a->database => $first->host, $b->database => $second->host]); +}); function getService(): DeletesServers { return (fn () => $this->app->make(DeletesServers::class))->call(pterodactylTestCase()); diff --git a/tests/Integration/Actions/Servers/UpdateServerStartupTest.php b/tests/Integration/Actions/Servers/UpdateServerStartupTest.php index 5bdf6c344..ac22efd85 100644 --- a/tests/Integration/Actions/Servers/UpdateServerStartupTest.php +++ b/tests/Integration/Actions/Servers/UpdateServerStartupTest.php @@ -8,6 +8,8 @@ use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Validation\ValidationException; +use Pterodactyl\Actions\Servers\UpdateServerDockerImage; +use Pterodactyl\Contracts\Servers\UpdatesServerDockerImage; use Pterodactyl\Contracts\Servers\UpdatesServerStartup; use Pterodactyl\Models\Egg; use Pterodactyl\Models\Server; @@ -18,7 +20,7 @@ use Pterodactyl\Tests\Integration\IntegrationTestCase; use function pterodactylTestCase; uses(IntegrationTestCase::class, DatabaseTransactions::class); -test('non admin can modify server variables', function () { +test('non admin can modify server variables', function (): void { $server = $this->createServerModel(); try { $this->app->make(UpdatesServerStartup::class)->update($server, ['egg_id' => $server->egg_id + 1, 'environment' => ['BUNGEE_VERSION' => '$$', 'SERVER_JARFILE' => 'server.jar']]); @@ -32,6 +34,7 @@ test('non admin can modify server variables', function () { expect($errors['environment.BUNGEE_VERSION'])->toHaveCount(1); expect($errors['environment.BUNGEE_VERSION'][0])->toBe('The Bungeecord Version variable may only contain letters and numbers.'); } + ServerVariable::query()->where('variable_id', $server->variables[1]->id)->delete(); $result = getService()->update($server, ['egg_id' => $server->egg_id + 1, 'startup' => 'random gibberish', 'environment' => ['BUNGEE_VERSION' => '1234', 'SERVER_JARFILE' => 'test.jar']]); expect($result)->toBeInstanceOf(Server::class); @@ -40,7 +43,7 @@ test('non admin can modify server variables', function () { expect($result->variables[0]->server_value)->toBe('1234'); expect($result->variables[1]->server_value)->toBe('test.jar'); }); -test('server is properly modified as admin user', function () { +test('server is properly modified as admin user', function (): void { /** @var Egg $nextEgg */ $nextEgg = Egg::query()->where('id', '!=', 1)->firstOrFail(); $server = $this->createServerModel(['egg_id' => 1]); @@ -55,9 +58,10 @@ test('server is properly modified as admin user', function () { // as not installed when you modify the startup... expect($response->isInstalled())->toBeTrue(); }); -test('environment variables can be updated by admin', function () { +test('environment variables can be updated by admin', function (): void { $server = $this->createServerModel(); $server->loadMissing(['egg', 'variables']); + $clone = $this->cloneEggAndVariables($server->egg); // This makes the BUNGEE_VERSION variable not user editable. $clone->variables()->first()->update(['user_editable' => false]); @@ -68,14 +72,16 @@ test('environment variables can be updated by admin', function () { expect($response->variables)->toHaveCount(2); expect($response->variables[0]->server_value)->toBe('EXIST'); expect($response->variables[1]->server_value)->toBe('test.jar'); + $response = getService()->update($server, ['environment' => ['BUNGEE_VERSION' => '1234', 'SERVER_JARFILE' => 'test.jar']], User::USER_LEVEL_ADMIN); expect($response->variables)->toHaveCount(2); expect($response->variables[0]->server_value)->toBe('1234'); expect($response->variables[1]->server_value)->toBe('test.jar'); }); -test('admin egg change keeps matching variables and falls back to the new egg defaults', function () { +test('admin egg change keeps matching variables and falls back to the new egg defaults', function (): void { $server = $this->createServerModel(['startup' => 'old startup', 'image' => 'old/image']); $server->loadMissing('egg'); + $nextEgg = $this->cloneEggAndVariables($server->egg); $nextEgg->forceFill(['startup' => 'new egg startup', 'docker_images' => ['Default' => 'new/image']])->save(); $previous = $server->variables->pluck('id', 'env_variable'); @@ -90,22 +96,51 @@ test('admin egg change keeps matching variables and falls back to the new egg de expect(ServerVariable::query()->where('server_id', $server->id)->whereIn('variable_id', $previous->values())->count())->toBe(0); expect(ServerVariable::query()->where('server_id', $server->id)->count())->toBe(2); }); -test('non admin cannot move a server to another egg', function () { +test('non admin cannot move a server to another egg', function (): void { $server = $this->createServerModel(); $server->loadMissing('egg'); + $nextEgg = $this->cloneEggAndVariables($server->egg); $response = getService()->update($server, ['egg_id' => $nextEgg->id, 'environment' => ['BUNGEE_VERSION' => '1234', 'SERVER_JARFILE' => 'test.jar']]); expect($response->egg_id)->toBe($server->egg_id); expect($response->startup)->toBe($server->startup); }); -test('invalid egg id triggers exception', function () { +test('admin image changes go through the docker image contract only when the image changes', function (): void { + $spy = new class(new UpdateServerDockerImage()) implements UpdatesServerDockerImage + { + /** @var list */ + public array $images = []; + + public function __construct(private readonly UpdatesServerDockerImage $inner) {} + + public function update(Server $server, string $image): Server + { + $this->images[] = $image; + + return $this->inner->update($server, $image); + } + }; + $this->app->instance(UpdatesServerDockerImage::class, $spy); + $server = $this->createServerModel(['image' => 'old/image']); + + // Users never change the image, and an unchanged image is not written again. + getService()->update($server, ['docker_image' => 'user/image']); + getService()->update($server, ['startup' => 'same image', 'docker_image' => 'old/image'], User::USER_LEVEL_ADMIN); + + expect($spy->images)->toBe([]); + + $response = getService()->update($server, ['startup' => 'new startup', 'docker_image' => 'new/image'], User::USER_LEVEL_ADMIN); + + expect($spy->images)->toBe(['new/image']) + ->and($response->image)->toBe('new/image') + ->and($response->startup)->toBe('new startup'); +}); +test('invalid egg id triggers exception', function (): void { $server = $this->createServerModel(); $this->expectException(ModelNotFoundException::class); getService()->update($server, ['egg_id' => 123456789], User::USER_LEVEL_ADMIN); }); function getService(): UpdatesServerStartup { - return (function () { - return $this->app->make(UpdatesServerStartup::class); - })->call(pterodactylTestCase()); + return (fn () => $this->app->make(UpdatesServerStartup::class))->call(pterodactylTestCase()); } diff --git a/tests/Integration/Extensions/DynamicDatabaseConnectionTest.php b/tests/Integration/Extensions/DynamicDatabaseConnectionTest.php new file mode 100644 index 000000000..d167046de --- /dev/null +++ b/tests/Integration/Extensions/DynamicDatabaseConnectionTest.php @@ -0,0 +1,37 @@ +create(['port' => 3306, 'username' => 'first']); + $second = DatabaseHost::factory()->create(['port' => 3307, 'username' => 'second']); + $dynamic = new DynamicDatabaseConnection(); + + $dynamic->set('dynamic', $first); + + $resolved = DB::connection('dynamic'); + expect($resolved->getConfig('host'))->toBe($first->host); + + $dynamic->set('dynamic', $second->id, 'panel'); + $connection = DB::connection('dynamic'); + + expect($connection)->not->toBe($resolved) + ->and($connection->getConfig('host'))->toBe($second->host) + ->and($connection->getConfig('port'))->toBe(3307) + ->and($connection->getConfig('username'))->toBe('second') + ->and($connection->getConfig('database'))->toBe('panel'); +}); diff --git a/tests/Support/Fakes/FakeDaemonServer.php b/tests/Support/Fakes/FakeDaemonServer.php index 44fd40b7f..69da626b9 100644 --- a/tests/Support/Fakes/FakeDaemonServer.php +++ b/tests/Support/Fakes/FakeDaemonServer.php @@ -61,11 +61,6 @@ class FakeDaemonServer extends FakeDaemonHttpClient Assert::assertNotEmpty($this->callsFor('reinstall'), 'Expected daemon server reinstall to have been called.'); } - public function assertArchiveRequested(): void - { - Assert::assertNotEmpty($this->callsFor('requestArchive'), 'Expected daemon server archive request to have been called.'); - } - public function assertDetailsFetched(): void { Assert::assertNotEmpty($this->callsFor('getDetails'), 'Expected daemon server details to have been fetched.'); @@ -91,7 +86,7 @@ class FakeDaemonServer extends FakeDaemonHttpClient return $this->reply(); } - if (! preg_match('#^/api/servers/([^/]+)(?:/(sync|reinstall|archive|logs))?$#', $path, $matches)) { + if (! preg_match('#^/api/servers/([^/]+)(?:/(sync|reinstall|logs))?$#', $path, $matches)) { return null; } @@ -100,7 +95,6 @@ class FakeDaemonServer extends FakeDaemonHttpClient ['DELETE', ''] => 'delete', ['POST', 'sync'] => 'sync', ['POST', 'reinstall'] => 'reinstall', - ['POST', 'archive'] => 'requestArchive', ['GET', 'logs'] => 'getLogs', default => null, }; diff --git a/tests/Support/Fakes/FakeDatabaseHostGateway.php b/tests/Support/Fakes/FakeDatabaseHostGateway.php index 237c15ed0..7e801e280 100644 --- a/tests/Support/Fakes/FakeDatabaseHostGateway.php +++ b/tests/Support/Fakes/FakeDatabaseHostGateway.php @@ -41,23 +41,6 @@ class FakeDatabaseHostGateway extends DatabaseHostGateway public int $flushCount = 0; - private string $connection = DatabaseHostGateway::DEFAULT_CONNECTION_NAME; - - public function __construct() {} - - public function setConnection(string $connection): self - { - $this->connection = $connection; - $this->calls[] = ['method' => 'setConnection', 'args' => [$connection]]; - - return $this; - } - - public function getConnection(): string - { - return $this->connection; - } - public function createDatabase(string $database): bool { $this->calls[] = ['method' => 'createDatabase', 'args' => [$database]]; diff --git a/tests/Unit/Services/Extensions/ExtensionRepositoryTest.php b/tests/Unit/Services/Extensions/ExtensionRepositoryTest.php index b743c1958..2150d03de 100644 --- a/tests/Unit/Services/Extensions/ExtensionRepositoryTest.php +++ b/tests/Unit/Services/Extensions/ExtensionRepositoryTest.php @@ -8,7 +8,6 @@ use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\File; use Pterodactyl\Events\Extensions\ExtensionLoadFailed; use Pterodactyl\Facades\Extensions; -use Pterodactyl\Services\Extensions\ExtensionManager; use Pterodactyl\Services\Extensions\ExtensionManifestValidator; use Pterodactyl\Services\Extensions\ExtensionProviderLoader; use Pterodactyl\Services\Extensions\ExtensionRepository; @@ -17,15 +16,15 @@ use Pterodactyl\Tests\TestCase; use function pterodactylTestCase; uses(TestCase::class); -beforeEach(function () { +beforeEach(function (): void { $this->directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'ptero-extensions-'.uniqid(); File::ensureDirectoryExists($this->directory); config(['extensions.directory' => $this->directory]); }); -afterEach(function () { +afterEach(function (): void { File::deleteDirectory($this->directory); }); -test('discovers valid packages and records invalid ones', function () { +test('discovers valid packages and records invalid ones', function (): void { writeExtension('alpha', ['id' => 'alpha', 'name' => 'Alpha', 'version' => '1.0.0']); writeExtension('broken', ['id' => 'broken', 'name' => '', 'version' => '1.0.0']); // Directory name not matching the manifest id is rejected. @@ -36,7 +35,7 @@ test('discovers valid packages and records invalid ones', function () { expect($repository->discoveryErrors())->toHaveKey('broken'); expect($repository->discoveryErrors())->toHaveKey('renamed'); }); -test('nothing is enabled without install records', function () { +test('nothing is enabled without install records', function (): void { writeExtension('alpha', ['id' => 'alpha', 'name' => 'Alpha', 'version' => '1.0.0']); $repository = repository(); // No extensions table in the unit test database — records() degrades to @@ -44,7 +43,7 @@ test('nothing is enabled without install records', function () { expect($repository->enabled()->isEmpty())->toBeTrue(); expect($repository->frontendPayload(authenticated: true))->toBe([]); }); -test('provider boot failures are caught', function () { +test('provider boot failures are caught', function (): void { Event::fake([ExtensionLoadFailed::class]); writeExtension('broken', ['id' => 'broken', 'name' => 'Broken', 'version' => '1.0.0', 'provider' => 'BrokenExtension\Provider', 'autoload' => ['BrokenExtension\\' => 'src']]); $src = $this->directory.DIRECTORY_SEPARATOR.'broken'.DIRECTORY_SEPARATOR.'src'; @@ -67,14 +66,13 @@ test('provider boot failures are caught', function () { $manifest = (new ExtensionManifestValidator)->fromDirectory($this->directory.DIRECTORY_SEPARATOR.'broken'); $repository = repository(); (new ExtensionProviderLoader(pterodactylTestCase()->app, $repository))->registerProviders(collect([$manifest->id => $manifest])); - Event::assertDispatched(ExtensionLoadFailed::class, fn (ExtensionLoadFailed $event) => $event->identifier === 'broken' && $event->phase === 'boot' && str_contains($event->reason, 'boot failed')); + Event::assertDispatched(ExtensionLoadFailed::class, fn (ExtensionLoadFailed $event): bool => $event->identifier === 'broken' && $event->phase === 'boot' && str_contains($event->reason, 'boot failed')); }); -test('the facade and the deprecated manager hand out the same settings as the repository', function () { +test('the facade hands out the same settings as the repository', function (): void { $settings = repository()->settings('alpha'); expect(Extensions::settings('alpha'))->toBe($settings); expect(Extensions::isAvailable('alpha'))->toBeFalse(); - expect(app(ExtensionManager::class)->settings('alpha'))->toBe($settings); }); function repository(): ExtensionRepository { @@ -87,9 +85,10 @@ function repository(): ExtensionRepository return $repository; })->call(pterodactylTestCase()); } + function writeExtension(string $directory, array $manifest): void { - (function () use ($directory, $manifest) { + (function () use ($directory, $manifest): void { $path = $this->directory.DIRECTORY_SEPARATOR.$directory; File::ensureDirectoryExists($path); file_put_contents($path.DIRECTORY_SEPARATOR.'extension.json', json_encode($manifest)); diff --git a/tools/oxlint/rules/lint.spec.ts b/tools/oxlint/rules/lint.spec.ts index 9313171e0..5d9ff7ae1 100644 --- a/tools/oxlint/rules/lint.spec.ts +++ b/tools/oxlint/rules/lint.spec.ts @@ -20,6 +20,32 @@ const components = 'resources/scripts/components/Probe.tsx'; const api = 'resources/scripts/api/queries.ts'; const generated = 'resources/scripts/api/generated/types.gen.ts'; +type LintDiagnostic = { + readonly code?: string; + readonly severity: string; +}; + +type LintResult = { + readonly status: number | null; + readonly diagnostics: readonly LintDiagnostic[]; +}; + +function lint(path: string, source: string): LintResult { + const filename = resolve(directory, path); + + mkdirSync(dirname(filename), { recursive: true }); + writeFileSync(filename, source); + const result = spawnSync(resolve(root, 'node_modules/.bin/oxlint'), ['--format', 'json', path], { + cwd: directory, + encoding: 'utf8', + }); + + rmSync(filename); + expect(result.stderr).toBe(''); + + return { status: result.status, diagnostics: JSON.parse(result.stdout).diagnostics }; +} + it.each([ [ 'rejects aliased generated imports', @@ -152,22 +178,3 @@ it.each([ expect(result.diagnostics.filter((diagnostic) => diagnostic.severity === 'error')).toEqual([]); expect(result.status).toBe(0); }); - -function lint( - path: string, - source: string -): { status: number | null; diagnostics: { code?: string; severity: string }[] } { - const filename = resolve(directory, path); - - mkdirSync(dirname(filename), { recursive: true }); - writeFileSync(filename, source); - const result = spawnSync(resolve(root, 'node_modules/.bin/oxlint'), ['--format', 'json', path], { - cwd: directory, - encoding: 'utf8', - }); - - rmSync(filename); - expect(result.stderr).toBe(''); - - return { status: result.status, diagnostics: JSON.parse(result.stdout).diagnostics }; -} diff --git a/tools/oxlint/rules/rules/design-tokens.ts b/tools/oxlint/rules/rules/design-tokens.ts index fdc4468db..8810ddf55 100644 --- a/tools/oxlint/rules/rules/design-tokens.ts +++ b/tools/oxlint/rules/rules/design-tokens.ts @@ -1,5 +1,6 @@ import { defineRule } from '@oxlint/plugins'; import type { ESTree } from '@oxlint/plugins'; +import { stringLiteralValue } from '../shared/literals.ts'; const palette = 'slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose|white|black'; @@ -27,8 +28,10 @@ export const designTokensRule = defineRule({ return { Literal(node) { - if (typeof node.value === 'string') { - check(node, node.value); + const value = stringLiteralValue(node); + + if (value !== null) { + check(node, value); } }, TemplateElement: (node) => check(node, node.value.cooked ?? node.value.raw), @@ -37,11 +40,9 @@ export const designTokensRule = defineRule({ return; } - if ( - node.value.type !== 'Literal' || - typeof node.value.value !== 'string' || - node.value.value.startsWith('var(') - ) { + const fontFamily = stringLiteralValue(node.value); + + if (fontFamily === null || fontFamily.startsWith('var(')) { return; } @@ -57,7 +58,9 @@ export const designTokensRule = defineRule({ const value = node.value?.type === 'JSXExpressionContainer' ? node.value.expression : node.value; - if (value?.type === 'Literal' && typeof value.value === 'string' && paintNames.test(value.value)) { + const paint = stringLiteralValue(value); + + if (value !== null && value !== undefined && paint !== null && paintNames.test(paint)) { context.report({ node: value, messageId: 'token' }); } }, diff --git a/tools/oxlint/rules/rules/generated-api-imports.ts b/tools/oxlint/rules/rules/generated-api-imports.ts index b8683983b..f8417ea85 100644 --- a/tools/oxlint/rules/rules/generated-api-imports.ts +++ b/tools/oxlint/rules/rules/generated-api-imports.ts @@ -1,6 +1,7 @@ import { dirname, resolve, sep } from 'node:path'; import { defineRule } from '@oxlint/plugins'; import type { ESTree } from '@oxlint/plugins'; +import { stringLiteralValue } from '../shared/literals.ts'; /** Keep generated transport details behind the panel API wrappers. */ export const generatedApiImportsRule = defineRule({ @@ -18,17 +19,22 @@ export const generatedApiImportsRule = defineRule({ return {}; } + const importTarget = (imported: string): string | null => { + if (imported.startsWith('@/')) { + return resolve(sourceRoot, imported.slice(2)); + } + + return imported.startsWith('.') ? resolve(dirname(filename), imported) : null; + }; + const check = (source: ESTree.Expression) => { - if (source.type !== 'Literal' || typeof source.value !== 'string') { + const imported = stringLiteralValue(source); + + if (imported === null) { return; } - const imported = source.value; - const target = imported.startsWith('@/') - ? resolve(sourceRoot, imported.slice(2)) - : imported.startsWith('.') - ? resolve(dirname(filename), imported) - : null; + const target = importTarget(imported); if (target !== generatedRoot && !target?.startsWith(generatedRoot + sep)) { return; diff --git a/tools/oxlint/rules/rules/generated-api-mutations.ts b/tools/oxlint/rules/rules/generated-api-mutations.ts index dc4e46864..fcf1e0d9f 100644 --- a/tools/oxlint/rules/rules/generated-api-mutations.ts +++ b/tools/oxlint/rules/rules/generated-api-mutations.ts @@ -1,4 +1,5 @@ import { defineRule } from '@oxlint/plugins'; +import { stringLiteralValue } from '../shared/literals.ts'; /** JSON API mutations use the options emitted by HeyAPI. */ export const generatedApiMutationsRule = defineRule({ @@ -9,12 +10,8 @@ export const generatedApiMutationsRule = defineRule({ create(context) { return { Property(node) { - const name = - node.key.type === 'Identifier' && !node.computed - ? node.key.name - : node.key.type === 'Literal' - ? node.key.value - : null; + const { key } = node; + const name = key.type === 'Identifier' && !node.computed ? key.name : stringLiteralValue(key); if (name === 'mutationFn') { context.report({ node: node.key, messageId: 'mutation' }); diff --git a/tools/oxlint/rules/rules/no-known-value-widening.ts b/tools/oxlint/rules/rules/no-known-value-widening.ts index bce9596c1..43f864ceb 100644 --- a/tools/oxlint/rules/rules/no-known-value-widening.ts +++ b/tools/oxlint/rules/rules/no-known-value-widening.ts @@ -85,7 +85,11 @@ function hasKnownEvidence( const declarator = variableDeclarator(variable); - if (declarator === null || declarator.init === null || !isStableConstVariable(variable, declarator)) { + if (declarator === null) { + return false; + } + + if (declarator.init === null || !isStableConstVariable(variable, declarator)) { return false; } diff --git a/tools/oxlint/rules/rules/no-widen-then-assert.ts b/tools/oxlint/rules/rules/no-widen-then-assert.ts index 28aa045ec..984cf6b46 100644 --- a/tools/oxlint/rules/rules/no-widen-then-assert.ts +++ b/tools/oxlint/rules/rules/no-widen-then-assert.ts @@ -15,6 +15,26 @@ const functionBoundaryTypes = new Set([ 'TSEmptyBodyFunctionExpression', ]); +const objectTypeNodes = new Set([ + 'TSArrayType', + 'TSConstructorType', + 'TSFunctionType', + 'TSMappedType', + 'TSObjectKeyword', + 'TSTupleType', +]); + +const freshValueNodes = new Set([ + 'Literal', + 'TemplateLiteral', + 'ArrayExpression', + 'ArrowFunctionExpression', + 'ClassExpression', + 'FunctionExpression', + 'NewExpression', + 'ObjectExpression', +]); + function unwrapExpressionParentheses(expression: ESTree.Expression): ESTree.Expression { let current = expression; @@ -63,6 +83,39 @@ function isBroadRecordKeyType(type: ESTree.TSType): boolean { return unwrapped.type === 'TSTypeReference' && typeReferenceName(unwrapped) === 'PropertyKey'; } +function isBroadRecordReference(type: ESTree.TSTypeReference): boolean { + if (typeReferenceName(type) !== 'Record') { + return false; + } + + const parameters = type.typeArguments?.params ?? []; + + return ( + parameters.length === 2 && + parameters[0] !== undefined && + parameters[1] !== undefined && + isBroadRecordKeyType(parameters[0]) && + isUnknownOrAnyType(parameters[1]) + ); +} + +function isBroadIndexSignatureLiteral(type: ESTree.TSTypeLiteral): boolean { + if (type.members.length !== 1) { + return false; + } + + const [member] = type.members; + const [parameter] = member?.type === 'TSIndexSignature' ? member.parameters : []; + + return ( + member?.type === 'TSIndexSignature' && + member.parameters.length === 1 && + parameter !== undefined && + isBroadRecordKeyType(parameter.typeAnnotation.typeAnnotation) && + isUnknownOrAnyType(member.typeAnnotation.typeAnnotation) + ); +} + function isBroadRecordType(type: ESTree.TSType): boolean { const unwrapped = unwrapTypeParentheses(type); @@ -73,35 +126,10 @@ function isBroadRecordType(type: ESTree.TSType): boolean { return inner !== undefined && isBroadRecordType(inner); } - if (typeReferenceName(unwrapped) !== 'Record') { - return false; - } - - const parameters = unwrapped.typeArguments?.params ?? []; - - return ( - parameters.length === 2 && - parameters[0] !== undefined && - parameters[1] !== undefined && - isBroadRecordKeyType(parameters[0]) && - isUnknownOrAnyType(parameters[1]) - ); + return isBroadRecordReference(unwrapped); } - if (unwrapped.type !== 'TSTypeLiteral' || unwrapped.members.length !== 1) { - return false; - } - - const [member] = unwrapped.members; - const [parameter] = member?.type === 'TSIndexSignature' ? member.parameters : []; - - return ( - member?.type === 'TSIndexSignature' && - member.parameters.length === 1 && - parameter !== undefined && - isBroadRecordKeyType(parameter.typeAnnotation.typeAnnotation) && - isUnknownOrAnyType(member.typeAnnotation.typeAnnotation) - ); + return unwrapped.type === 'TSTypeLiteral' && isBroadIndexSignatureLiteral(unwrapped); } function broadTypeKind(type: ESTree.TSType): BroadTypeKind | null { @@ -143,23 +171,23 @@ function typesHaveSameSyntax(sourceText: string, left: ESTree.TSType | null, rig function isDefinitelyObjectType(type: ESTree.TSType): boolean { const unwrapped = unwrapTypeParentheses(type); - switch (unwrapped.type) { - case 'TSArrayType': - case 'TSConstructorType': - case 'TSFunctionType': - case 'TSMappedType': - case 'TSObjectKeyword': - case 'TSTupleType': - return true; - case 'TSTypeLiteral': - return unwrapped.members.length > 0; - case 'TSIntersectionType': - return unwrapped.types.every(isDefinitelyObjectType); - case 'TSTypeOperator': - return unwrapped.operator === 'readonly' && isDefinitelyObjectType(unwrapped.typeAnnotation); - default: - return false; + if (objectTypeNodes.has(unwrapped.type)) { + return true; } + + if (unwrapped.type === 'TSTypeLiteral') { + return unwrapped.members.length > 0; + } + + if (unwrapped.type === 'TSIntersectionType') { + return unwrapped.types.every(isDefinitelyObjectType); + } + + return ( + unwrapped.type === 'TSTypeOperator' && + unwrapped.operator === 'readonly' && + isDefinitelyObjectType(unwrapped.typeAnnotation) + ); } function isDefinitelyNarrowerRecordType(type: ESTree.TSType): boolean { @@ -235,6 +263,35 @@ function variableDeclarator(variable: Variable): ESTree.VariableDeclarator | nul return null; } +function annotatedEvidence( + identifier: Variable['identifiers'][number], + boundary: ESTree.Node | null +): KnownValueEvidence | null { + const annotation = identifier.typeAnnotation?.typeAnnotation; + + if (annotation === undefined || functionBoundary(identifier) !== boundary || broadTypeKind(annotation) !== null) { + return null; + } + + return { type: annotation }; +} + +function stableConstInitializer(variable: Variable, boundary: ESTree.Node | null): ESTree.Expression | null { + const declarator = variableDeclarator(variable); + + if ( + declarator?.parent.type !== 'VariableDeclaration' || + declarator.parent.kind !== 'const' || + declarator.init === null || + variable.references.some((reference) => reference.isWrite() && !reference.init) || + functionBoundary(declarator) !== boundary + ) { + return null; + } + + return declarator.init; +} + function knownValueEvidence( expression: ESTree.Expression, scopes: Parameters[0], @@ -244,25 +301,10 @@ function knownValueEvidence( const unwrapped = unwrapExpressionParentheses(expression); if (unwrapped.type === 'TSAsExpression' || unwrapped.type === 'TSTypeAssertion') { - if (broadTypeKind(unwrapped.typeAnnotation) !== null) { - return null; - } - - return { type: unwrapped.typeAnnotation }; + return broadTypeKind(unwrapped.typeAnnotation) === null ? { type: unwrapped.typeAnnotation } : null; } - if (unwrapped.type === 'Literal' || unwrapped.type === 'TemplateLiteral') { - return { type: null }; - } - - if ( - unwrapped.type === 'ArrayExpression' || - unwrapped.type === 'ArrowFunctionExpression' || - unwrapped.type === 'ClassExpression' || - unwrapped.type === 'FunctionExpression' || - unwrapped.type === 'NewExpression' || - unwrapped.type === 'ObjectExpression' - ) { + if (freshValueNodes.has(unwrapped.type)) { return { type: null }; } @@ -279,29 +321,16 @@ function knownValueEvidence( const annotatedIdentifier = variable.identifiers.find( (identifier) => identifier.typeAnnotation !== null && identifier.typeAnnotation !== undefined ); - const annotation = annotatedIdentifier?.typeAnnotation?.typeAnnotation; - if (annotation !== undefined && annotatedIdentifier !== undefined) { - if (functionBoundary(annotatedIdentifier) !== boundary || broadTypeKind(annotation) !== null) { - return null; - } - - return { type: annotation }; + if (annotatedIdentifier !== undefined) { + return annotatedEvidence(annotatedIdentifier, boundary); } - const declarator = variableDeclarator(variable); + const initializer = stableConstInitializer(variable, boundary); - if ( - declarator?.parent.type !== 'VariableDeclaration' || - declarator.parent.kind !== 'const' || - declarator.init === null || - variable.references.some((reference) => reference.isWrite() && !reference.init) || - functionBoundary(declarator) !== boundary - ) { - return null; - } - - return knownValueEvidence(declarator.init, scopes, boundary, new Set([...visitedVariables, variable])); + return initializer === null + ? null + : knownValueEvidence(initializer, scopes, boundary, new Set([...visitedVariables, variable])); } function widenedBinding( diff --git a/tools/oxlint/rules/shared/dictionary-types.ts b/tools/oxlint/rules/shared/dictionary-types.ts index 926af0214..84eceea4a 100644 --- a/tools/oxlint/rules/shared/dictionary-types.ts +++ b/tools/oxlint/rules/shared/dictionary-types.ts @@ -33,6 +33,29 @@ function declaredStatement(statement: ESTree.Statement): ESTree.Node | null { : statement; } +function shadowableNames(declaration: ESTree.Node | null): readonly string[] { + if (declaration?.type === 'ImportDeclaration') { + return declaration.specifiers.map((specifier) => specifier.local.name); + } + + if ( + declaration?.type === 'TSTypeAliasDeclaration' || + declaration?.type === 'TSInterfaceDeclaration' || + declaration?.type === 'TSEnumDeclaration' + ) { + return [declaration.id.name]; + } + + if ( + (declaration?.type === 'ClassDeclaration' || declaration?.type === 'FunctionDeclaration') && + declaration.id !== null + ) { + return [declaration.id.name]; + } + + return []; +} + export function createTypeEnvironment(program: ESTree.Program): TypeEnvironment { const aliases = new Map(); const interfaces = new Map(); @@ -41,59 +64,20 @@ export function createTypeEnvironment(program: ESTree.Program): TypeEnvironment for (const statement of program.body) { const declaration = declaredStatement(statement); - if (declaration?.type === 'ImportDeclaration') { - for (const specifier of declaration.specifiers) { - if (BUILT_INS.has(specifier.local.name)) { - shadowedBuiltIns.add(specifier.local.name); - } + for (const name of shadowableNames(declaration)) { + if (BUILT_INS.has(name)) { + shadowedBuiltIns.add(name); } - - continue; } if (declaration?.type === 'TSTypeAliasDeclaration') { - const existing = aliases.get(declaration.id.name); - - if (existing === undefined) { - aliases.set(declaration.id.name, declaration); + if (aliases.has(declaration.id.name)) { + shadowedBuiltIns.add(declaration.id.name); } else { - shadowedBuiltIns.add(declaration.id.name); - } - - if (BUILT_INS.has(declaration.id.name)) { - shadowedBuiltIns.add(declaration.id.name); - } - - continue; - } - - if (declaration?.type === 'TSInterfaceDeclaration') { - const declarations = interfaces.get(declaration.id.name) ?? []; - - declarations.push(declaration); - interfaces.set(declaration.id.name, declarations); - if (BUILT_INS.has(declaration.id.name)) { - shadowedBuiltIns.add(declaration.id.name); - } - - continue; - } - - if (declaration?.type === 'TSEnumDeclaration') { - if (BUILT_INS.has(declaration.id.name)) { - shadowedBuiltIns.add(declaration.id.name); - } - - continue; - } - - if ( - (declaration?.type === 'ClassDeclaration' || declaration?.type === 'FunctionDeclaration') && - declaration.id !== null - ) { - if (BUILT_INS.has(declaration.id.name)) { - shadowedBuiltIns.add(declaration.id.name); + aliases.set(declaration.id.name, declaration); } + } else if (declaration?.type === 'TSInterfaceDeclaration') { + interfaces.set(declaration.id.name, [...(interfaces.get(declaration.id.name) ?? []), declaration]); } } @@ -108,18 +92,6 @@ function isBuiltIn(name: string, environment: TypeEnvironment): boolean { return BUILT_INS.has(name) && !environment.shadowedBuiltIns.has(name); } -function isUnappliedReferenceTo(type: ESTree.TSType, name: string): boolean { - const unwrapped = unwrapTransparentType(type); - - return ( - unwrapped.type === 'TSTypeReference' && - typeReferenceName(unwrapped) === name && - (unwrapped.typeArguments === null || - unwrapped.typeArguments === undefined || - unwrapped.typeArguments.params.length === 0) - ); -} - function unwrapTransparentType(type: ESTree.TSType): ESTree.TSType { let current = type; @@ -133,6 +105,18 @@ function unwrapTransparentType(type: ESTree.TSType): ESTree.TSType { return current; } +function isUnappliedReferenceTo(type: ESTree.TSType, name: string): boolean { + const unwrapped = unwrapTransparentType(type); + + return ( + unwrapped.type === 'TSTypeReference' && + typeReferenceName(unwrapped) === name && + (unwrapped.typeArguments === null || + unwrapped.typeArguments === undefined || + unwrapped.typeArguments.params.length === 0) + ); +} + function isNeverType(type: ESTree.TSType): boolean { return unwrapTransparentType(type).type === 'TSNeverKeyword'; } @@ -215,6 +199,121 @@ function aliasSubstitution( return next; } +type Recurse = ( + type: ESTree.TSType, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet +) => T; + +type AliasExpansion = { + readonly type: ESTree.TSType; + readonly substitutions: TypeAliasEnvironment; + readonly resolvingAliases: ReadonlySet; +}; + +function expandAlias( + name: string, + reference: ESTree.TSTypeReference, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet +): AliasExpansion | null { + const alias = environment.aliases.get(name); + + if (alias === undefined || resolvingAliases.has(name)) { + return null; + } + + const nextSubstitutions = aliasSubstitution(alias, reference, substitutions); + + if (nextSubstitutions === null) { + return null; + } + + const nextResolving = new Set(resolvingAliases); + + nextResolving.add(name); + + return { type: alias.typeAnnotation, substitutions: nextSubstitutions, resolvingAliases: nextResolving }; +} + +function unsafeKeywordValue(type: ESTree.TSType): UnsafeDictionary['unsafeValue'] | null { + if (type.type === 'TSUnknownKeyword') { + return 'unknown'; + } + + if (type.type === 'TSAnyKeyword') { + return 'any'; + } + + if (type.type === 'TSObjectKeyword') { + return 'object'; + } + + if (type.type === 'TSTypeLiteral' && isEffectivelyEmptyTypeLiteral(type)) { + return 'empty-object'; + } + + return null; +} + +function unsafeIntersectionValue( + type: ESTree.TSIntersectionType, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet, + recurse: Recurse +): UnsafeDictionary['unsafeValue'] | null { + const unsafeMembers = type.types.map((member) => recurse(member, environment, substitutions, resolvingAliases)); + + if (unsafeMembers.includes('any')) { + return 'any'; + } + + return unsafeMembers.length > 0 && unsafeMembers.every((member) => member !== null) ? unsafeMembers[0] : null; +} + +function unsafeReferenceValue( + reference: ESTree.TSTypeReference, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet, + recurse: Recurse +): UnsafeDictionary['unsafeValue'] | null { + const name = typeReferenceName(reference); + + if (name === null) { + return null; + } + + if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, environment)) { + const wrapped = reference.typeArguments?.params[0]; + + return wrapped === undefined ? null : recurse(wrapped, environment, substitutions, resolvingAliases); + } + + const substitution = substitutions.get(name); + + if (substitution !== undefined) { + return isUnappliedReferenceTo(substitution, name) + ? null + : recurse(substitution, environment, substitutions, resolvingAliases); + } + + const interfaceDeclarations = environment.interfaces.get(name); + + if (interfaceDeclarations !== undefined) { + return isEffectivelyEmptyInterface(interfaceDeclarations) ? 'empty-object' : null; + } + + const expansion = expandAlias(name, reference, environment, substitutions, resolvingAliases); + + return expansion === null + ? null + : recurse(expansion.type, environment, expansion.substitutions, expansion.resolvingAliases); +} + function unsafeDirectValue( type: ESTree.TSType, environment: TypeEnvironment, @@ -223,22 +322,6 @@ function unsafeDirectValue( ): UnsafeDictionary['unsafeValue'] | null { const unwrapped = unwrapTransparentType(type); - if (unwrapped.type === 'TSUnknownKeyword') { - return 'unknown'; - } - - if (unwrapped.type === 'TSAnyKeyword') { - return 'any'; - } - - if (unwrapped.type === 'TSObjectKeyword') { - return 'object'; - } - - if (unwrapped.type === 'TSTypeLiteral' && isEffectivelyEmptyTypeLiteral(unwrapped)) { - return 'empty-object'; - } - if (unwrapped.type === 'TSUnionType') { return unwrapped.types.some( (member) => unsafeDirectValue(member, environment, substitutions, resolvingAliases) !== null @@ -248,64 +331,75 @@ function unsafeDirectValue( } if (unwrapped.type === 'TSIntersectionType') { - const unsafeMembers = unwrapped.types.map((member) => - unsafeDirectValue(member, environment, substitutions, resolvingAliases) - ); - - if (unsafeMembers.includes('any')) { - return 'any'; - } - - return unsafeMembers.length > 0 && unsafeMembers.every((member) => member !== null) ? unsafeMembers[0] : null; + return unsafeIntersectionValue(unwrapped, environment, substitutions, resolvingAliases, unsafeDirectValue); } - if (unwrapped.type !== 'TSTypeReference') { + if (unwrapped.type === 'TSTypeReference') { + return unsafeReferenceValue(unwrapped, environment, substitutions, resolvingAliases, unsafeDirectValue); + } + + return unsafeKeywordValue(unwrapped); +} + +function builtInDictionaryValueTypes( + reference: ESTree.TSTypeReference, + name: string, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet, + recurse: Recurse +): readonly ResolvedType[] | null { + if (!isBuiltIn(name, environment)) { return null; } - const name = typeReferenceName(unwrapped); + if (TRANSPARENT_WRAPPERS.has(name) || name === 'Pick' || name === 'Omit') { + const source = reference.typeArguments?.params[0]; + + return source === undefined ? [] : recurse(source, environment, substitutions, resolvingAliases); + } + + if (name === 'Record') { + const value = reference.typeArguments?.params[1] ?? null; + + return value === null ? [] : [{ type: value, substitutions }]; + } + + return null; +} + +function dictionaryReferenceValueTypes( + reference: ESTree.TSTypeReference, + environment: TypeEnvironment, + substitutions: TypeAliasEnvironment, + resolvingAliases: ReadonlySet, + recurse: Recurse +): readonly ResolvedType[] { + const name = typeReferenceName(reference); if (name === null) { - return null; - } - - if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, environment)) { - const wrapped = unwrapped.typeArguments?.params[0]; - - return wrapped === undefined ? null : unsafeDirectValue(wrapped, environment, substitutions, resolvingAliases); + return []; } const substitution = substitutions.get(name); if (substitution !== undefined) { return isUnappliedReferenceTo(substitution, name) - ? null - : unsafeDirectValue(substitution, environment, substitutions, resolvingAliases); + ? [] + : recurse(substitution, environment, substitutions, resolvingAliases); } - const interfaceDeclarations = environment.interfaces.get(name); + const builtIn = builtInDictionaryValueTypes(reference, name, environment, substitutions, resolvingAliases, recurse); - if (interfaceDeclarations !== undefined) { - return isEffectivelyEmptyInterface(interfaceDeclarations) ? 'empty-object' : null; + if (builtIn !== null) { + return builtIn; } - const alias = environment.aliases.get(name); + const expansion = expandAlias(name, reference, environment, substitutions, resolvingAliases); - if (alias === undefined || resolvingAliases.has(name)) { - return null; - } - - const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions); - - if (nextSubstitutions === null) { - return null; - } - - const nextResolving = new Set(resolvingAliases); - - nextResolving.add(name); - - return unsafeDirectValue(alias.typeAnnotation, environment, nextSubstitutions, nextResolving); + return expansion === null + ? [] + : recurse(expansion.type, environment, expansion.substitutions, expansion.resolvingAliases); } function dictionaryValueTypes( @@ -332,55 +426,7 @@ function dictionaryValueTypes( return []; } - const name = typeReferenceName(unwrapped); - - if (name === null) { - return []; - } - - const substitution = substitutions.get(name); - - if (substitution !== undefined) { - return isUnappliedReferenceTo(substitution, name) - ? [] - : dictionaryValueTypes(substitution, environment, substitutions, resolvingAliases); - } - - if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, environment)) { - const wrapped = unwrapped.typeArguments?.params[0]; - - return wrapped === undefined ? [] : dictionaryValueTypes(wrapped, environment, substitutions, resolvingAliases); - } - - if (name === 'Record' && isBuiltIn(name, environment)) { - const value = unwrapped.typeArguments?.params[1] ?? null; - - return value === null ? [] : [{ type: value, substitutions }]; - } - - if ((name === 'Pick' || name === 'Omit') && isBuiltIn(name, environment)) { - const source = unwrapped.typeArguments?.params[0]; - - return source === undefined ? [] : dictionaryValueTypes(source, environment, substitutions, resolvingAliases); - } - - const alias = environment.aliases.get(name); - - if (alias === undefined || resolvingAliases.has(name)) { - return []; - } - - const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions); - - if (nextSubstitutions === null) { - return []; - } - - const nextResolving = new Set(resolvingAliases); - - nextResolving.add(name); - - return dictionaryValueTypes(alias.typeAnnotation, environment, nextSubstitutions, nextResolving); + return dictionaryReferenceValueTypes(unwrapped, environment, substitutions, resolvingAliases, dictionaryValueTypes); } export function classifyUnsafeDictionaryValue( @@ -413,75 +459,6 @@ function resolvesToDictionary( return dictionaryValueTypes(type, environment, substitutions, resolvingAliases).length > 0; } -export function classifyWideningTarget(type: ESTree.TSType, environment: TypeEnvironment): WideningTarget | null { - const unwrapped = unwrapTransparentType(type); - - if (unwrapped.type === 'TSUnknownKeyword') { - return { kind: 'unknown' }; - } - - if (unwrapped.type === 'TSObjectKeyword') { - return { kind: 'object' }; - } - - if (unwrapped.type === 'TSTypeLiteral') { - return unwrapped.members.some((member) => member.type === 'TSIndexSignature') - ? { kind: 'open dictionary' } - : unwrapped.members.length > 0 - ? { kind: 'anonymous object' } - : null; - } - - if (unwrapped.type === 'TSMappedType') { - return { kind: 'open dictionary' }; - } - - if (unwrapped.type !== 'TSTypeReference') { - return null; - } - - const name = typeReferenceName(unwrapped); - - if (name === null) { - return null; - } - - if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, environment)) { - const wrapped = unwrapped.typeArguments?.params[0]; - - return wrapped === undefined ? null : classifyWideningTarget(wrapped, environment); - } - - if (name === 'Record' && isBuiltIn(name, environment)) { - return { kind: 'open dictionary' }; - } - - const alias = environment.aliases.get(name); - - if (alias === undefined) { - return null; - } - - if ((alias.typeParameters?.params.length ?? 0) > 0) { - const substitutions = aliasSubstitution(alias, unwrapped, new Map()); - - return substitutions !== null && - resolvesToDictionary(alias.typeAnnotation, environment, substitutions, new Set([name])) - ? { kind: 'generic container' } - : null; - } - - const substitutions = aliasSubstitution(alias, unwrapped, new Map()); - - if (substitutions === null) { - return null; - } - - const resolved = classifyAliasBroadTarget(alias.typeAnnotation, environment, substitutions, new Set([name])); - - return resolved; -} - function classifyAliasBroadTarget( type: ESTree.TSType, environment: TypeEnvironment, @@ -514,23 +491,85 @@ function classifyAliasBroadTarget( return classifyAliasBroadTarget(substitution, environment, substitutions, resolvingAliases); } + const expansion = expandAlias(name, unwrapped, environment, substitutions, resolvingAliases); + + return expansion === null + ? null + : classifyAliasBroadTarget(expansion.type, environment, expansion.substitutions, expansion.resolvingAliases); +} + +function classifyTypeLiteralTarget(type: ESTree.TSTypeLiteral): WideningTarget | null { + if (type.members.some((member) => member.type === 'TSIndexSignature')) { + return { kind: 'open dictionary' }; + } + + return type.members.length > 0 ? { kind: 'anonymous object' } : null; +} + +function classifyReferenceTarget( + reference: ESTree.TSTypeReference, + environment: TypeEnvironment, + recurse: (type: ESTree.TSType, environment: TypeEnvironment) => WideningTarget | null +): WideningTarget | null { + const name = typeReferenceName(reference); + + if (name === null) { + return null; + } + + if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, environment)) { + const wrapped = reference.typeArguments?.params[0]; + + return wrapped === undefined ? null : recurse(wrapped, environment); + } + + if (name === 'Record' && isBuiltIn(name, environment)) { + return { kind: 'open dictionary' }; + } + const alias = environment.aliases.get(name); - if (alias === undefined || resolvingAliases.has(name)) { + if (alias === undefined) { return null; } - const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions); + const substitutions = aliasSubstitution(alias, reference, new Map()); - if (nextSubstitutions === null) { + if (substitutions === null) { return null; } - const nextResolving = new Set(resolvingAliases); + if ((alias.typeParameters?.params.length ?? 0) > 0) { + return resolvesToDictionary(alias.typeAnnotation, environment, substitutions, new Set([name])) + ? { kind: 'generic container' } + : null; + } - nextResolving.add(name); + return classifyAliasBroadTarget(alias.typeAnnotation, environment, substitutions, new Set([name])); +} - return classifyAliasBroadTarget(alias.typeAnnotation, environment, nextSubstitutions, nextResolving); +export function classifyWideningTarget(type: ESTree.TSType, environment: TypeEnvironment): WideningTarget | null { + const unwrapped = unwrapTransparentType(type); + + if (unwrapped.type === 'TSUnknownKeyword') { + return { kind: 'unknown' }; + } + + if (unwrapped.type === 'TSObjectKeyword') { + return { kind: 'object' }; + } + + if (unwrapped.type === 'TSTypeLiteral') { + return classifyTypeLiteralTarget(unwrapped); + } + + if (unwrapped.type === 'TSMappedType') { + return { kind: 'open dictionary' }; + } + + return unwrapped.type === 'TSTypeReference' + ? classifyReferenceTarget(unwrapped, environment, classifyWideningTarget) + : null; } export function isPopulatedObjectExpression(expression: ESTree.Expression): boolean { diff --git a/tools/oxlint/rules/shared/literals.ts b/tools/oxlint/rules/shared/literals.ts new file mode 100644 index 000000000..a6655baa8 --- /dev/null +++ b/tools/oxlint/rules/shared/literals.ts @@ -0,0 +1,9 @@ +import type { ESTree } from '@oxlint/plugins'; + +/** + * ESTree literal nodes share one shape and are discriminated only by the runtime type of `value`, + * so this is the single place lint rules decode a node into its string value. + */ +export function stringLiteralValue(node: ESTree.Node | null | undefined): string | null { + return node?.type === 'Literal' && typeof node.value === 'string' ? node.value : null; +} diff --git a/tools/phpstan/rules/extension.neon b/tools/phpstan/rules/extension.neon index 69ee83db8..1be1b226e 100644 --- a/tools/phpstan/rules/extension.neon +++ b/tools/phpstan/rules/extension.neon @@ -82,7 +82,6 @@ parameters: - app/Services/Servers/EnvironmentService.php - app/Support/JsonValueGuard.php - app/Support/JsonValueTree.php - - app/Support/Alerts/AlertsMessageBag.php - app/Http/Controllers/Api/Admin/DatabaseHosts/DatabaseHostController.php - app/Http/Controllers/Api/Admin/Servers/ServerMountController.php - app/Http/Controllers/Api/Remote/Backups/BackupStatusController.php diff --git a/tools/phpstan/rules/install.php b/tools/phpstan/rules/install.php index 220b92b00..f5a316498 100644 --- a/tools/phpstan/rules/install.php +++ b/tools/phpstan/rules/install.php @@ -12,7 +12,6 @@ declare(strict_types=1); * * Usage: php install.php [target-repository] [--force] */ - $arguments = array_slice($argv, 1); $force = in_array('--force', $arguments, true); $positional = array_values(array_filter($arguments, static fn (string $argument): bool => ! str_starts_with($argument, '--'))); diff --git a/tools/phpstan/rules/phpunit.xml b/tools/phpstan/rules/phpunit.xml index bc09bc612..bcf0ac954 100644 --- a/tools/phpstan/rules/phpunit.xml +++ b/tools/phpstan/rules/phpunit.xml @@ -10,4 +10,7 @@ tests + + + diff --git a/tools/phpstan/rules/src/Rules/NoChainedVarTagsRule.php b/tools/phpstan/rules/src/Rules/NoChainedVarTagsRule.php index 718d41f49..032042f34 100644 --- a/tools/phpstan/rules/src/Rules/NoChainedVarTagsRule.php +++ b/tools/phpstan/rules/src/Rules/NoChainedVarTagsRule.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\AssertionForms; -use Rules\Support\NodeChildren; use PhpParser\Node; use PhpParser\Node\Expr\Closure; use PhpParser\Node\FunctionLike; @@ -15,6 +13,8 @@ use PhpParser\Node\Stmt\Function_; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\AssertionForms; +use Rules\Support\NodeChildren; /** * The statement-sequence half of no-chained-type-assertions: two consecutive diff --git a/tools/phpstan/rules/src/Rules/NoForbiddenTermsInSymbolNamesRule.php b/tools/phpstan/rules/src/Rules/NoForbiddenTermsInSymbolNamesRule.php index 75a20a9e0..de690795d 100644 --- a/tools/phpstan/rules/src/Rules/NoForbiddenTermsInSymbolNamesRule.php +++ b/tools/phpstan/rules/src/Rules/NoForbiddenTermsInSymbolNamesRule.php @@ -116,7 +116,7 @@ final class NoForbiddenTermsInSymbolNamesRule implements Rule private function matchedTerm(string $name): ?string { foreach ($this->forbiddenTerms as $term) { - if (stripos($name, $term) !== false) { + if (mb_stripos($name, $term) !== false) { return $term; } } diff --git a/tools/phpstan/rules/src/Rules/NoInstanceofOnMixedRule.php b/tools/phpstan/rules/src/Rules/NoInstanceofOnMixedRule.php index 9dc1963da..49ec9838e 100644 --- a/tools/phpstan/rules/src/Rules/NoInstanceofOnMixedRule.php +++ b/tools/phpstan/rules/src/Rules/NoInstanceofOnMixedRule.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\Expr\Instanceof_; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\TypeClassifier; /** * The instanceof half of anti-slop's no-runtime-typeof: `$value instanceof T` diff --git a/tools/phpstan/rules/src/Rules/NoKnownValueWideningPropertyRule.php b/tools/phpstan/rules/src/Rules/NoKnownValueWideningPropertyRule.php index b4b5f9a4b..a9e34e288 100644 --- a/tools/phpstan/rules/src/Rules/NoKnownValueWideningPropertyRule.php +++ b/tools/phpstan/rules/src/Rules/NoKnownValueWideningPropertyRule.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; @@ -16,6 +15,7 @@ use PHPStan\Analyser\Scope; use PHPStan\Node\ClassPropertyNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\TypeClassifier; /** * The property half of anti-slop's no-known-value-widening: a property whose diff --git a/tools/phpstan/rules/src/Rules/NoKnownValueWideningReturnRule.php b/tools/phpstan/rules/src/Rules/NoKnownValueWideningReturnRule.php index 85fbbd594..8c76672ab 100644 --- a/tools/phpstan/rules/src/Rules/NoKnownValueWideningReturnRule.php +++ b/tools/phpstan/rules/src/Rules/NoKnownValueWideningReturnRule.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; @@ -16,6 +15,7 @@ use PHPStan\Analyser\Scope; use PHPStan\Node\FunctionReturnStatementsNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\TypeClassifier; /** * The return half of anti-slop's no-known-value-widening: a function whose diff --git a/tools/phpstan/rules/src/Rules/NoMixedParametersRule.php b/tools/phpstan/rules/src/Rules/NoMixedParametersRule.php index 4dd93b8de..8d5f1eab0 100644 --- a/tools/phpstan/rules/src/Rules/NoMixedParametersRule.php +++ b/tools/phpstan/rules/src/Rules/NoMixedParametersRule.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\SignatureResolver; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\FunctionLike; use PhpParser\Node\Stmt\ClassMethod; @@ -13,6 +11,8 @@ use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\MixedType; +use Rules\Support\SignatureResolver; +use Rules\Support\TypeClassifier; /** * Port of anti-slop's no-unknown-parameters: a parameter declared `mixed` diff --git a/tools/phpstan/rules/src/Rules/NoMixedReturnsRule.php b/tools/phpstan/rules/src/Rules/NoMixedReturnsRule.php index 491381814..49c179cbd 100644 --- a/tools/phpstan/rules/src/Rules/NoMixedReturnsRule.php +++ b/tools/phpstan/rules/src/Rules/NoMixedReturnsRule.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\SignatureResolver; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\Expr\ArrowFunction; use PhpParser\Node\Expr\Closure; @@ -15,6 +13,8 @@ use PhpParser\Node\Stmt\ClassMethod; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\SignatureResolver; +use Rules\Support\TypeClassifier; /** * Port of anti-slop's no-unknown-returns: a declared return contract of diff --git a/tools/phpstan/rules/src/Rules/NoMixedTypeAliasesRule.php b/tools/phpstan/rules/src/Rules/NoMixedTypeAliasesRule.php index a816f7ba0..83807a843 100644 --- a/tools/phpstan/rules/src/Rules/NoMixedTypeAliasesRule.php +++ b/tools/phpstan/rules/src/Rules/NoMixedTypeAliasesRule.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\TypeAliasDocblock; use PhpParser\Node; use PHPStan\Analyser\Scope; use PHPStan\Node\InClassNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\TypeAliasDocblock; /** * Port of anti-slop's no-unknown-type-aliases: a named alias whose body is diff --git a/tools/phpstan/rules/src/Rules/NoObjectParametersRule.php b/tools/phpstan/rules/src/Rules/NoObjectParametersRule.php index 2652a9f5e..5e9b1a6f3 100644 --- a/tools/phpstan/rules/src/Rules/NoObjectParametersRule.php +++ b/tools/phpstan/rules/src/Rules/NoObjectParametersRule.php @@ -4,13 +4,13 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\SignatureResolver; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\FunctionLike; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\SignatureResolver; +use Rules\Support\TypeClassifier; /** * Port of anti-slop's no-object-parameters: the bare `object` type on an input diff --git a/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryPropertyRule.php b/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryPropertyRule.php index 942cea31d..a787f34e0 100644 --- a/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryPropertyRule.php +++ b/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryPropertyRule.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PHPStan\Analyser\Scope; use PHPStan\Node\ClassPropertyNode; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\TypeClassifier; /** * The property position of no-unsafe-dictionary-type, plus the "stdClass in diff --git a/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryTypeRule.php b/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryTypeRule.php index 235d637c9..346e5cac1 100644 --- a/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryTypeRule.php +++ b/tools/phpstan/rules/src/Rules/NoUnsafeDictionaryTypeRule.php @@ -4,13 +4,13 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\SignatureResolver; -use Rules\Support\TypeClassifier; use PhpParser\Node; use PhpParser\Node\FunctionLike; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\SignatureResolver; +use Rules\Support\TypeClassifier; /** * Port of anti-slop's no-unsafe-dictionary-type for parameter and return @@ -44,7 +44,7 @@ final class NoUnsafeDictionaryTypeRule implements Rule $kind = $this->typeClassifier->unsafeDictionaryValueKind($parameter->type); if ($kind !== null) { $errors[] = $this->buildError($node, sprintf( - "Parameter `\$%s` is a dictionary of `%s` values, which gives callers no value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads (cuyz/valinor, spatie/laravel-data) before insertion.", + 'Parameter `$%s` is a dictionary of `%s` values, which gives callers no value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads (cuyz/valinor, spatie/laravel-data) before insertion.', $parameter->name, $kind, )); diff --git a/tools/phpstan/rules/src/Rules/NoWidenThenAssertRule.php b/tools/phpstan/rules/src/Rules/NoWidenThenAssertRule.php index ff6e236f7..15f41ba56 100644 --- a/tools/phpstan/rules/src/Rules/NoWidenThenAssertRule.php +++ b/tools/phpstan/rules/src/Rules/NoWidenThenAssertRule.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\AssertionForms; -use Rules\Support\NodeChildren; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Expr\Assign; @@ -23,6 +21,8 @@ use PhpParser\Node\Stmt\Function_; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\AssertionForms; +use Rules\Support\NodeChildren; /** * Port of anti-slop's no-widen-then-assert: within one function, a binding is diff --git a/tools/phpstan/rules/src/Rules/RequireSafetyCommentForAssertionRule.php b/tools/phpstan/rules/src/Rules/RequireSafetyCommentForAssertionRule.php index 99b0f174b..1859f2737 100644 --- a/tools/phpstan/rules/src/Rules/RequireSafetyCommentForAssertionRule.php +++ b/tools/phpstan/rules/src/Rules/RequireSafetyCommentForAssertionRule.php @@ -4,12 +4,12 @@ declare(strict_types=1); namespace Rules\Rules; -use Rules\Support\AssertionForms; use PhpParser\Node; use PhpParser\Node\Stmt; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; +use Rules\Support\AssertionForms; /** * Port of anti-slop's require-safety-comment-for-type-assertion: every diff --git a/tools/phpstan/rules/src/Support/TypeAliasDocblock.php b/tools/phpstan/rules/src/Support/TypeAliasDocblock.php index f64e37539..dcf237f5f 100644 --- a/tools/phpstan/rules/src/Support/TypeAliasDocblock.php +++ b/tools/phpstan/rules/src/Support/TypeAliasDocblock.php @@ -65,7 +65,7 @@ final class TypeAliasDocblock $parts = []; $depth = 0; $current = ''; - foreach (str_split($body) as $character) { + foreach (mb_str_split($body) as $character) { if ($character === '<' || $character === '{' || $character === '(' || $character === '[') { $depth++; } elseif ($character === '>' || $character === '}' || $character === ')' || $character === ']') { diff --git a/tools/phpstan/rules/tests/Integration/PackageCoverageTest.php b/tools/phpstan/rules/tests/Integration/PackageCoverageTest.php index ef55c51e7..eddb45da4 100644 --- a/tools/phpstan/rules/tests/Integration/PackageCoverageTest.php +++ b/tools/phpstan/rules/tests/Integration/PackageCoverageTest.php @@ -15,7 +15,7 @@ use PHPUnit\Framework\TestCase; */ final class PackageCoverageTest extends TestCase { - public function testPackagesCoverDynamicAccessAndRuntimeTypeChecks(): void + public function test_packages_cover_dynamic_access_and_runtime_type_checks(): void { $projectRoot = dirname(__DIR__, 5); $command = sprintf( @@ -31,9 +31,9 @@ final class PackageCoverageTest extends TestCase // Local tooling may prefix phpstan's stdout with guidance text; the // JSON report starts at the first brace. $raw = implode('', $output); - $braceOffset = strpos($raw, '{'); + $braceOffset = mb_strpos($raw, '{'); self::assertIsInt($braceOffset, 'no JSON object found in phpstan output'); - $report = json_decode(substr($raw, $braceOffset), true, 32, JSON_THROW_ON_ERROR); + $report = json_decode(mb_substr($raw, $braceOffset), true, 32, JSON_THROW_ON_ERROR); self::assertIsArray($report); $messages = []; diff --git a/tools/phpstan/rules/tests/Rules/NoChainedAssertionsRuleTest.php b/tools/phpstan/rules/tests/Rules/NoChainedAssertionsRuleTest.php index 06a3fe89c..2fceb8667 100644 --- a/tools/phpstan/rules/tests/Rules/NoChainedAssertionsRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoChainedAssertionsRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoChainedAssertionsRule; -use Rules\Support\AssertionForms; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoChainedAssertionsRule; +use Rules\Support\AssertionForms; /** * @extends RuleTestCase */ final class NoChainedAssertionsRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoChainedAssertionsRule(new AssertionForms); - } - - public function testRule(): void + public function test_rule(): void { $message = 'This assertion chain discards type evidence and fabricates a new type. Keep the original precise type, or parse untrusted input once at its boundary.'; @@ -29,4 +24,9 @@ final class NoChainedAssertionsRuleTest extends RuleTestCase [$message, 11], ]); } + + protected function getRule(): Rule + { + return new NoChainedAssertionsRule(new AssertionForms); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoChainedVarTagsRuleTest.php b/tools/phpstan/rules/tests/Rules/NoChainedVarTagsRuleTest.php index 4508d1e6e..9cda1817a 100644 --- a/tools/phpstan/rules/tests/Rules/NoChainedVarTagsRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoChainedVarTagsRuleTest.php @@ -4,25 +4,25 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoChainedVarTagsRule; -use Rules\Support\AssertionForms; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoChainedVarTagsRule; +use Rules\Support\AssertionForms; /** * @extends RuleTestCase */ final class NoChainedVarTagsRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoChainedVarTagsRule(new AssertionForms); - } - - public function testRule(): void + public function test_rule(): void { $this->analyse([__DIR__.'/data/no-chained-var-tags.php'], [ ['Consecutive `@var` docblocks re-narrow `$decoded` without new evidence. Keep the original precise type, or parse untrusted input once at its boundary.', 14], ]); } + + protected function getRule(): Rule + { + return new NoChainedVarTagsRule(new AssertionForms); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoClassLoadingMocksRuleTest.php b/tools/phpstan/rules/tests/Rules/NoClassLoadingMocksRuleTest.php index f31639fd0..80b70cb28 100644 --- a/tools/phpstan/rules/tests/Rules/NoClassLoadingMocksRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoClassLoadingMocksRuleTest.php @@ -4,21 +4,16 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoClassLoadingMocksRule; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoClassLoadingMocksRule; /** * @extends RuleTestCase */ final class NoClassLoadingMocksRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoClassLoadingMocksRule($this->createReflectionProvider()); - } - - public function testRule(): void + public function test_rule(): void { $concrete = 'Mocking the concrete class `%s` fakes an implementation instead of a contract. Extract a real interface, or inject a faithful in-memory fake.'; $loading = 'Mocking `%s` replaces the autoloaded class for the whole process. Extract a real interface and inject a faithful in-memory fake instead.'; @@ -33,4 +28,9 @@ final class NoClassLoadingMocksRuleTest extends RuleTestCase [sprintf($loading, 'alias:'.$class), 39], ]); } + + protected function getRule(): Rule + { + return new NoClassLoadingMocksRule($this->createReflectionProvider()); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoConditionalEmptyArraySpreadRuleTest.php b/tools/phpstan/rules/tests/Rules/NoConditionalEmptyArraySpreadRuleTest.php index ba4cfdfba..395b15b10 100644 --- a/tools/phpstan/rules/tests/Rules/NoConditionalEmptyArraySpreadRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoConditionalEmptyArraySpreadRuleTest.php @@ -4,21 +4,16 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoConditionalEmptyArraySpreadRule; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoConditionalEmptyArraySpreadRule; /** * @extends RuleTestCase */ final class NoConditionalEmptyArraySpreadRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoConditionalEmptyArraySpreadRule; - } - - public function testRule(): void + public function test_rule(): void { $message = 'This conditional spread hides key omission behind an empty array. Build the array in separate statements and add the key only when present.'; @@ -29,4 +24,9 @@ final class NoConditionalEmptyArraySpreadRuleTest extends RuleTestCase [$message, 18], ]); } + + protected function getRule(): Rule + { + return new NoConditionalEmptyArraySpreadRule; + } } diff --git a/tools/phpstan/rules/tests/Rules/NoForbiddenTermsInSymbolNamesRuleTest.php b/tools/phpstan/rules/tests/Rules/NoForbiddenTermsInSymbolNamesRuleTest.php index 9bebd244a..3e68bc8b7 100644 --- a/tools/phpstan/rules/tests/Rules/NoForbiddenTermsInSymbolNamesRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoForbiddenTermsInSymbolNamesRuleTest.php @@ -4,21 +4,16 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoForbiddenTermsInSymbolNamesRule; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoForbiddenTermsInSymbolNamesRule; /** * @extends RuleTestCase */ final class NoForbiddenTermsInSymbolNamesRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoForbiddenTermsInSymbolNamesRule(['shape']); - } - - public function testRule(): void + public function test_rule(): void { $message = 'Rename symbol `%s` for its domain role; `shape` describes structure rather than ownership.'; @@ -34,4 +29,9 @@ final class NoForbiddenTermsInSymbolNamesRuleTest extends RuleTestCase [sprintf($message, 'resultShape'), 21], ]); } + + protected function getRule(): Rule + { + return new NoForbiddenTermsInSymbolNamesRule(['shape']); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoInstanceofOnMixedRuleTest.php b/tools/phpstan/rules/tests/Rules/NoInstanceofOnMixedRuleTest.php index 8c7c12e49..fd55b977a 100644 --- a/tools/phpstan/rules/tests/Rules/NoInstanceofOnMixedRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoInstanceofOnMixedRuleTest.php @@ -4,25 +4,25 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoInstanceofOnMixedRule; -use Rules\Support\TypeClassifier; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoInstanceofOnMixedRule; +use Rules\Support\TypeClassifier; /** * @extends RuleTestCase */ final class NoInstanceofOnMixedRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoInstanceofOnMixedRule(new TypeClassifier, ['src/Boundary/**']); - } - - public function testRule(): void + public function test_rule(): void { $this->analyse([__DIR__.'/data/no-instanceof-on-mixed.php'], [ ['This `instanceof` narrows a `mixed` value without establishing its contract. Parse the value at its I/O boundary (cuyz/valinor, spatie/laravel-data), then branch on the domain type.', 9], ]); } + + protected function getRule(): Rule + { + return new NoInstanceofOnMixedRule(new TypeClassifier, ['src/Boundary/**']); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoKnownValueWideningReturnRuleTest.php b/tools/phpstan/rules/tests/Rules/NoKnownValueWideningReturnRuleTest.php index 36ff077f4..f759cdf2d 100644 --- a/tools/phpstan/rules/tests/Rules/NoKnownValueWideningReturnRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoKnownValueWideningReturnRuleTest.php @@ -4,25 +4,25 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoKnownValueWideningReturnRule; -use Rules\Support\TypeClassifier; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoKnownValueWideningReturnRule; +use Rules\Support\TypeClassifier; /** * @extends RuleTestCase */ final class NoKnownValueWideningReturnRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoKnownValueWideningReturnRule(new TypeClassifier); - } - - public function testRule(): void + public function test_rule(): void { $this->analyse([__DIR__.'/data/no-known-value-widening.php'], [ ['The broad declared return type discards the known evidence of every returned value. Delete the annotation and let inference stand, or introduce a named shape.', 28], ]); } + + protected function getRule(): Rule + { + return new NoKnownValueWideningReturnRule(new TypeClassifier); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoKnownValueWideningRuleTest.php b/tools/phpstan/rules/tests/Rules/NoKnownValueWideningRuleTest.php index 6221a6ee8..10c4f3153 100644 --- a/tools/phpstan/rules/tests/Rules/NoKnownValueWideningRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoKnownValueWideningRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoKnownValueWideningPropertyRule; -use Rules\Support\TypeClassifier; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoKnownValueWideningPropertyRule; +use Rules\Support\TypeClassifier; /** * @extends RuleTestCase */ final class NoKnownValueWideningRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoKnownValueWideningPropertyRule(new TypeClassifier); - } - - public function testRule(): void + public function test_rule(): void { $message = 'The broad declared type on property `$%s` discards its default value\'s evidence. Delete the annotation and let inference stand, or introduce a named shape.'; @@ -28,4 +23,9 @@ final class NoKnownValueWideningRuleTest extends RuleTestCase [sprintf($message, 'marker'), 20], ]); } + + protected function getRule(): Rule + { + return new NoKnownValueWideningPropertyRule(new TypeClassifier); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoMixedParametersRuleTest.php b/tools/phpstan/rules/tests/Rules/NoMixedParametersRuleTest.php index 396c83390..5345191c0 100644 --- a/tools/phpstan/rules/tests/Rules/NoMixedParametersRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoMixedParametersRuleTest.php @@ -4,11 +4,11 @@ declare(strict_types=1); namespace Rules\Tests\Rules; +use PHPStan\Rules\Rule; +use PHPStan\Testing\RuleTestCase; use Rules\Rules\NoMixedParametersRule; use Rules\Support\SignatureResolver; use Rules\Support\TypeClassifier; -use PHPStan\Rules\Rule; -use PHPStan\Testing\RuleTestCase; /** * @extends RuleTestCase diff --git a/tools/phpstan/rules/tests/Rules/NoMixedReturnsRuleTest.php b/tools/phpstan/rules/tests/Rules/NoMixedReturnsRuleTest.php index ccc32b38a..ab87d70ab 100644 --- a/tools/phpstan/rules/tests/Rules/NoMixedReturnsRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoMixedReturnsRuleTest.php @@ -4,26 +4,18 @@ declare(strict_types=1); namespace Rules\Tests\Rules; +use PHPStan\Rules\Rule; +use PHPStan\Testing\RuleTestCase; use Rules\Rules\NoMixedReturnsRule; use Rules\Support\SignatureResolver; use Rules\Support\TypeClassifier; -use PHPStan\Rules\Rule; -use PHPStan\Testing\RuleTestCase; /** * @extends RuleTestCase */ final class NoMixedReturnsRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoMixedReturnsRule( - new SignatureResolver($this->createReflectionProvider()), - new TypeClassifier, - ); - } - - public function testRule(): void + public function test_rule(): void { $returns = 'This function exposes `mixed` to its caller. Parse the value at its boundary (cuyz/valinor, spatie/laravel-data) and return a named domain type.'; $yields = 'This function yields `mixed` values to its caller. Parse each value at its boundary and yield a named domain type.'; @@ -37,4 +29,12 @@ final class NoMixedReturnsRuleTest extends RuleTestCase [$returns, 70], ]); } + + protected function getRule(): Rule + { + return new NoMixedReturnsRule( + new SignatureResolver($this->createReflectionProvider()), + new TypeClassifier, + ); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoMixedTypeAliasesRuleTest.php b/tools/phpstan/rules/tests/Rules/NoMixedTypeAliasesRuleTest.php index 6e03c32d5..d1cc4a7bc 100644 --- a/tools/phpstan/rules/tests/Rules/NoMixedTypeAliasesRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoMixedTypeAliasesRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoMixedTypeAliasesRule; -use Rules\Support\TypeAliasDocblock; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoMixedTypeAliasesRule; +use Rules\Support\TypeAliasDocblock; /** * @extends RuleTestCase */ final class NoMixedTypeAliasesRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoMixedTypeAliasesRule(new TypeAliasDocblock); - } - - public function testRule(): void + public function test_rule(): void { $message = 'Type alias `%s` hides `mixed`. Keep `mixed` explicit at the parsing boundary; otherwise alias the parsed owner type.'; @@ -30,4 +25,9 @@ final class NoMixedTypeAliasesRuleTest extends RuleTestCase [sprintf($message, 'Hidden'), 15], ]); } + + protected function getRule(): Rule + { + return new NoMixedTypeAliasesRule(new TypeAliasDocblock); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoObjectParametersRuleTest.php b/tools/phpstan/rules/tests/Rules/NoObjectParametersRuleTest.php index 326cd0a79..4a34470a9 100644 --- a/tools/phpstan/rules/tests/Rules/NoObjectParametersRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoObjectParametersRuleTest.php @@ -4,26 +4,18 @@ declare(strict_types=1); namespace Rules\Tests\Rules; +use PHPStan\Rules\Rule; +use PHPStan\Testing\RuleTestCase; use Rules\Rules\NoObjectParametersRule; use Rules\Support\SignatureResolver; use Rules\Support\TypeClassifier; -use PHPStan\Rules\Rule; -use PHPStan\Testing\RuleTestCase; /** * @extends RuleTestCase */ final class NoObjectParametersRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoObjectParametersRule( - new SignatureResolver($this->createReflectionProvider()), - new TypeClassifier, - ); - } - - public function testRule(): void + public function test_rule(): void { $message = 'Parameter `$%s` uses the broad `object` type. Accept a named owner type; parse external input (cuyz/valinor, spatie/laravel-data) at its boundary before calling this function.'; @@ -35,4 +27,12 @@ final class NoObjectParametersRuleTest extends RuleTestCase [sprintf($message, 'thing'), 29], ]); } + + protected function getRule(): Rule + { + return new NoObjectParametersRule( + new SignatureResolver($this->createReflectionProvider()), + new TypeClassifier, + ); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoServiceConstructionRuleTest.php b/tools/phpstan/rules/tests/Rules/NoServiceConstructionRuleTest.php index c022962e3..ecee151fd 100644 --- a/tools/phpstan/rules/tests/Rules/NoServiceConstructionRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoServiceConstructionRuleTest.php @@ -4,21 +4,16 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Laravel\Rules\NoServiceConstructionRule; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Laravel\Rules\NoServiceConstructionRule; /** * @extends RuleTestCase */ final class NoServiceConstructionRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoServiceConstructionRule(['App\\Services\\'], ['app/Providers/**']); - } - - public function testRule(): void + public function test_rule(): void { $message = 'Runtime code constructs the service `App\Services\ReportBuilder` instead of receiving it. Inject it through the constructor and let the container own the wiring.'; @@ -28,4 +23,9 @@ final class NoServiceConstructionRuleTest extends RuleTestCase [$message, 34], ]); } + + protected function getRule(): Rule + { + return new NoServiceConstructionRule(['App\\Services\\'], ['app/Providers/**']); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryPropertyRuleTest.php b/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryPropertyRuleTest.php index f163e3d85..067dd12b9 100644 --- a/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryPropertyRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryPropertyRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoUnsafeDictionaryPropertyRule; -use Rules\Support\TypeClassifier; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoUnsafeDictionaryPropertyRule; +use Rules\Support\TypeClassifier; /** * @extends RuleTestCase */ final class NoUnsafeDictionaryPropertyRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoUnsafeDictionaryPropertyRule(new TypeClassifier); - } - - public function testRule(): void + public function test_rule(): void { $this->analyse([__DIR__.'/data/no-unsafe-dictionary-property.php'], [ ['Property `$meta` is a dictionary of `mixed` values, which stores data without a value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads before insertion.', 10], @@ -27,4 +22,9 @@ final class NoUnsafeDictionaryPropertyRuleTest extends RuleTestCase ['Property `$blob` is typed `stdClass`, an anonymous bag with no contract. Declare a named readonly DTO and parse external payloads into it.', 15], ]); } + + protected function getRule(): Rule + { + return new NoUnsafeDictionaryPropertyRule(new TypeClassifier); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryTypeRuleTest.php b/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryTypeRuleTest.php index 0320387c1..aee49e636 100644 --- a/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryTypeRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoUnsafeDictionaryTypeRuleTest.php @@ -4,28 +4,20 @@ declare(strict_types=1); namespace Rules\Tests\Rules; +use PHPStan\Rules\Rule; +use PHPStan\Testing\RuleTestCase; use Rules\Rules\NoUnsafeDictionaryTypeRule; use Rules\Support\SignatureResolver; use Rules\Support\TypeClassifier; -use PHPStan\Rules\Rule; -use PHPStan\Testing\RuleTestCase; /** * @extends RuleTestCase */ final class NoUnsafeDictionaryTypeRuleTest extends RuleTestCase { - protected function getRule(): Rule + public function test_rule(): void { - return new NoUnsafeDictionaryTypeRule( - new SignatureResolver($this->createReflectionProvider()), - new TypeClassifier, - ); - } - - public function testRule(): void - { - $parameter = "Parameter `\$%s` is a dictionary of `%s` values, which gives callers no value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads (cuyz/valinor, spatie/laravel-data) before insertion."; + $parameter = 'Parameter `$%s` is a dictionary of `%s` values, which gives callers no value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads (cuyz/valinor, spatie/laravel-data) before insertion.'; $this->analyse([__DIR__.'/data/no-unsafe-dictionary-type.php'], [ [sprintf($parameter, 'meta', 'mixed'), 10], @@ -38,4 +30,12 @@ final class NoUnsafeDictionaryTypeRuleTest extends RuleTestCase ['This function returns a dictionary of `mixed` values, which gives callers no value contract. Declare an `array{...}` shape or a readonly DTO; parse external payloads before returning them.', 45], ]); } + + protected function getRule(): Rule + { + return new NoUnsafeDictionaryTypeRule( + new SignatureResolver($this->createReflectionProvider()), + new TypeClassifier, + ); + } } diff --git a/tools/phpstan/rules/tests/Rules/NoWidenThenAssertRuleTest.php b/tools/phpstan/rules/tests/Rules/NoWidenThenAssertRuleTest.php index 813b099d4..6d504b297 100644 --- a/tools/phpstan/rules/tests/Rules/NoWidenThenAssertRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/NoWidenThenAssertRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\NoWidenThenAssertRule; -use Rules\Support\AssertionForms; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\NoWidenThenAssertRule; +use Rules\Support\AssertionForms; /** * @extends RuleTestCase */ final class NoWidenThenAssertRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new NoWidenThenAssertRule(new AssertionForms); - } - - public function testRule(): void + public function test_rule(): void { $message = 'Binding `$%s` discards type evidence and later recreates it with an assertion. Keep the precise type from initialization through use; parse boundary input once.'; @@ -29,4 +24,9 @@ final class NoWidenThenAssertRuleTest extends RuleTestCase [sprintf($message, 'vars'), 35], ]); } + + protected function getRule(): Rule + { + return new NoWidenThenAssertRule(new AssertionForms); + } } diff --git a/tools/phpstan/rules/tests/Rules/RequireSafetyCommentForAssertionRuleTest.php b/tools/phpstan/rules/tests/Rules/RequireSafetyCommentForAssertionRuleTest.php index 2140f3a7e..9baaa8d56 100644 --- a/tools/phpstan/rules/tests/Rules/RequireSafetyCommentForAssertionRuleTest.php +++ b/tools/phpstan/rules/tests/Rules/RequireSafetyCommentForAssertionRuleTest.php @@ -4,22 +4,17 @@ declare(strict_types=1); namespace Rules\Tests\Rules; -use Rules\Rules\RequireSafetyCommentForAssertionRule; -use Rules\Support\AssertionForms; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use Rules\Rules\RequireSafetyCommentForAssertionRule; +use Rules\Support\AssertionForms; /** * @extends RuleTestCase */ final class RequireSafetyCommentForAssertionRuleTest extends RuleTestCase { - protected function getRule(): Rule - { - return new RequireSafetyCommentForAssertionRule(new AssertionForms); - } - - public function testRule(): void + public function test_rule(): void { $assertion = 'This type assertion has no `SAFETY:` justification. State the checked invariant immediately before the assertion or its containing statement.'; $varTag = 'This inline `@var` overrides inference without a `SAFETY:` justification. State the checked invariant in the docblock or immediately before the statement.'; @@ -31,4 +26,9 @@ final class RequireSafetyCommentForAssertionRuleTest extends RuleTestCase [$assertion, 30], ]); } + + protected function getRule(): Rule + { + return new RequireSafetyCommentForAssertionRule(new AssertionForms); + } }