refactor: fix all 105 PHPStan 2 strict type findings across core and modules

Resolve all non-false-positive PHPStan 2 findings, reducing the baseline
from 486 to 382 entries (only unused-public false positives remain).

Categories fixed:
- Remove 39 redundant type checks (is_string, is_array, is_object, method_exists)
- Remove 12 no-op array_values() on already-sequential lists
- Simplify 13 null-coalesce on guaranteed offsets
- Remove 8 always-true instanceof checks
- Replace 12 redundant test assertions (assertTrue(true) → addToAssertionCount)
- Simplify 6 unnecessary nullsafe operators (?-> → ->)
- Fix 6 always-true !== '' comparisons
- Fix remaining: unset.offset, return.unusedType, staticMethod narrowing

53 files changed across core/, modules/, pages/, and tests/.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-14 12:54:20 +02:00
parent a736566071
commit 3f0db68b27
53 changed files with 90 additions and 640 deletions

View File

@@ -283,7 +283,7 @@ final class ModuleRegistry
// — Merge search resources (fail-fast on duplicate provider) ——
foreach ($manifest->searchResources as $provider) {
if (!is_string($provider) || trim($provider) === '') {
if (trim($provider) === '') {
throw new RuntimeException(
"Search resource provider in module '{$manifest->id}' must be a non-empty class-string."
);
@@ -333,7 +333,7 @@ final class ModuleRegistry
// — Merge layout context providers ————————————————
foreach ($manifest->layoutContextProviders as $providerClass) {
if (!is_string($providerClass) || trim($providerClass) === '') {
if (trim($providerClass) === '') {
throw new RuntimeException(
"Layout context provider in module '{$manifest->id}' must be a non-empty class-string."
);
@@ -343,7 +343,7 @@ final class ModuleRegistry
// — Merge session providers ——————————————————————
foreach ($manifest->sessionProviders as $providerClass) {
if (!is_string($providerClass) || trim($providerClass) === '') {
if (trim($providerClass) === '') {
throw new RuntimeException(
"Session provider in module '{$manifest->id}' must be a non-empty class-string."
);
@@ -353,7 +353,7 @@ final class ModuleRegistry
// — Merge authorization policies (fail-fast on duplicate) ———
foreach ($manifest->authorizationPolicies as $policyClass) {
if (!is_string($policyClass) || trim($policyClass) === '') {
if (trim($policyClass) === '') {
throw new RuntimeException(
"Authorization policy in module '{$manifest->id}' must be a non-empty class-string."
);
@@ -402,7 +402,7 @@ final class ModuleRegistry
'default_schedule_time' => $schedulerJob['default_schedule_time'],
'default_schedule_weekdays_csv' => $schedulerJob['default_schedule_weekdays_csv'],
'default_catchup_once' => (int) $schedulerJob['default_catchup_once'],
'allowed_schedule_types' => array_values($schedulerJob['allowed_schedule_types']),
'allowed_schedule_types' => $schedulerJob['allowed_schedule_types'],
'module_id' => $manifest->id,
];
}
@@ -637,10 +637,10 @@ final class ModuleRegistry
/** @return list<string> */
public function getPermissionKeys(): array
{
return array_values(array_map(
return array_map(
static fn (array $permission): string => (string) $permission['key'],
$this->mergedPermissions
));
);
}
/** @return list<class-string> */

View File

@@ -34,9 +34,6 @@ final class ModuleRuntimeAssetPublisher
$desired = [];
foreach ($modules as $manifest) {
if (!$manifest instanceof ModuleManifest) {
continue;
}
$moduleWebDir = rtrim($manifest->basePath, '/') . '/web';
if (!is_dir($moduleWebDir)) {
continue;

View File

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace MintyPHP\Console\Runner\Doctor;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Bootstrap\EnvValidator;
use MintyPHP\Console\Support\CliAppBootstrap;
use MintyPHP\DB;
@@ -22,8 +21,7 @@ final class DoctorRunner implements DoctorRunnerInterface
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/** @var AppContainer $container */
$container = CliAppBootstrap::bootstrap('cli', 'bin/console doctor');
CliAppBootstrap::bootstrap('cli', 'bin/console doctor');
$startedAt = microtime(true);
$results = [];
@@ -71,14 +69,7 @@ final class DoctorRunner implements DoctorRunnerInterface
];
});
$runCheck('App container bootstrap', static function () use ($container): array {
if (!$container instanceof AppContainer) {
return [
'status' => 'fail',
'message' => 'registerContainer.php did not return AppContainer',
];
}
$runCheck('App container bootstrap', static function (): array {
app(AuthService::class);
app(AuthorizationService::class);
app(UiAccessService::class);

View File

@@ -229,7 +229,7 @@ class ApiBootstrap
}
$parts = explode(':', $token, 2);
$selector = trim((string) ($parts[0] ?? ''));
$selector = trim($parts[0]);
if ($selector === '' || !preg_match('/^[a-f0-9]{24}$/i', $selector)) {
return '';
}
@@ -256,7 +256,7 @@ class ApiBootstrap
try {
if (is_callable(self::$apiAuditServiceResolver)) {
$service = (self::$apiAuditServiceResolver)();
if (is_object($service) && method_exists($service, 'startRequestContext')) {
if (method_exists($service, 'startRequestContext')) {
$service->startRequestContext();
}
}
@@ -270,7 +270,7 @@ class ApiBootstrap
try {
if (is_callable(self::$apiAuditServiceResolver)) {
$service = (self::$apiAuditServiceResolver)();
if (is_object($service) && method_exists($service, 'finish')) {
if (method_exists($service, 'finish')) {
$service->finish($statusCode, $errorCode);
}
}
@@ -284,7 +284,7 @@ class ApiBootstrap
try {
if (is_callable(self::$apiSystemAuditReporterResolver)) {
$service = (self::$apiSystemAuditReporterResolver)();
if (is_object($service) && method_exists($service, 'start')) {
if (method_exists($service, 'start')) {
$service->start();
}
}
@@ -298,7 +298,7 @@ class ApiBootstrap
try {
if (is_callable(self::$apiSystemAuditReporterResolver)) {
$service = (self::$apiSystemAuditReporterResolver)();
if (is_object($service) && method_exists($service, 'finish')) {
if (method_exists($service, 'finish')) {
$service->finish($statusCode, $errorCode);
}
}

View File

@@ -243,7 +243,7 @@ class ApiResponse
try {
if (is_callable(self::$apiAuditServiceResolver)) {
$service = (self::$apiAuditServiceResolver)();
if (is_object($service) && method_exists($service, 'finish')) {
if (method_exists($service, 'finish')) {
$service->finish($statusCode, $errorCode);
}
}
@@ -257,7 +257,7 @@ class ApiResponse
try {
if (is_callable(self::$apiAuditServiceResolver)) {
$service = (self::$apiAuditServiceResolver)();
if (is_object($service) && method_exists($service, 'currentRequestId')) {
if (method_exists($service, 'currentRequestId')) {
return $service->currentRequestId();
}
}
@@ -273,12 +273,7 @@ class ApiResponse
throw new \RuntimeException('ApiResponse is not configured for dependency: ' . AuthorizationService::class);
}
$service = (self::$authorizationServiceResolver)();
if (!$service instanceof AuthorizationService) {
throw new \RuntimeException('ApiResponse resolver returned invalid dependency: ' . AuthorizationService::class);
}
return $service;
return (self::$authorizationServiceResolver)();
}
private static function finishSystemAuditReporter(int $statusCode, ?string $errorCode = null): void
@@ -286,7 +281,7 @@ class ApiResponse
try {
if (is_callable(self::$apiSystemAuditReporterResolver)) {
$service = (self::$apiSystemAuditReporterResolver)();
if (is_object($service) && method_exists($service, 'finish')) {
if (method_exists($service, 'finish')) {
$service->finish($statusCode, $errorCode);
}
}

View File

@@ -52,7 +52,7 @@ class RequestRuntime implements RequestRuntimeInterface
}
$parts = explode(',', $forwarded);
return trim((string) ($parts[0] ?? '')) === 'https';
return trim($parts[0]) === 'https';
}
/**

View File

@@ -46,7 +46,7 @@ class MailLogRepository implements MailLogRepositoryInterface
public function listPaged(array $options): array
{
$search = trim((string) ($options['search'] ?? ''));
$status = MailLogStatus::tryNormalize((string) ($options['status'] ?? ''))?->value ?? '';
$status = MailLogStatus::tryNormalize((string) ($options['status'] ?? ''))->value ?? '';
$createdFrom = trim((string) ($options['created_from'] ?? ''));
$createdTo = trim((string) ($options['created_to'] ?? ''));

View File

@@ -1080,6 +1080,7 @@ class AdminStatsRepository implements AdminStatsRepositoryInterface
$vars = get_defined_vars();
/** @phpstan-ignore unset.offset (get_defined_vars() includes $this in object context; must remove before returning) */
unset($vars['this']);
return $vars;
}

View File

@@ -95,7 +95,7 @@ class AccessPolicyFactory
if ($this->moduleRegistry !== null) {
try {
foreach ($this->moduleRegistry->getAuthorizationPolicies() as $policyClass) {
if (!is_string($policyClass) || trim($policyClass) === '') {
if (trim($policyClass) === '') {
continue;
}
$policy = $this->instantiateModulePolicy($policyClass);

View File

@@ -15,9 +15,7 @@ class AuthorizationService
public function __construct(array $policies)
{
foreach ($policies as $policy) {
if ($policy instanceof AuthorizationPolicyInterface) {
$this->policies[] = $policy;
}
$this->policies[] = $policy;
}
}

View File

@@ -53,14 +53,10 @@ final class UiAccessService
continue;
}
if (!is_array($definition)) {
$resolved[$key] = false;
continue;
}
$ability = $definition['ability'];
$context = [];
if (array_key_exists('context', $definition) && is_array($definition['context'])) {
if (array_key_exists('context', $definition)) {
$context = $this->normalizeContext($definition['context']);
}
$resolved[$key] = $this->allow($actorUserId, $ability, [
@@ -113,7 +109,7 @@ final class UiAccessService
private function normalizeContext(array $context): array
{
$normalized = $this->normalizeValue($context);
return is_array($normalized) ? $normalized : [];
return $this->normalizeValue($context);
}
private function normalizeValue(mixed $value): mixed

View File

@@ -278,12 +278,10 @@ class TenantSsoService
if ($auth['client_secret_override_enc'] === '') {
return ['ok' => false, 'error' => 'client_secret_override_required'];
}
if ($auth['client_secret_override_enc'] !== '') {
try {
$clientSecret = $this->cryptoGateway->decryptString($auth['client_secret_override_enc']);
} catch (\Throwable $exception) {
return ['ok' => false, 'error' => 'secret_invalid'];
}
try {
$clientSecret = $this->cryptoGateway->decryptString($auth['client_secret_override_enc']);
} catch (\Throwable $exception) {
return ['ok' => false, 'error' => 'secret_invalid'];
}
if (trim($clientSecret) === '') {
return ['ok' => false, 'error' => 'client_secret_override_required'];

View File

@@ -138,6 +138,6 @@ class BrandingLogoService
usort($matches, static function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return $matches[0] ?? null;
return $matches[0];
}
}

View File

@@ -136,9 +136,6 @@ class UserCustomFieldValueService
$tenantScopeId = (int) ($tenantScopeId ?? 0);
$orderedTenants = [];
foreach ($tenantSummaries as $tenantSummary) {
if (!is_array($tenantSummary)) {
continue;
}
$tenantId = (int) ($tenantSummary['id'] ?? 0);
if ($tenantId <= 0) {
continue;
@@ -579,7 +576,7 @@ class UserCustomFieldValueService
private static function mapPublicValueByType(string $type, ?array $valueData, array $optionsById)
{
$hasValue = is_array($valueData);
$hasValue = $valueData !== null;
if ($type === 'multiselect') {
if (!$hasValue) {
return [];

View File

@@ -112,7 +112,7 @@ trait ImageUploadTrait
usort($matches, static function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return $matches[0] ?? null;
return $matches[0];
}
protected static function imageCreateResource(string $path, string $mime)

View File

@@ -126,9 +126,6 @@ class CsvReaderService
$lineNumber = 0;
while (($row = fgetcsv($handle, 0, $delimiter, '"', '\\')) !== false) {
$lineNumber++;
if (!is_array($row)) {
continue;
}
$row = $this->normalizeRowColumns($row, count($row));
if ($this->isEmptyRow($row)) {
continue;
@@ -207,9 +204,6 @@ class CsvReaderService
if ($lineNumber <= $headerLine) {
continue;
}
if (!is_array($row)) {
continue;
}
$row = $this->normalizeRowColumns($row, count($headers));
if ($this->isEmptyRow($row)) {
continue;

View File

@@ -161,7 +161,7 @@ class ScheduledJobRegistry
'default_schedule_time' => $jobDefinition['default_schedule_time'],
'default_schedule_weekdays_csv' => $jobDefinition['default_schedule_weekdays_csv'],
'default_catchup_once' => (int) $jobDefinition['default_catchup_once'],
'allowed_schedule_types' => array_values($jobDefinition['allowed_schedule_types']),
'allowed_schedule_types' => $jobDefinition['allowed_schedule_types'],
];
}
}

View File

@@ -196,7 +196,7 @@ class SchedulerRunService
$errorCode = 'job_not_registered';
} else {
$execution = $this->scheduledJobRegistry->execute((string) $job['job_key'], $actorUserId);
$status = ScheduledJobRunStatus::tryNormalize((string) $execution['status'])?->value
$status = ScheduledJobRunStatus::tryNormalize((string) $execution['status'])->value
?? ScheduledJobRunStatus::Failed->value;
$errorCode = $this->nullableString($execution['error_code']);
$errorMessage = $this->nullableString($execution['error_message']);

View File

@@ -156,7 +156,7 @@ class TenantAvatarService
usort($matches, static function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return $matches[0] ?? null;
return $matches[0];
}
private function avatarDirs(string $uuid): array

View File

@@ -105,19 +105,9 @@ class UserAccessPdfService
private static function configurePdfOptions(Options $options): void
{
// Keep PDF rendering deterministic and avoid remote/network execution.
if (method_exists($options, 'setIsRemoteEnabled')) {
$options->setIsRemoteEnabled(false);
} else {
$options->set('isRemoteEnabled', false);
}
if (method_exists($options, 'setIsPhpEnabled')) {
$options->setIsPhpEnabled(false);
} else {
$options->set('isPhpEnabled', false);
}
if (method_exists($options, 'setDefaultFont')) {
$options->setDefaultFont('DejaVu Sans');
}
$options->setIsRemoteEnabled(false);
$options->setIsPhpEnabled(false);
$options->setDefaultFont('DejaVu Sans');
}
private static function renderTemplate(string $template, array $vars, string $locale): string

View File

@@ -217,6 +217,6 @@ class UserAvatarService
usort($matches, static function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return $matches[0] ?? null;
return $matches[0];
}
}

View File

@@ -145,11 +145,7 @@ class Guard
if (!is_callable(self::$authorizationServiceResolver)) {
throw new \RuntimeException('Guard is not configured for dependency: ' . AuthorizationService::class);
}
$service = (self::$authorizationServiceResolver)();
if (!$service instanceof AuthorizationService) {
throw new \RuntimeException('Guard resolver returned invalid dependency: ' . AuthorizationService::class);
}
return $service;
return (self::$authorizationServiceResolver)();
}
private static function authService(): AuthService
@@ -157,11 +153,7 @@ class Guard
if (!is_callable(self::$authServiceResolver)) {
throw new \RuntimeException('Guard is not configured for dependency: ' . AuthService::class);
}
$service = (self::$authServiceResolver)();
if (!$service instanceof AuthService) {
throw new \RuntimeException('Guard resolver returned invalid dependency: ' . AuthService::class);
}
return $service;
return (self::$authServiceResolver)();
}
private static function tenantService(): TenantService
@@ -169,11 +161,7 @@ class Guard
if (!is_callable(self::$tenantServiceResolver)) {
throw new \RuntimeException('Guard is not configured for dependency: ' . TenantService::class);
}
$service = (self::$tenantServiceResolver)();
if (!$service instanceof TenantService) {
throw new \RuntimeException('Guard resolver returned invalid dependency: ' . TenantService::class);
}
return $service;
return (self::$tenantServiceResolver)();
}
private static function isAllowedByAbility(int $userId, string $ability, array $context = []): bool

View File

@@ -163,9 +163,6 @@ class SearchConfig
try {
$registry = (self::$moduleRegistryResolver)();
if (!$registry instanceof ModuleRegistry) {
return self::$moduleProviders;
}
foreach ($registry->getSearchResources() as $providerClass) {
$provider = self::resolveModuleProvider($providerClass);
if ($provider instanceof SearchResourceProvider) {

View File

@@ -487,11 +487,6 @@ function appBuildLayoutNavContext(array $layoutAuth, array $session, array $quer
$provider = \MintyPHP\App\Module\ModuleClassResolver::resolve($container, $providerClass);
if ($provider instanceof \MintyPHP\App\Module\Contracts\LayoutContextProvider) {
$providerData = $provider->provide($session, $container);
if (!is_array($providerData)) {
throw new \RuntimeException(
"Layout context provider '{$providerClass}' must return an array."
);
}
$layoutNav = appMergeLayoutNavProviderData($layoutNav, $providerData, $providerClass);
}
}

View File

@@ -206,9 +206,6 @@ function gridSplitToolbarSchema(array $toolbarSchema, array $searchKeys = []): a
$search = [];
$drawer = [];
foreach ($toolbarSchema as $field) {
if (!is_array($field)) {
continue;
}
$key = trim((string) ($field['key'] ?? ''));
$isSearch = (bool) ($field['search'] ?? false) || ($key !== '' && isset($searchKeyMap[$key]));
if ($isSearch) {
@@ -231,9 +228,6 @@ function gridSchemaByKey(array $toolbarSchema): array
{
$schemaByKey = [];
foreach ($toolbarSchema as $field) {
if (!is_array($field)) {
continue;
}
$key = trim((string) ($field['key'] ?? ''));
if ($key === '') {
continue;
@@ -255,9 +249,6 @@ function gridBuildToolbarFilterState(array $toolbarSchema, array $filterState):
{
$state = [];
foreach ($toolbarSchema as $field) {
if (!is_array($field)) {
continue;
}
$key = trim((string) ($field['key'] ?? ''));
if ($key === '') {
@@ -347,9 +338,6 @@ function gridOptionMapFromItems(array $items): array
{
$map = [];
foreach ($items as $item) {
if (!is_array($item)) {
continue;
}
$id = trim((string) ($item['id'] ?? ''));
if ($id === '') {
continue;
@@ -370,9 +358,6 @@ function gridOptionMapFromAllowed(array $field): array
{
$map = [];
foreach ((array) ($field['allowed'] ?? []) as $item) {
if (!is_array($item)) {
continue;
}
$id = trim((string) ($item['id'] ?? ''));
if ($id === '') {
continue;

View File

@@ -101,9 +101,6 @@ function requestNormalizeSafeInternalTarget(string $target, int $maxDepth = 5):
$queryParams = [];
parse_str((string) ($safeParts['query'] ?? ''), $queryParams);
if (!is_array($queryParams)) {
$queryParams = [];
}
$nestedReturnTarget = requestExtractNestedReturnValue($queryParams['return'] ?? null);
unset($queryParams['return']);
$query = http_build_query($queryParams);
@@ -185,9 +182,6 @@ function requestPathWithReturnTarget(string $path, string $returnTarget = ''): s
}
$queryParams = [];
parse_str((string) ($parts['query'] ?? ''), $queryParams);
if (!is_array($queryParams)) {
$queryParams = [];
}
unset($queryParams['return']);
$queryParams['return'] = $normalizedReturnTarget;
$query = http_build_query($queryParams);

View File

@@ -146,9 +146,6 @@ function selectFilter(
function renderGridFilterToolbar(array $schema, array $active = [], array $optionSets = []): void
{
foreach ($schema as $field) {
if (!is_array($field)) {
continue;
}
if (($field['render'] ?? true) === false) {
continue;
}
@@ -463,10 +460,10 @@ function appStylePathsForGroups(array $groupNames): array
$registry = app(\MintyPHP\App\Module\ModuleRegistry::class);
if ($registry instanceof \MintyPHP\App\Module\ModuleRegistry) {
foreach ($registry->getAssetGroups() as $groupName => $paths) {
if (!is_string($groupName) || $groupName === '') {
if ($groupName === '') {
continue;
}
if (!is_array($paths) || isset($groups[$groupName])) {
if (isset($groups[$groupName])) {
continue;
}
$groups[$groupName] = $paths;