From 963c3998438b81645366881c32cd255baebf7b15 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Wed, 8 Apr 2026 21:50:11 +0200 Subject: [PATCH] Fix CS --- src/ArgumentResolver/UserResolver.php | 2 +- src/Audit/AuditRecordType.php | 17 ++++------ src/Audit/Display/AbstractAuditLogDisplay.php | 3 +- src/Audit/Display/AuditLogDisplayFactory.php | 8 +++-- src/Audit/Display/PackageCreatedDisplay.php | 2 +- src/Audit/Display/UserDeletedDisplay.php | 1 - src/Audit/Display/UserVerifiedDisplay.php | 1 - src/Audit/UserRegistrationMethod.php | 2 +- src/Command/DumpPackagesV2Command.php | 7 ++-- src/Command/TransferOwnershipCommand.php | 25 +++++++-------- src/Command/UpdateFilterListCommand.php | 2 +- src/Controller/ApiController.php | 14 +++++--- src/Controller/FeedController.php | 4 +-- src/Controller/GitHubLoginController.php | 2 +- src/Controller/PackageController.php | 4 +-- src/Controller/ProfileController.php | 7 ++-- src/Controller/RegistrationController.php | 12 ++++--- src/Controller/ResetPasswordController.php | 1 - src/Entity/AuditRecord.php | 2 +- src/Entity/AuditRecordRepository.php | 3 +- src/Entity/FilterListEntry.php | 7 ++-- src/Entity/FilterListEntryRepository.php | 1 + src/Entity/Package.php | 1 - src/Entity/PackageRepository.php | 17 +++++----- src/Entity/SecurityAdvisory.php | 1 - src/Entity/UserRepository.php | 3 +- src/Entity/Version.php | 2 +- src/Entity/VersionRepository.php | 4 +-- src/Event/VersionReferenceChangedEvent.php | 8 ++--- .../BadRequestExceptionListener.php | 2 +- src/EventListener/FilterListEntryListener.php | 3 +- src/EventListener/OriginListener.php | 4 +-- src/EventListener/PackageListener.php | 2 -- src/EventListener/UserListener.php | 2 +- src/EventListener/VersionListener.php | 1 - src/FilterList/Dump/DumpableFilterList.php | 3 +- .../Dump/FilterListDumperProvider.php | 4 ++- .../FilterListEntryUpdateListener.php | 5 +-- src/FilterList/FilterListResolver.php | 3 +- .../List/AikidoMalwareFilterList.php | 7 ++-- src/FilterList/RemoteFilterListEntry.php | 3 +- src/Form/Model/AdminUpdateEmailRequest.php | 3 +- src/Form/Type/MaintainerType.php | 4 +-- src/Model/PackageManager.php | 6 ++-- src/Model/VersionIdCache.php | 2 +- src/Package/Updater.php | 8 +++-- src/Package/V2Dumper.php | 12 +++---- .../AuditLog/AbstractAdminAwareTextFilter.php | 10 +++--- src/QueryFilter/AuditLog/ActorFilter.php | 9 +++--- .../AuditLog/AuditRecordTypeFilter.php | 5 +-- .../AuditLog/DateTimeFromFilter.php | 7 ++-- src/QueryFilter/AuditLog/DateTimeToFilter.php | 7 ++-- .../AuditLog/PackageNameFilter.php | 7 ++-- src/QueryFilter/AuditLog/UserFilter.php | 11 +++---- src/QueryFilter/AuditLog/VendorFilter.php | 4 +-- src/QueryFilter/QueryFilterInterface.php | 2 ++ .../BruteForceLoginFormAuthenticator.php | 2 +- .../GitHubSecurityAdvisoriesSource.php | 3 +- src/Service/BlogRssFetcher.php | 11 +++---- src/Service/FilterListWorker.php | 32 ++++++++++--------- src/Service/IdGenerator.php | 2 -- src/Service/Locker.php | 1 - src/Util/IpAddress.php | 4 +-- ...erPackageValidMaintainersListValidator.php | 2 -- .../ValidPackageRepositoryValidator.php | 2 +- tests/Audit/AuditRecordTest.php | 7 ---- .../Display/AuditLogDisplayFactoryTest.php | 5 ++- tests/Audit/VersionAuditRecordTest.php | 1 - .../Command/TransferOwnershipCommandTest.php | 5 ++- tests/Controller/ProfileControllerTest.php | 1 - .../Controller/RegistrationControllerTest.php | 28 ++++++++-------- .../TransparencyLogControllerTest.php | 4 +-- tests/Entity/AuditRecordRepositoryTest.php | 3 -- tests/Entity/VersionRepositoryTest.php | 1 - .../Dump/FilterListDumperProviderTest.php | 2 +- tests/FilterList/FilterListResolverTest.php | 4 +-- .../List/AikidoMalwareFilterListTest.php | 6 ++-- tests/FilterListWorkerTest.php | 10 +++--- tests/Package/UpdaterTest.php | 4 --- tests/Package/V2DumperTest.php | 8 ++--- .../QueryFilter/AuditLog/ActorFilterTest.php | 2 +- .../AuditLog/AuditRecordTypeFilterTest.php | 3 +- .../AuditLog/PackageNameFilterTest.php | 2 +- tests/QueryFilter/AuditLog/UserFilterTest.php | 2 +- .../QueryFilter/AuditLog/VendorFilterTest.php | 2 +- tests/Security/EmailVerifierTest.php | 2 -- tests/SecurityAdvisoryWorkerTest.php | 2 -- tests/bootstrap.php | 4 +-- 88 files changed, 219 insertions(+), 247 deletions(-) diff --git a/src/ArgumentResolver/UserResolver.php b/src/ArgumentResolver/UserResolver.php index 026e11480..c864b49fb 100644 --- a/src/ArgumentResolver/UserResolver.php +++ b/src/ArgumentResolver/UserResolver.php @@ -56,7 +56,7 @@ public function resolve(Request $request, ArgumentMetadata $argument): iterable $user = $this->doctrine->getRepository(User::class)->findOneBy(['usernameCanonical' => $username]); - if (!$user && $this->security->isGranted('ROLE_ADMIN') && \filter_var($username, \FILTER_VALIDATE_EMAIL)) { + if (!$user && $this->security->isGranted('ROLE_ADMIN') && filter_var($username, \FILTER_VALIDATE_EMAIL)) { $user = $this->doctrine->getRepository(User::class)->findOneBy(['emailCanonical' => $username]); } diff --git a/src/Audit/AuditRecordType.php b/src/Audit/AuditRecordType.php index 4e7325b0d..73d772457 100644 --- a/src/Audit/AuditRecordType.php +++ b/src/Audit/AuditRecordType.php @@ -53,22 +53,17 @@ enum AuditRecordType: string public function category(): string { - return match($this) { - self::MaintainerAdded, self::MaintainerRemoved, self::PackageTransferred - => 'ownership', + return match ($this) { + self::MaintainerAdded, self::MaintainerRemoved, self::PackageTransferred => 'ownership', self::PackageCreated, self::PackageDeleted, self::CanonicalUrlChanged, - self::PackageAbandoned, self::PackageUnabandoned, self::PackageFrozen, self::PackageUnfrozen - => 'package', - self::VersionCreated, self::VersionDeleted, self::VersionReferenceChanged - => 'version', + self::PackageAbandoned, self::PackageUnabandoned, self::PackageFrozen, self::PackageUnfrozen => 'package', + self::VersionCreated, self::VersionDeleted, self::VersionReferenceChanged => 'version', self::UserCreated, self::UserVerified, self::UserDeleted, self::PasswordResetRequested, self::PasswordReset, self::PasswordChanged, self::EmailChanged, self::UsernameChanged, self::GitHubLinkedWithUser, self::GitHubDisconnectedFromUser, self::TwoFaAuthenticationActivated, - self::TwoFaAuthenticationDeactivated - => 'user', - self::FilterListEntryAdded, self::FilterListEntryDeleted - => 'filterlist', + self::TwoFaAuthenticationDeactivated => 'user', + self::FilterListEntryAdded, self::FilterListEntryDeleted => 'filterlist', }; } } diff --git a/src/Audit/Display/AbstractAuditLogDisplay.php b/src/Audit/Display/AbstractAuditLogDisplay.php index 04bade731..7ddb0301c 100644 --- a/src/Audit/Display/AbstractAuditLogDisplay.php +++ b/src/Audit/Display/AbstractAuditLogDisplay.php @@ -37,7 +37,6 @@ public function getActor(): ActorDisplay public function getTypeTranslationKey(): string { - return 'audit_log.type.' . $this->getType()->value; + return 'audit_log.type.'.$this->getType()->value; } - } diff --git a/src/Audit/Display/AuditLogDisplayFactory.php b/src/Audit/Display/AuditLogDisplayFactory.php index c07e73f67..a1cb9aa76 100644 --- a/src/Audit/Display/AuditLogDisplayFactory.php +++ b/src/Audit/Display/AuditLogDisplayFactory.php @@ -23,10 +23,12 @@ class AuditLogDisplayFactory { public function __construct( private readonly Security $security, - ) {} + ) { + } /** * @param iterable $auditRecords + * * @return array */ public function build(iterable $auditRecords): array @@ -91,7 +93,7 @@ public function buildSingle(AuditRecord $record): AuditLogDisplayInterface $record->attributes['name'], $record->attributes['version'], $record->attributes['metadata']['source']['reference'] ?? null, - $record->attributes['metadata']['dist']['reference'] ?? null, + $record->attributes['metadata']['dist']['reference'] ?? null, $this->buildActor($record->attributes['actor']), $record->ip, ), @@ -245,7 +247,7 @@ private function buildActor(array|string|null $actor): ActorDisplay return new ActorDisplay(null, 'unknown'); } - if (is_string($actor)) { + if (\is_string($actor)) { return new ActorDisplay(null, $actor); } diff --git a/src/Audit/Display/PackageCreatedDisplay.php b/src/Audit/Display/PackageCreatedDisplay.php index 558003c93..98ab43ebc 100644 --- a/src/Audit/Display/PackageCreatedDisplay.php +++ b/src/Audit/Display/PackageCreatedDisplay.php @@ -35,4 +35,4 @@ public function getTemplateName(): string { return 'audit_log/display/package_created.html.twig'; } -} \ No newline at end of file +} diff --git a/src/Audit/Display/UserDeletedDisplay.php b/src/Audit/Display/UserDeletedDisplay.php index e15c1e95f..ae7a9f1eb 100644 --- a/src/Audit/Display/UserDeletedDisplay.php +++ b/src/Audit/Display/UserDeletedDisplay.php @@ -13,7 +13,6 @@ namespace App\Audit\Display; use App\Audit\AuditRecordType; -use App\Audit\UserRegistrationMethod; readonly class UserDeletedDisplay extends AbstractAuditLogDisplay { diff --git a/src/Audit/Display/UserVerifiedDisplay.php b/src/Audit/Display/UserVerifiedDisplay.php index b51c3d93b..03f5bbb16 100644 --- a/src/Audit/Display/UserVerifiedDisplay.php +++ b/src/Audit/Display/UserVerifiedDisplay.php @@ -13,7 +13,6 @@ namespace App\Audit\Display; use App\Audit\AuditRecordType; -use App\Audit\UserRegistrationMethod; readonly class UserVerifiedDisplay extends AbstractAuditLogDisplay { diff --git a/src/Audit/UserRegistrationMethod.php b/src/Audit/UserRegistrationMethod.php index 6c55bab7c..149675868 100644 --- a/src/Audit/UserRegistrationMethod.php +++ b/src/Audit/UserRegistrationMethod.php @@ -19,6 +19,6 @@ enum UserRegistrationMethod: string public function translationKey(): string { - return 'audit_log.enums.user-registration-method.' . $this->value; + return 'audit_log.enums.user-registration-method.'.$this->value; } } diff --git a/src/Command/DumpPackagesV2Command.php b/src/Command/DumpPackagesV2Command.php index 95b23b904..fe9a7f6c0 100644 --- a/src/Command/DumpPackagesV2Command.php +++ b/src/Command/DumpPackagesV2Command.php @@ -16,13 +16,13 @@ use App\Package\V2Dumper; use App\Service\Locker; use Doctrine\Persistence\ManagerRegistry; +use Graze\DogStatsD\Client as StatsDClient; use Monolog\Logger; use Seld\Signal\SignalHandler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Graze\DogStatsD\Client as StatsDClient; /** * @author Jordi Boggiano @@ -38,8 +38,7 @@ public function __construct( private string $cacheDir, private Logger $logger, private StatsDClient $statsd, - ) - { + ) { parent::__construct(); } @@ -136,7 +135,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $ids = $this->getEM()->getRepository(Package::class)->getStalePackagesForDumpingV2($workerId, $numWorkers); if (\count($ids) > 2000) { $this->logger->emergency('Huge backlog in packages to be dumped is abnormal', ['count' => \count($ids), 'worker' => (string) $workerId]); - $ids = array_slice($ids, 0, 2000); + $ids = \array_slice($ids, 0, 2000); } } $this->statsd->gauge('packagist.metadata_dump_queue', \count($ids), ['worker' => (string) $workerId]); diff --git a/src/Command/TransferOwnershipCommand.php b/src/Command/TransferOwnershipCommand.php index feb9ac50c..72578dcee 100644 --- a/src/Command/TransferOwnershipCommand.php +++ b/src/Command/TransferOwnershipCommand.php @@ -12,7 +12,6 @@ namespace App\Command; -use App\Entity\AuditRecord; use App\Entity\Package; use App\Entity\User; use App\Model\PackageManager; @@ -32,8 +31,7 @@ class TransferOwnershipCommand extends Command public function __construct( private readonly ManagerRegistry $doctrine, private readonly PackageManager $packageManager, - ) - { + ) { parent::__construct(); } @@ -43,8 +41,8 @@ protected function configure(): void ->setName('packagist:transfer-ownership') ->setDescription('Transfer all packages of a vendor') ->setDefinition([ - new InputArgument('vendorOrPackage', InputArgument::REQUIRED,'Vendor or package name'), - new InputArgument('maintainers', InputArgument::IS_ARRAY|InputArgument::REQUIRED, 'The usernames of the new maintainers'), + new InputArgument('vendorOrPackage', InputArgument::REQUIRED, 'Vendor or package name'), + new InputArgument('maintainers', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'The usernames of the new maintainers'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Dry run'), ]) ; @@ -61,14 +59,15 @@ protected function execute(InputInterface $input, OutputInterface $output): int $vendorOrPackage = $input->getArgument('vendorOrPackage'); $maintainers = $this->queryAndValidateMaintainers($input, $output); - if (!count($maintainers)) { + if (!\count($maintainers)) { return Command::FAILURE; } $packages = $this->queryPackages($vendorOrPackage); - if (!count($packages)) { - $output->writeln(sprintf('No packages found for %s', $vendorOrPackage)); + if (!\count($packages)) { + $output->writeln(\sprintf('No packages found for %s', $vendorOrPackage)); + return Command::FAILURE; } @@ -98,14 +97,14 @@ private function queryAndValidateMaintainers(InputInterface $input, OutputInterf $notFound = []; foreach ($usernames as $username) { - if (!array_key_exists($username, $maintainers)) { + if (!\array_key_exists($username, $maintainers)) { $notFound[] = $username; } } sort($notFound); - $output->writeln(sprintf('%d maintainers could not be found: %s', count($notFound), implode(', ', $notFound))); + $output->writeln(\sprintf('%d maintainers could not be found: %s', \count($notFound), implode(', ', $notFound))); return []; } @@ -125,13 +124,13 @@ private function queryPackages(string $vendorOrPackage): array } return $repository->findBy([ - 'vendor' => $vendorOrPackage + 'vendor' => $vendorOrPackage, ]); } /** * @param Package[] $packages - * @param User[] $maintainers + * @param User[] $maintainers */ private function outputPackageTable(OutputInterface $output, array $packages, array $maintainers): void { @@ -163,7 +162,7 @@ private function outputPackageTable(OutputInterface $output, array $packages, ar /** * @param Package[] $packages - * @param User[] $maintainers + * @param User[] $maintainers */ private function transferOwnership(array $packages, array $maintainers): void { diff --git a/src/Command/UpdateFilterListCommand.php b/src/Command/UpdateFilterListCommand.php index 4f953e03f..164fd4b91 100644 --- a/src/Command/UpdateFilterListCommand.php +++ b/src/Command/UpdateFilterListCommand.php @@ -45,7 +45,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int try { $list = FilterLists::from($input->getArgument('list')); } catch (\ValueError) { - $output->writeln('list must be one of ' . implode(', ', array_map(fn (FilterLists $list) => $list->value, FilterLists::cases()))); + $output->writeln('list must be one of '.implode(', ', array_map(fn (FilterLists $list) => $list->value, FilterLists::cases()))); return self::INVALID; } diff --git a/src/Controller/ApiController.php b/src/Controller/ApiController.php index ddfaa3e33..46efda8b4 100644 --- a/src/Controller/ApiController.php +++ b/src/Controller/ApiController.php @@ -372,12 +372,12 @@ public function securityAdvisoryAction(Request $request, ProviderManager $provid return $resp; } - if ($request->headers->get('User-Agent') === 'GuzzleHttp/7' && in_array($request->getClientIp(), [ + if ($request->headers->get('User-Agent') === 'GuzzleHttp/7' && \in_array($request->getClientIp(), [ '168.243.26.34', '52.20.173.197', '78.46.106.56', '178.79.183.158', '77.135.173.242', '139.255.192.18', '188.40.28.3', '18.157.117.165', '15.188.186.192', '54.72.75.192', - '81.196.171.134', '52.51.253.125', '138.199.6.240', '103.217.209.214', '3.75.82.169', '65.109.33.73', '185.118.121.6', '34.233.255.120', '2a01:4f8:c013:37fb::1', '23.21.44.77', - '4.182.131.232', '185.11.255.148', '3.65.203.52', '178.22.124.147', '131.175.200.52', '80.193.72.14', '2a02:4780:d:7d90::1', '34.200.24.102', '52.72.37.76', '116.203.120.12', - '80.65.238.52', '146.177.71.160', '18.153.179.13', '3.123.161.63', '54.147.71.92', '44.197.170.214', '51.15.252.215', '2a03:b0c0:2:d0::d4c:4001', - ], true) + '81.196.171.134', '52.51.253.125', '138.199.6.240', '103.217.209.214', '3.75.82.169', '65.109.33.73', '185.118.121.6', '34.233.255.120', '2a01:4f8:c013:37fb::1', '23.21.44.77', + '4.182.131.232', '185.11.255.148', '3.65.203.52', '178.22.124.147', '131.175.200.52', '80.193.72.14', '2a02:4780:d:7d90::1', '34.200.24.102', '52.72.37.76', '116.203.120.12', + '80.65.238.52', '146.177.71.160', '18.153.179.13', '3.123.161.63', '54.147.71.92', '44.197.170.214', '51.15.252.215', '2a03:b0c0:2:d0::d4c:4001', + ], true) ) { return new JsonResponse('Please use a proper user agent with contact information to use our API', Response::HTTP_TOO_MANY_REQUESTS, ['Retry-After' => 31536000]); } @@ -491,6 +491,7 @@ protected function receiveUpdateRequest(Request $request, string $url, string $u $statsd->increment('update_pkg_api.success', tags: ['mode' => 'github_user_secret']); } else { $statsd->increment('update_pkg_api.failed', tags: ['reason' => 'invalid_user_sig']); + return new JsonResponse(['status' => 'error', 'message' => 'Secret should be the Packagist API Token for the Packagist user "'.$username.'". Signature verification failed.'], 403); } } else { @@ -520,6 +521,7 @@ protected function receiveUpdateRequest(Request $request, string $url, string $u $statsd->increment('update_pkg_api.success', tags: ['mode' => 'github_auto']); } else { $statsd->increment('update_pkg_api.failed', tags: ['reason' => 'invalid_gh_sig']); + return new JsonResponse(['status' => 'error', 'message' => 'Invalid github signature. Delete this webhook and recreate it using the manual account sync trigger from https://packagist.org/about#how-to-update-packages'], 403); } } @@ -528,6 +530,7 @@ protected function receiveUpdateRequest(Request $request, string $url, string $u if (!$packages) { if (!$user) { $statsd->increment('update_pkg_api.failed', tags: ['reason' => 'no_user_found']); + return new JsonResponse(['status' => 'error', 'message' => 'Missing or invalid username/apiToken in request'], 403); } @@ -540,6 +543,7 @@ protected function receiveUpdateRequest(Request $request, string $url, string $u if (!$packages) { $statsd->increment('update_pkg_api.failed', tags: ['reason' => 'no_package_found']); + return new JsonResponse(['status' => 'error', 'message' => 'Could not find a package that matches this request (does user maintain the package?)'], 404); } diff --git a/src/Controller/FeedController.php b/src/Controller/FeedController.php index 45d73772c..d150769ef 100644 --- a/src/Controller/FeedController.php +++ b/src/Controller/FeedController.php @@ -121,8 +121,8 @@ public function extensionReleasesAction(Request $req): Response $feed = $this->buildFeed( $req, - "New Extension Releases", - "Latest PIE extension releases on Packagist.org.", + 'New Extension Releases', + 'Latest PIE extension releases on Packagist.org.', $this->generateUrl('browse_extensions', [], UrlGeneratorInterface::ABSOLUTE_URL), $packages ); diff --git a/src/Controller/GitHubLoginController.php b/src/Controller/GitHubLoginController.php index 26643bc7c..9cdb5fc12 100644 --- a/src/Controller/GitHubLoginController.php +++ b/src/Controller/GitHubLoginController.php @@ -114,7 +114,7 @@ public function connectCheck(Request $request, ClientRegistry $clientRegistry, S } $this->getEM()->persist($user); - $this->getEM()->persist(AuditRecord::gitHubLinkedWithUser($user, $user, $githubNickname??'', $ghUser->getId())); + $this->getEM()->persist(AuditRecord::gitHubLinkedWithUser($user, $user, $githubNickname ?? '', $ghUser->getId())); $this->getEM()->flush(); $scheduler->scheduleUserScopeMigration($user->getId(), $oldScope, $user->getGithubScope() ?? ''); diff --git a/src/Controller/PackageController.php b/src/Controller/PackageController.php index 960aa5cbd..5b49c5d13 100644 --- a/src/Controller/PackageController.php +++ b/src/Controller/PackageController.php @@ -74,7 +74,6 @@ use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Component\Routing\Requirement\EnumRequirement; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; @@ -986,7 +985,6 @@ public function removeMaintainerAction(Request $req, #[MapEntity] Package $packa ]); } - #[Route(path: '/packages/{name:package}/transfer/', name: 'transfer_package', requirements: ['name' => Package::PACKAGE_NAME_REGEX], methods: ['GET', 'POST'])] public function transferPackageAction(Request $req, #[MapEntity] Package $package, #[CurrentUser] User $user, LoggerInterface $logger): RedirectResponse { @@ -1014,7 +1012,7 @@ public function transferPackageAction(Request $req, #[MapEntity] Package $packag if ($result) { $usernames = array_map(fn (User $user) => $user->getUsername(), $newMaintainers); - $this->addFlash('success', sprintf('Package has been transferred to %s', implode(', ', $usernames))); + $this->addFlash('success', \sprintf('Package has been transferred to %s', implode(', ', $usernames))); } else { $this->addFlash('warning', 'Package maintainers are identical and have not been changed'); } diff --git a/src/Controller/ProfileController.php b/src/Controller/ProfileController.php index a9a2e070f..90053aca4 100644 --- a/src/Controller/ProfileController.php +++ b/src/Controller/ProfileController.php @@ -70,7 +70,7 @@ public function publicProfile(Request $req, #[VarName('name')] User $user, Favor // Admin email update form $adminEmailForm = null; if ($this->isGranted('ROLE_ADMIN')) { - assert($loggedUser !== null); + \assert($loggedUser !== null); $adminUpdateEmailRequest = new AdminUpdateEmailRequest($user->getEmail()); $adminEmailForm = $this->createForm(AdminUpdateEmailType::class, $adminUpdateEmailRequest); $adminEmailForm->handleRequest($req); @@ -98,11 +98,12 @@ public function publicProfile(Request $req, #[VarName('name')] User $user, Favor $this->getEM()->flush(); // Send notifications - $reason = 'Your email has been changed by an administrator from ' . $oldEmail . ' to ' . $newEmail; + $reason = 'Your email has been changed by an administrator from '.$oldEmail.' to '.$newEmail; $userNotifier->notifyChange($oldEmail, $reason); $userNotifier->notifyChange($newEmail, $reason); $this->addFlash('success', 'Email address updated successfully.'); + return $this->redirectToRoute('user_profile', ['name' => $user->getUsername()]); } catch (\Exception $e) { $logger->error('Failed to update user email', [ @@ -138,7 +139,7 @@ public function publicProfile(Request $req, #[VarName('name')] User $user, Favor if ($this->isGranted('ROLE_ADMIN') && $user->getGithubId()) { $githubUsername = null; try { - $response = $httpClient->request('GET', 'https://api.github.com/user/' . $user->getGithubId()); + $response = $httpClient->request('GET', 'https://api.github.com/user/'.$user->getGithubId()); if ($response->getStatusCode() === 200) { $githubUsername = $response->toArray()['login'] ?? null; } diff --git a/src/Controller/RegistrationController.php b/src/Controller/RegistrationController.php index 1366a6cf7..32964631e 100644 --- a/src/Controller/RegistrationController.php +++ b/src/Controller/RegistrationController.php @@ -90,6 +90,7 @@ public function checkEmailConfirmation(string $token, UserRepository $userReposi if ($result === null) { $this->addFlash('error', 'This link is invalid or has expired. Please register again.'); + return $this->redirectToRoute('register'); } @@ -109,6 +110,7 @@ public function resendConfirmation(string $token, Request $request, UserReposito if ($result === null) { $this->addFlash('error', 'This link is invalid or has expired. Please register again.'); + return $this->redirectToRoute('register'); } @@ -139,7 +141,7 @@ public function resendConfirmation(string $token, Request $request, UserReposito // Generate new token with updated email $newToken = $this->generateRegistrationToken($user); - $this->addFlash('success', 'Confirmation email has been sent to ' . $user->getEmail()); + $this->addFlash('success', 'Confirmation email has been sent to '.$user->getEmail()); return $this->redirectToRoute('register_check_email', ['token' => $newToken]); } @@ -197,10 +199,10 @@ public function confirmEmail(Request $request, UserRepository $userRepository, U private function generateRegistrationToken(User $user): string { $timestamp = $this->clock->now()->getTimestamp(); - $data = $user->getId() . '|' . $user->getEmail() . '|' . $timestamp; + $data = $user->getId().'|'.$user->getEmail().'|'.$timestamp; $signature = hash_hmac('sha256', $data, $this->internalSecret); - return base64_encode($data . '|' . $signature); + return base64_encode($data.'|'.$signature); } /** @@ -214,7 +216,7 @@ private function validateRegistrationToken(string $token, UserRepository $userRe } $parts = explode('|', $decoded); - if (count($parts) !== 4) { + if (\count($parts) !== 4) { return null; } @@ -227,7 +229,7 @@ private function validateRegistrationToken(string $token, UserRepository $userRe } // Verify signature - $data = $userId . '|' . $email . '|' . $timestamp; + $data = $userId.'|'.$email.'|'.$timestamp; $expectedSignature = hash_hmac('sha256', $data, $this->internalSecret); if (!hash_equals($expectedSignature, $providedSignature)) { return null; diff --git a/src/Controller/ResetPasswordController.php b/src/Controller/ResetPasswordController.php index b5bc1e190..8475adf21 100644 --- a/src/Controller/ResetPasswordController.php +++ b/src/Controller/ResetPasswordController.php @@ -19,7 +19,6 @@ use App\Security\BruteForceLoginFormAuthenticator; use App\Security\Passport\Badge\ResolvedTwoFactorCodeCredentials; use App\Security\UserChecker; -use Beelab\Recaptcha2Bundle\Recaptcha\RecaptchaVerifier; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; diff --git a/src/Entity/AuditRecord.php b/src/Entity/AuditRecord.php index 08ddfe74b..2e885ddea 100644 --- a/src/Entity/AuditRecord.php +++ b/src/Entity/AuditRecord.php @@ -303,7 +303,7 @@ public static function filterListEntryDeleted(FilterListEntry $entry, ?User $act AuditRecordType::FilterListEntryDeleted, [ 'entry' => self::getFilterListEntryData($entry), - 'actor' => self::getUserData($actor, 'automation') + 'actor' => self::getUserData($actor, 'automation'), ], ); } diff --git a/src/Entity/AuditRecordRepository.php b/src/Entity/AuditRecordRepository.php index afa07e9ea..c2b595ae9 100644 --- a/src/Entity/AuditRecordRepository.php +++ b/src/Entity/AuditRecordRepository.php @@ -27,8 +27,7 @@ class AuditRecordRepository extends ServiceEntityRepository public function __construct( ManagerRegistry $registry, private readonly AuditRecordsManager $auditRecordsManager, - ) - { + ) { parent::__construct($registry, AuditRecord::class); } diff --git a/src/Entity/FilterListEntry.php b/src/Entity/FilterListEntry.php index 78f23432e..db6a752d3 100644 --- a/src/Entity/FilterListEntry.php +++ b/src/Entity/FilterListEntry.php @@ -35,10 +35,10 @@ class FilterListEntry private string $version; #[ORM\Column(type: 'text', nullable: true)] - private string|null $reason; + private ?string $reason; #[ORM\Column(nullable: true)] - private string|null $link; + private ?string $link; #[ORM\Column] private FilterLists $list; @@ -49,7 +49,7 @@ class FilterListEntry private \DateTimeImmutable $updatedAt; #[ORM\Column(nullable: true)] - private string|null $publicId; + private ?string $publicId; public function __construct(RemoteFilterListEntry $remote) { @@ -87,6 +87,7 @@ public function getReason(): ?string { return $this->reason; } + public function getPublicId(): ?string { return $this->publicId; diff --git a/src/Entity/FilterListEntryRepository.php b/src/Entity/FilterListEntryRepository.php index 827ff130f..0596a85d0 100644 --- a/src/Entity/FilterListEntryRepository.php +++ b/src/Entity/FilterListEntryRepository.php @@ -68,6 +68,7 @@ public function getPackageEntries(string $packageName): array /** * @param array $packageNames + * * @return array> */ public function getAllPackageEntriesMap(array $packageNames): array diff --git a/src/Entity/Package.php b/src/Entity/Package.php index 400f321db..10f62831c 100644 --- a/src/Entity/Package.php +++ b/src/Entity/Package.php @@ -12,7 +12,6 @@ namespace App\Entity; -use App\Audit\AbandonmentReason; use App\Service\UpdaterWorker; use App\Util\HttpDownloaderOptionsFactory; use App\Validator\Copyright; diff --git a/src/Entity/PackageRepository.php b/src/Entity/PackageRepository.php index e8d6d4ea9..ca770c42c 100644 --- a/src/Entity/PackageRepository.php +++ b/src/Entity/PackageRepository.php @@ -69,7 +69,7 @@ public function findProviders(string $name): array 'name' => $match[1], 'altName' => 'ext-'.$match[1], 'pkgName' => '%/'.$match[1], - ]);; + ]); $result = array_merge($result, $query->getResult()); } @@ -581,19 +581,20 @@ public function getDependents(string $name, int $offset = 0, int $limit = 15, st /** * @param list $requirers + * * @return array array keyed by requirer name and the value is requirement or null if not found */ public function getDefaultBranchRequireFor(array $requirers, string $requiree): array { $requires = $this->getEntityManager()->getConnection()->fetchAllAssociative( <<<'SQL' - SELECT p.name, COALESCE(lr.packageVersion, lrd.packageVersion, NULL) AS requirement - FROM package p - LEFT JOIN package_version pv ON pv.package_id = p.id AND pv.defaultBranch = 1 - LEFT JOIN link_require lr ON lr.version_id = pv.id AND lr.packageName = :requiree - LEFT JOIN link_require_dev lrd ON lrd.version_id = pv.id AND lrd.packageName = :requiree - WHERE p.name IN (:requirers) - SQL, + SELECT p.name, COALESCE(lr.packageVersion, lrd.packageVersion, NULL) AS requirement + FROM package p + LEFT JOIN package_version pv ON pv.package_id = p.id AND pv.defaultBranch = 1 + LEFT JOIN link_require lr ON lr.version_id = pv.id AND lr.packageName = :requiree + LEFT JOIN link_require_dev lrd ON lrd.version_id = pv.id AND lrd.packageName = :requiree + WHERE p.name IN (:requirers) + SQL, ['requiree' => $requiree, 'requirers' => $requirers], ['requirers' => ArrayParameterType::STRING], ); diff --git a/src/Entity/SecurityAdvisory.php b/src/Entity/SecurityAdvisory.php index abd363ab7..ec2196b04 100644 --- a/src/Entity/SecurityAdvisory.php +++ b/src/Entity/SecurityAdvisory.php @@ -12,7 +12,6 @@ namespace App\Entity; -use App\SecurityAdvisory\AdvisoryIdGenerator; use App\SecurityAdvisory\AdvisoryParser; use App\SecurityAdvisory\FriendsOfPhpSecurityAdvisoriesSource; use App\SecurityAdvisory\RemoteSecurityAdvisory; diff --git a/src/Entity/UserRepository.php b/src/Entity/UserRepository.php index 352d851c9..f0febfc7e 100644 --- a/src/Entity/UserRepository.php +++ b/src/Entity/UserRepository.php @@ -42,8 +42,9 @@ public function findOneByUsernameOrEmail(string $usernameOrEmail): ?User } /** - * @param string[] $usernames + * @param string[] $usernames * @param ?array $orderBy + * * @return array */ public function findEnabledUsersByUsername(array $usernames, ?array $orderBy = null): array diff --git a/src/Entity/Version.php b/src/Entity/Version.php index f328a5d0e..91f6bcbba 100644 --- a/src/Entity/Version.php +++ b/src/Entity/Version.php @@ -738,7 +738,7 @@ public function getPieSupportedOS(): array } if (isset($this->phpExt['os-families-exclude'])) { - return array_values(array_diff(["windows", "bsd", "darwin", "solaris", "linux", "unknown"], $this->phpExt['os-families-exclude'])); + return array_values(array_diff(['windows', 'bsd', 'darwin', 'solaris', 'linux', 'unknown'], $this->phpExt['os-families-exclude'])); } return ['no restrictions']; diff --git a/src/Entity/VersionRepository.php b/src/Entity/VersionRepository.php index b53a85055..bd1b44814 100644 --- a/src/Entity/VersionRepository.php +++ b/src/Entity/VersionRepository.php @@ -156,7 +156,7 @@ public function getVersionData(array $versionIds): array ['ids' => ArrayParameterType::INTEGER] ); foreach ($rows as $row) { - assert(isset($result[$row['version_id']])); + \assert(isset($result[$row['version_id']])); $result[$row['version_id']][$link][] = $row; } } @@ -168,7 +168,7 @@ public function getVersionData(array $versionIds): array ); foreach ($rows as $row) { $versionId = $row['version_id']; - assert(isset($result[$versionId])); + \assert(isset($result[$versionId])); $result[$versionId]['tags'][] = $row['name']; } diff --git a/src/Event/VersionReferenceChangedEvent.php b/src/Event/VersionReferenceChangedEvent.php index f9fb41263..645f61154 100644 --- a/src/Event/VersionReferenceChangedEvent.php +++ b/src/Event/VersionReferenceChangedEvent.php @@ -99,7 +99,7 @@ public function hasMetadataChanged(): bool */ private function arraysAreEqual(array $a, array $b): bool { - if (count($a) !== count($b)) { + if (\count($a) !== \count($b)) { return false; } @@ -107,18 +107,18 @@ private function arraysAreEqual(array $a, array $b): bool ksort($b); foreach ($a as $key => $value) { - if (!array_key_exists($key, $b)) { + if (!\array_key_exists($key, $b)) { return false; } - if (is_array($value) && is_array($b[$key])) { + if (\is_array($value) && \is_array($b[$key])) { if (!$this->arraysAreEqual($value, $b[$key])) { return false; } continue; } - if (is_array($value) !== is_array($b[$key])) { + if (\is_array($value) !== \is_array($b[$key])) { return false; } diff --git a/src/EventListener/BadRequestExceptionListener.php b/src/EventListener/BadRequestExceptionListener.php index 164655d6a..42bd08602 100644 --- a/src/EventListener/BadRequestExceptionListener.php +++ b/src/EventListener/BadRequestExceptionListener.php @@ -13,8 +13,8 @@ namespace App\EventListener; use Symfony\Component\EventDispatcher\Attribute\AsEventListener; -use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpFoundation\Exception\BadRequestException; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Twig\Error\RuntimeError; diff --git a/src/EventListener/FilterListEntryListener.php b/src/EventListener/FilterListEntryListener.php index e2c5ea848..73a0f9926 100644 --- a/src/EventListener/FilterListEntryListener.php +++ b/src/EventListener/FilterListEntryListener.php @@ -31,7 +31,8 @@ class FilterListEntryListener public function __construct( private ManagerRegistry $doctrine, private Security $security, - ) {} + ) { + } /** * @param LifecycleEventArgs $event diff --git a/src/EventListener/OriginListener.php b/src/EventListener/OriginListener.php index d919495ef..992a5c4fe 100644 --- a/src/EventListener/OriginListener.php +++ b/src/EventListener/OriginListener.php @@ -57,8 +57,8 @@ public function onRequest(RequestEvent $event): void } // valid as well with HTTP in dev - $scheme = parse_url($origin, PHP_URL_SCHEME); - $host = parse_url($origin, PHP_URL_HOST); + $scheme = parse_url($origin, \PHP_URL_SCHEME); + $host = parse_url($origin, \PHP_URL_HOST); $knownOrigin = $scheme.'://'.$host; if ('dev' === $this->environment && $knownOrigin === 'http://'.$this->packagistHost) { return; diff --git a/src/EventListener/PackageListener.php b/src/EventListener/PackageListener.php index 089b2c09d..0d1cce6cf 100644 --- a/src/EventListener/PackageListener.php +++ b/src/EventListener/PackageListener.php @@ -12,7 +12,6 @@ namespace App\EventListener; -use App\Audit\AbandonmentReason; use App\Entity\AuditRecord; use App\Entity\Package; use App\Entity\User; @@ -66,7 +65,6 @@ public function onPackageUnabandoned(PackageUnabandonedEvent $event): void $this->buffered[] = AuditRecord::packageUnabandoned($package, $this->getUser()); } - /** * @param LifecycleEventArgs $event */ diff --git a/src/EventListener/UserListener.php b/src/EventListener/UserListener.php index 2d5eeae62..fb5a89015 100644 --- a/src/EventListener/UserListener.php +++ b/src/EventListener/UserListener.php @@ -29,7 +29,7 @@ class UserListener { use DoctrineTrait; - /** @var list */ + /** @var list */ private array $buffered = []; public function __construct( diff --git a/src/EventListener/VersionListener.php b/src/EventListener/VersionListener.php index 006c8c9dd..d5e6645e5 100644 --- a/src/EventListener/VersionListener.php +++ b/src/EventListener/VersionListener.php @@ -13,7 +13,6 @@ namespace App\EventListener; use App\Entity\AuditRecord; -use App\Entity\Package; use App\Entity\User; use App\Entity\Version; use App\Event\VersionReferenceChangedEvent; diff --git a/src/FilterList/Dump/DumpableFilterList.php b/src/FilterList/Dump/DumpableFilterList.php index 19f3b55e9..1ed2971e3 100644 --- a/src/FilterList/Dump/DumpableFilterList.php +++ b/src/FilterList/Dump/DumpableFilterList.php @@ -19,5 +19,6 @@ public function __construct( public string $url, public ?string $reason, public ?string $id, - ) {} + ) { + } } diff --git a/src/FilterList/Dump/FilterListDumperProvider.php b/src/FilterList/Dump/FilterListDumperProvider.php index 8851d2f2e..b3efc7154 100644 --- a/src/FilterList/Dump/FilterListDumperProvider.php +++ b/src/FilterList/Dump/FilterListDumperProvider.php @@ -24,10 +24,12 @@ public function __construct( private ManagerRegistry $doctrine, private UrlGeneratorInterface $urlGenerator, - ) {} + ) { + } /** * @param string[] $packageNames + * * @return array>> */ public function getEntriesForDump(array $packageNames): array diff --git a/src/FilterList/FilterListEntryUpdateListener.php b/src/FilterList/FilterListEntryUpdateListener.php index 521325cda..84a5c7d60 100644 --- a/src/FilterList/FilterListEntryUpdateListener.php +++ b/src/FilterList/FilterListEntryUpdateListener.php @@ -32,7 +32,8 @@ class FilterListEntryUpdateListener public function __construct( private ManagerRegistry $doctrine, - ) {} + ) { + } /** * @param LifecycleEventArgs $event @@ -60,7 +61,7 @@ public function postRemove(FilterListEntry $entry, LifecycleEventArgs $event): v public function flushChangesToPackages(): void { - if (count($this->packagesToMarkStale) === 0) { + if (\count($this->packagesToMarkStale) === 0) { return; } diff --git a/src/FilterList/FilterListResolver.php b/src/FilterList/FilterListResolver.php index 0854a0a7d..60c94dfd3 100644 --- a/src/FilterList/FilterListResolver.php +++ b/src/FilterList/FilterListResolver.php @@ -17,8 +17,9 @@ class FilterListResolver { /** - * @param array $existingEntries + * @param array $existingEntries * @param array $remoteEntries + * * @return array{list, list, bool} */ public function resolve(array $existingEntries, array $remoteEntries): array diff --git a/src/FilterList/List/AikidoMalwareFilterList.php b/src/FilterList/List/AikidoMalwareFilterList.php index 21d4c5329..88f8da9da 100644 --- a/src/FilterList/List/AikidoMalwareFilterList.php +++ b/src/FilterList/List/AikidoMalwareFilterList.php @@ -24,7 +24,8 @@ class AikidoMalwareFilterList implements FilterListInterface public function __construct( private HttpClientInterface $httpClient, private LoggerInterface $logger, - ) {} + ) { + } public function getListEntries(): ?array { @@ -32,7 +33,7 @@ public function getListEntries(): ?array $data = json_decode( $this->httpClient->request('GET', self::FEED_URL)->getContent(), true, - flags: JSON_THROW_ON_ERROR, + flags: \JSON_THROW_ON_ERROR, ); } catch (\Throwable $e) { $this->logger->error('Failed to fetch Aikido malware list', [ @@ -55,7 +56,7 @@ public function getListEntries(): ?array $packageName, $entry['version'], FilterLists::AIKIDO_MALWARE, - sprintf('https://app.aikido.dev/reports/malware/software-supply-chain-attacks?search=%s&ecosystem=packagist', urlencode($packageName)), + \sprintf('https://app.aikido.dev/reports/malware/software-supply-chain-attacks?search=%s&ecosystem=packagist', urlencode($packageName)), 'malware', ); } diff --git a/src/FilterList/RemoteFilterListEntry.php b/src/FilterList/RemoteFilterListEntry.php index 9c6e5f7c5..b6f4586aa 100644 --- a/src/FilterList/RemoteFilterListEntry.php +++ b/src/FilterList/RemoteFilterListEntry.php @@ -20,5 +20,6 @@ public function __construct( public FilterLists $list, public ?string $link, public string $reason, - ) {} + ) { + } } diff --git a/src/Form/Model/AdminUpdateEmailRequest.php b/src/Form/Model/AdminUpdateEmailRequest.php index f312f9576..0fa62914d 100644 --- a/src/Form/Model/AdminUpdateEmailRequest.php +++ b/src/Form/Model/AdminUpdateEmailRequest.php @@ -20,5 +20,6 @@ public function __construct( #[Assert\NotBlank] #[Assert\Email] public string $email, - ) {} + ) { + } } diff --git a/src/Form/Type/MaintainerType.php b/src/Form/Type/MaintainerType.php index 9a7cbe279..ebb05e2fe 100644 --- a/src/Form/Type/MaintainerType.php +++ b/src/Form/Type/MaintainerType.php @@ -45,8 +45,8 @@ function (?string $username): ?User { $username = mb_strtolower($username); $users = $this->em->getRepository(User::class)->findEnabledUsersByUsername([$username]); - if (!count($users) || !array_key_exists($username, $users)) { - $failure = new TransformationFailedException(sprintf('User "%s" does not exist.', $username)); + if (!\count($users) || !\array_key_exists($username, $users)) { + $failure = new TransformationFailedException(\sprintf('User "%s" does not exist.', $username)); $failure->setInvalidMessage('The given "{{ value }}" value is not a valid username.', [ '{{ value }}' => $username, ]); diff --git a/src/Model/PackageManager.php b/src/Model/PackageManager.php index 5ebec63bf..80d5bda0e 100644 --- a/src/Model/PackageManager.php +++ b/src/Model/PackageManager.php @@ -248,10 +248,10 @@ public function transferPackage(Package $package, array $newMaintainers, bool $n { $oldMaintainers = $package->getMaintainers()->toArray(); $normalizedOldMaintainers = array_values(array_map(fn (User $user) => $user->getId(), $oldMaintainers)); - sort($normalizedOldMaintainers, SORT_NUMERIC); + sort($normalizedOldMaintainers, \SORT_NUMERIC); $normalizedMaintainers = array_values(array_map(fn (User $user) => $user->getId(), $newMaintainers)); - sort($normalizedMaintainers, SORT_NUMERIC); + sort($normalizedMaintainers, \SORT_NUMERIC); if ($normalizedMaintainers === $normalizedOldMaintainers) { return false; @@ -259,7 +259,7 @@ public function transferPackage(Package $package, array $newMaintainers, bool $n $package->getMaintainers()->clear(); foreach ($newMaintainers as $maintainer) { - $isNewMaintainer = !in_array($maintainer->getId(), $normalizedOldMaintainers); + $isNewMaintainer = !\in_array($maintainer->getId(), $normalizedOldMaintainers); $package->addMaintainer($maintainer); if ($notifyNewMaintainers && $isNewMaintainer) { diff --git a/src/Model/VersionIdCache.php b/src/Model/VersionIdCache.php index 02c427483..74b61b544 100644 --- a/src/Model/VersionIdCache.php +++ b/src/Model/VersionIdCache.php @@ -39,7 +39,7 @@ public function augmentDownloadPayloadWithIds(array $payload): array foreach ($results as $key => $result) { if ($result) { - assert(isset($payload[$key])); + \assert(isset($payload[$key])); [$id, $vid] = explode(',', $result); $payload[$key]['id'] = (int) $id; $payload[$key]['vid'] = (int) $vid; diff --git a/src/Package/Updater.php b/src/Package/Updater.php index bf09c0086..a9f6dc2de 100644 --- a/src/Package/Updater.php +++ b/src/Package/Updater.php @@ -27,6 +27,7 @@ use App\Entity\Version; use App\Entity\VersionRepository; use App\Event\PackageAbandonedEvent; +use App\Event\VersionReferenceChangedEvent; use App\HtmlSanitizer\ReadmeImageSanitizer; use App\HtmlSanitizer\ReadmeLinkSanitizer; use App\Model\ProviderManager; @@ -57,7 +58,6 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Contracts\EventDispatcher\Event; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; -use App\Event\VersionReferenceChangedEvent; final readonly class VersionUpdatedResult { @@ -67,7 +67,8 @@ public function __construct( public Version $entity, /** @var list $events */ public array $events = [], - ) {} + ) { + } } final readonly class VersionSkippedResult @@ -75,7 +76,8 @@ public function __construct( public function __construct( public int $id, public string $version, - ) {} + ) { + } } /** diff --git a/src/Package/V2Dumper.php b/src/Package/V2Dumper.php index 875ad47a2..50d4c3892 100644 --- a/src/Package/V2Dumper.php +++ b/src/Package/V2Dumper.php @@ -14,7 +14,6 @@ use App\Audit\AuditRecordType; use App\Entity\AuditRecord; -use App\Entity\FilterListEntry; use App\Entity\Package; use App\Entity\PackageFreezeReason; use App\Entity\SecurityAdvisory; @@ -196,7 +195,7 @@ public function dump(array $packageIds, bool $force = false, bool $verbose = fal // Verify all written files match CDN versions if (!empty($this->writtenFiles) && !$force && \count($this->writtenFiles) < 50) { if ($verbose) { - echo 'Verifying ' . count($this->writtenFiles) . ' written files match CDN versions'.\PHP_EOL; + echo 'Verifying '.\count($this->writtenFiles).' written files match CDN versions'.\PHP_EOL; } $this->verifyCdnFiles(); } @@ -231,7 +230,6 @@ public function dump(array $packageIds, bool $force = false, bool $verbose = fal sleep(2); } } - } } @@ -288,9 +286,9 @@ private function writeFileAtomic(string $path, string $contents, ?int $mtime = n /** * @param mixed[] $versionData * @param array $advisories - * @param array>|null $filterLists + * @param array>|null $filterLists */ - private function dumpPackageToV2File(string $dir, Package $package, array $versionData, array $advisories, null|array $filterLists): void + private function dumpPackageToV2File(string $dir, Package $package, array $versionData, array $advisories, ?array $filterLists): void { $name = strtolower($package->getName()); $forceDump = $package->getDumpedAtV2() === null; @@ -318,7 +316,7 @@ private function dumpPackageToV2File(string $dir, Package $package, array $versi * @param array $versions * @param VersionData $versionData */ - private function dumpVersionsToV2File(Package $package, string $name, string $dir, string $filename, string $packageName, array $versions, array $versionData, bool $forceDump, ?array $advisories = null, array|null $fitlerLists = null): void + private function dumpVersionsToV2File(Package $package, string $name, string $dir, string $filename, string $packageName, array $versions, array $versionData, bool $forceDump, ?array $advisories = null, ?array $fitlerLists = null): void { $versionArrays = []; foreach ($versions as $version) { @@ -495,7 +493,7 @@ private function verifyCdnFiles(): void $this->logger->debug('Verifying CDN files', ['files' => $this->writtenFiles]); foreach ($this->writtenFiles as $relativePath) { - $localPath = $this->webDir . '/' . $relativePath; + $localPath = $this->webDir.'/'.$relativePath; if (!file_exists($localPath)) { continue; // Skip if local file doesn't exist } diff --git a/src/QueryFilter/AuditLog/AbstractAdminAwareTextFilter.php b/src/QueryFilter/AuditLog/AbstractAdminAwareTextFilter.php index 120c0f066..7600d5c9e 100644 --- a/src/QueryFilter/AuditLog/AbstractAdminAwareTextFilter.php +++ b/src/QueryFilter/AuditLog/AbstractAdminAwareTextFilter.php @@ -21,8 +21,9 @@ abstract class AbstractAdminAwareTextFilter implements QueryFilterInterface final private function __construct( protected readonly string $key, protected readonly string $value, - protected readonly bool $isAdmin - ) {} + protected readonly bool $isAdmin, + ) { + } /** * Apply exact or wildcard matching based on admin status. @@ -51,7 +52,6 @@ final public function filter(QueryBuilder $qb): QueryBuilder $useWildcard = false; } - return $this->applyFilter($qb, $paramName, $pattern, $useWildcard); } @@ -59,7 +59,7 @@ abstract protected function applyFilter( QueryBuilder $qb, string $paramName, string $pattern, - bool $useWildcard + bool $useWildcard, ): QueryBuilder; public function getSelectedValue(): mixed @@ -74,7 +74,7 @@ public static function fromQuery(InputBag $bag, string $key, bool $isAdmin): sta { $value = $bag->get($key, ''); - if (!is_string($value) || $value === '') { + if (!\is_string($value) || $value === '') { return new static($key, '', $isAdmin); } diff --git a/src/QueryFilter/AuditLog/ActorFilter.php b/src/QueryFilter/AuditLog/ActorFilter.php index 38da72fed..789e8f3e1 100644 --- a/src/QueryFilter/AuditLog/ActorFilter.php +++ b/src/QueryFilter/AuditLog/ActorFilter.php @@ -12,7 +12,6 @@ namespace App\QueryFilter\AuditLog; -use App\Entity\User; use Doctrine\ORM\QueryBuilder; class ActorFilter extends AbstractAdminAwareTextFilter @@ -22,13 +21,13 @@ protected function applyFilter(QueryBuilder $qb, string $paramName, string $patt // If pattern is numeric search by actorId if (is_numeric($pattern) && $this->isAdmin) { $qb->setParameter($paramName, (int) $pattern); - $qb->andWhere('a.actorId = :' . $paramName); + $qb->andWhere('a.actorId = :'.$paramName); } elseif ($useWildcard) { - $qb->setParameter($paramName, sprintf('"%s"', $pattern)); - $qb->andWhere("JSON_EXTRACT(a.attributes, '$.actor.username') LIKE :" . $paramName); + $qb->setParameter($paramName, \sprintf('"%s"', $pattern)); + $qb->andWhere("JSON_EXTRACT(a.attributes, '$.actor.username') LIKE :".$paramName); } else { $qb->setParameter($paramName, $pattern); - $qb->andWhere("JSON_EXTRACT(a.attributes, '$.actor.username') = :" . $paramName); + $qb->andWhere("JSON_EXTRACT(a.attributes, '$.actor.username') = :".$paramName); } return $qb; diff --git a/src/QueryFilter/AuditLog/AuditRecordTypeFilter.php b/src/QueryFilter/AuditLog/AuditRecordTypeFilter.php index 81254be71..1cb71e20b 100644 --- a/src/QueryFilter/AuditLog/AuditRecordTypeFilter.php +++ b/src/QueryFilter/AuditLog/AuditRecordTypeFilter.php @@ -25,11 +25,12 @@ class AuditRecordTypeFilter implements QueryFilterInterface final private function __construct( private readonly string $key, private readonly array $types = [], - ) {} + ) { + } public function filter(QueryBuilder $qb): QueryBuilder { - if (count($this->types) === 0) { + if (\count($this->types) === 0) { return $qb; } diff --git a/src/QueryFilter/AuditLog/DateTimeFromFilter.php b/src/QueryFilter/AuditLog/DateTimeFromFilter.php index 143a46f16..baf8e5538 100644 --- a/src/QueryFilter/AuditLog/DateTimeFromFilter.php +++ b/src/QueryFilter/AuditLog/DateTimeFromFilter.php @@ -19,8 +19,9 @@ class DateTimeFromFilter implements QueryFilterInterface { private function __construct( - private readonly string $value - ) {} + private readonly string $value, + ) { + } public function filter(QueryBuilder $qb): QueryBuilder { @@ -51,7 +52,7 @@ public static function fromQuery(InputBag $bag): self { $value = $bag->get('datetime_from', ''); - if (!is_string($value) || $value === '') { + if (!\is_string($value) || $value === '') { return new self(''); } diff --git a/src/QueryFilter/AuditLog/DateTimeToFilter.php b/src/QueryFilter/AuditLog/DateTimeToFilter.php index 0bd941675..0557e1c78 100644 --- a/src/QueryFilter/AuditLog/DateTimeToFilter.php +++ b/src/QueryFilter/AuditLog/DateTimeToFilter.php @@ -19,8 +19,9 @@ class DateTimeToFilter implements QueryFilterInterface { private function __construct( - private readonly string $value - ) {} + private readonly string $value, + ) { + } public function filter(QueryBuilder $qb): QueryBuilder { @@ -51,7 +52,7 @@ public static function fromQuery(InputBag $bag): self { $value = $bag->get('datetime_to', ''); - if (!is_string($value) || $value === '') { + if (!\is_string($value) || $value === '') { return new self(''); } diff --git a/src/QueryFilter/AuditLog/PackageNameFilter.php b/src/QueryFilter/AuditLog/PackageNameFilter.php index 8835f0d12..d1bdece8d 100644 --- a/src/QueryFilter/AuditLog/PackageNameFilter.php +++ b/src/QueryFilter/AuditLog/PackageNameFilter.php @@ -13,18 +13,17 @@ namespace App\QueryFilter\AuditLog; use Doctrine\ORM\QueryBuilder; -use Symfony\Component\HttpFoundation\InputBag; class PackageNameFilter extends AbstractAdminAwareTextFilter { protected function applyFilter(QueryBuilder $qb, string $paramName, string $pattern, bool $useWildcard): QueryBuilder { if ($useWildcard) { - $qb->setParameter($paramName, sprintf('"%s"', $pattern)); - $qb->andWhere("JSON_EXTRACT(a.attributes, '$.name') LIKE :" . $paramName); + $qb->setParameter($paramName, \sprintf('"%s"', $pattern)); + $qb->andWhere("JSON_EXTRACT(a.attributes, '$.name') LIKE :".$paramName); } else { $qb->setParameter($paramName, $pattern); - $qb->andWhere("JSON_EXTRACT(a.attributes, '$.name') = :" . $paramName); + $qb->andWhere("JSON_EXTRACT(a.attributes, '$.name') = :".$paramName); } return $qb; diff --git a/src/QueryFilter/AuditLog/UserFilter.php b/src/QueryFilter/AuditLog/UserFilter.php index ebb303441..706ae4cfe 100644 --- a/src/QueryFilter/AuditLog/UserFilter.php +++ b/src/QueryFilter/AuditLog/UserFilter.php @@ -12,9 +12,7 @@ namespace App\QueryFilter\AuditLog; -use App\Entity\User; use Doctrine\ORM\QueryBuilder; -use Symfony\Component\HttpFoundation\InputBag; class UserFilter extends AbstractAdminAwareTextFilter { @@ -23,17 +21,16 @@ protected function applyFilter(QueryBuilder $qb, string $paramName, string $patt // If pattern is numeric search by userId if (is_numeric($pattern) && $this->isAdmin) { $qb->setParameter($paramName, (int) $pattern); - $qb->andWhere('a.userId = :' . $paramName); + $qb->andWhere('a.userId = :'.$paramName); } elseif ($useWildcard) { - $qb->setParameter($paramName, sprintf('"%s"', $pattern)); - $qb->andWhere("JSON_EXTRACT(a.attributes, '$.user.username') LIKE :" . $paramName); + $qb->setParameter($paramName, \sprintf('"%s"', $pattern)); + $qb->andWhere("JSON_EXTRACT(a.attributes, '$.user.username') LIKE :".$paramName); } else { $qb->setParameter($paramName, $pattern); $qb->setParameter($paramName.'Json', json_encode(['username' => $pattern])); - $qb->andWhere("(JSON_EXTRACT(a.attributes, '$.user.username') = :" . $paramName." OR JSON_CONTAINS(a.attributes, :". $paramName."Json, '$.current_maintainers') = 1 OR JSON_CONTAINS(a.attributes, :". $paramName."Json, '$.previous_maintainers') = 1)"); + $qb->andWhere("(JSON_EXTRACT(a.attributes, '$.user.username') = :".$paramName.' OR JSON_CONTAINS(a.attributes, :'.$paramName."Json, '$.current_maintainers') = 1 OR JSON_CONTAINS(a.attributes, :".$paramName."Json, '$.previous_maintainers') = 1)"); } return $qb; } - } diff --git a/src/QueryFilter/AuditLog/VendorFilter.php b/src/QueryFilter/AuditLog/VendorFilter.php index aa97648b2..d31385dde 100644 --- a/src/QueryFilter/AuditLog/VendorFilter.php +++ b/src/QueryFilter/AuditLog/VendorFilter.php @@ -21,9 +21,9 @@ protected function applyFilter(QueryBuilder $qb, string $paramName, string $patt $qb->setParameter($paramName, $pattern); if ($useWildcard) { - $qb->andWhere('a.vendor LIKE :' . $paramName); + $qb->andWhere('a.vendor LIKE :'.$paramName); } else { - $qb->andWhere('a.vendor = :' . $paramName); + $qb->andWhere('a.vendor = :'.$paramName); } return $qb; diff --git a/src/QueryFilter/QueryFilterInterface.php b/src/QueryFilter/QueryFilterInterface.php index 7a5969915..bc5a44a13 100644 --- a/src/QueryFilter/QueryFilterInterface.php +++ b/src/QueryFilter/QueryFilterInterface.php @@ -17,6 +17,8 @@ interface QueryFilterInterface { public function filter(QueryBuilder $qb): QueryBuilder; + public function getKey(): string; + public function getSelectedValue(): mixed; } diff --git a/src/Security/BruteForceLoginFormAuthenticator.php b/src/Security/BruteForceLoginFormAuthenticator.php index a1c6d67f2..8f0c244e6 100644 --- a/src/Security/BruteForceLoginFormAuthenticator.php +++ b/src/Security/BruteForceLoginFormAuthenticator.php @@ -133,7 +133,7 @@ private function getCredentials(Request $request): array ]; if (!\is_string($credentials['username'])) { - throw new BadRequestHttpException(\sprintf('The key "_username" must be a string, "%s" given.', \get_debug_type($credentials['username']))); + throw new BadRequestHttpException(\sprintf('The key "_username" must be a string, "%s" given.', get_debug_type($credentials['username']))); } $credentials['username'] = trim($credentials['username']); diff --git a/src/SecurityAdvisory/GitHubSecurityAdvisoriesSource.php b/src/SecurityAdvisory/GitHubSecurityAdvisoriesSource.php index c18e8e9db..bdad53cbb 100644 --- a/src/SecurityAdvisory/GitHubSecurityAdvisoriesSource.php +++ b/src/SecurityAdvisory/GitHubSecurityAdvisoriesSource.php @@ -82,6 +82,7 @@ public function getAdvisories(ConsoleIO $io): ?RemoteSecurityAdvisoryCollection $this->logger->error('Failed to fetch GitHub advisories, aborting.', [ 'exception' => $e, ]); + return null; } @@ -93,7 +94,7 @@ public function getAdvisories(ConsoleIO $io): ?RemoteSecurityAdvisoryCollection } } while ($retries-- > 0); - assert(isset($data)); + \assert(isset($data)); foreach ($data['securityVulnerabilities']['nodes'] as $node) { $remoteId = null; diff --git a/src/Service/BlogRssFetcher.php b/src/Service/BlogRssFetcher.php index 2d29c881f..47b9770c6 100644 --- a/src/Service/BlogRssFetcher.php +++ b/src/Service/BlogRssFetcher.php @@ -12,11 +12,7 @@ namespace App\Service; -use Composer\Pcre\Preg; use Psr\Log\LoggerInterface; -use Symfony\Component\HtmlSanitizer\HtmlSanitizer; -use Symfony\Component\HtmlSanitizer\HtmlSanitizerAction; -use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; @@ -49,6 +45,7 @@ public function getNewsItems(): array $this->logger->error('Failed to fetch blog RSS feed', [ 'error' => $e->getMessage(), ]); + return []; } } @@ -72,7 +69,7 @@ private function fetchAndParseRss(): array } // Only include items with composer or packagist.org category - if (!in_array('composer', $categories, true) && !in_array('packagist.org', $categories, true)) { + if (!\in_array('composer', $categories, true) && !\in_array('packagist.org', $categories, true)) { continue; } @@ -87,7 +84,7 @@ private function fetchAndParseRss(): array $desc = $entry->description; $desc = str_replace('><', '> <', (string) $desc); - $desc = trim(html_entity_decode(strip_tags($desc), ENT_QUOTES | ENT_HTML5, 'UTF-8')); + $desc = trim(html_entity_decode(strip_tags($desc), \ENT_QUOTES | \ENT_HTML5, 'UTF-8')); $items[] = [ 'title' => (string) $entry->title, @@ -96,7 +93,7 @@ private function fetchAndParseRss(): array 'datePublished' => $pubDate, ]; - if (count($items) >= self::MAX_ITEMS) { + if (\count($items) >= self::MAX_ITEMS) { break; } } diff --git a/src/Service/FilterListWorker.php b/src/Service/FilterListWorker.php index 6faf3c1ca..7af88458c 100644 --- a/src/Service/FilterListWorker.php +++ b/src/Service/FilterListWorker.php @@ -13,16 +13,16 @@ namespace App\Service; use App\Entity\FilterListEntry; +use App\Entity\Job; use App\Entity\Package; -use App\FilterList\FilterLists; -use App\FilterList\List\FilterListInterface; use App\FilterList\FilterListEntryUpdateListener; use App\FilterList\FilterListResolver; -use App\Entity\Job; +use App\FilterList\FilterLists; +use App\FilterList\List\FilterListInterface; use App\Model\DownloadManager; +use Doctrine\Persistence\ManagerRegistry; use Psr\Log\LoggerInterface; use Seld\Signal\SignalHandler; -use Doctrine\Persistence\ManagerRegistry; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; @@ -46,10 +46,12 @@ public function __construct( private DownloadManager $downloadManager, private string $mailFromEmail, private UrlGeneratorInterface $urlGenerator, - ) {} + ) { + } /** * @param Job $job + * * @return FilterListCompletedResult|FilterListErroredResult|RescheduleResult */ public function process(Job $job, SignalHandler $signal): array @@ -100,20 +102,20 @@ public function process(Job $job, SignalHandler $signal): array $packageUrl = $this->urlGenerator->generate('view_package', ['name' => $packageName], UrlGeneratorInterface::ABSOLUTE_URL); if ($downloads >= 10_000) { - $subject = '[URGENT] Filter list entry added for high-download package ' . $packageName . ' (' . number_format($downloads) . ' downloads)'; - $body = 'A new filter list entry has been added for ' . $packageName . ' which has ' . number_format($downloads) . " total downloads. This requires urgent attention.\n\n"; + $subject = '[URGENT] Filter list entry added for high-download package '.$packageName.' ('.number_format($downloads).' downloads)'; + $body = 'A new filter list entry has been added for '.$packageName.' which has '.number_format($downloads)." total downloads. This requires urgent attention.\n\n"; } else { - $subject = 'Filter list entry added for ' . $packageName; - $body = 'A new filter list entry has been added for ' . $packageName . ".\n\n"; + $subject = 'Filter list entry added for '.$packageName; + $body = 'A new filter list entry has been added for '.$packageName.".\n\n"; } - $body .= 'Package: ' . $packageUrl . "\n" - . 'List: ' . $list->value . "\n" - . 'Versions: ' . implode(', ', array_map(fn (FilterListEntry $e) => $e->getVersion(), $entries)) . "\n" - . 'Reason: ' . ($entries[0]->getReason() ?? 'N/A') . "\n" - . 'Link: ' . ($entries[0]->getLink() ?? 'N/A') . "\n"; + $body .= 'Package: '.$packageUrl."\n" + .'List: '.$list->value."\n" + .'Versions: '.implode(', ', array_map(fn (FilterListEntry $e) => $e->getVersion(), $entries))."\n" + .'Reason: '.($entries[0]->getReason() ?? 'N/A')."\n" + .'Link: '.($entries[0]->getLink() ?? 'N/A')."\n"; - $message = (new Email()) + $message = new Email() ->subject($subject) ->from(new Address($this->mailFromEmail)) ->to($this->mailFromEmail) diff --git a/src/Service/IdGenerator.php b/src/Service/IdGenerator.php index c5c9d8045..da7361e81 100644 --- a/src/Service/IdGenerator.php +++ b/src/Service/IdGenerator.php @@ -20,13 +20,11 @@ class IdGenerator public static function generateSecurityAdvisoryId(): string { return self::generate('PKSA-'); - } public static function generateFilterListEntry(): string { return self::generate('PKFE-'); - } private static function generate(string $prefix): string diff --git a/src/Service/Locker.php b/src/Service/Locker.php index 8f63a5f7a..4ec09cd36 100644 --- a/src/Service/Locker.php +++ b/src/Service/Locker.php @@ -12,7 +12,6 @@ namespace App\Service; -use App\FilterList\FilterLists; use App\Util\DoctrineTrait; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection; diff --git a/src/Util/IpAddress.php b/src/Util/IpAddress.php index ce3899b73..2eea2c84d 100644 --- a/src/Util/IpAddress.php +++ b/src/Util/IpAddress.php @@ -12,8 +12,6 @@ namespace App\Util; -use Composer\Pcre\Preg; - class IpAddress { public static function stringToBinary(?string $value): ?string @@ -24,7 +22,7 @@ public static function stringToBinary(?string $value): ?string $binary = inet_pton($value); if ($binary === false) { - throw new \InvalidArgumentException('Invalid IP address: ' . $value); + throw new \InvalidArgumentException('Invalid IP address: '.$value); } return $binary; diff --git a/src/Validator/Constraints/TransferPackageValidMaintainersListValidator.php b/src/Validator/Constraints/TransferPackageValidMaintainersListValidator.php index 3036b697b..d3e35fc18 100644 --- a/src/Validator/Constraints/TransferPackageValidMaintainersListValidator.php +++ b/src/Validator/Constraints/TransferPackageValidMaintainersListValidator.php @@ -12,8 +12,6 @@ namespace App\Validator\Constraints; -use App\Entity\User; -use App\Form\Model\InvalidMaintainer; use Doctrine\Common\Collections\Collection; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; diff --git a/src/Validator/ValidPackageRepositoryValidator.php b/src/Validator/ValidPackageRepositoryValidator.php index f5484d57b..da98b5152 100644 --- a/src/Validator/ValidPackageRepositoryValidator.php +++ b/src/Validator/ValidPackageRepositoryValidator.php @@ -90,7 +90,7 @@ public function validate(mixed $value, Constraint $constraint): void } $name = $value->getName(); - if (!Preg::isMatch(sprintf('{^%s$}D', Package::PACKAGE_NAME_REGEX), $name)) { + if (!Preg::isMatch(\sprintf('{^%s$}D', Package::PACKAGE_NAME_REGEX), $name)) { $this->addViolation('The package name '.htmlentities($name, \ENT_COMPAT, 'utf-8').' is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match "[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9]([_.-]?[a-z0-9]+)*".'); return; diff --git a/tests/Audit/AuditRecordTest.php b/tests/Audit/AuditRecordTest.php index 7eb5ddfff..082581636 100644 --- a/tests/Audit/AuditRecordTest.php +++ b/tests/Audit/AuditRecordTest.php @@ -12,20 +12,13 @@ namespace App\Tests\Audit; -use App\Audit\AuditRecordType; use App\Entity\AuditRecord; use App\Entity\Package; -use App\Entity\RequireLink; -use App\Entity\User; -use App\Entity\Version; -use App\Event\VersionReferenceChangedEvent; use Doctrine\DBAL\Connection; use Doctrine\Persistence\ManagerRegistry; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; -use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class AuditRecordTest extends KernelTestCase { diff --git a/tests/Audit/Display/AuditLogDisplayFactoryTest.php b/tests/Audit/Display/AuditLogDisplayFactoryTest.php index 3b41f3b7d..ee8d7938d 100644 --- a/tests/Audit/Display/AuditLogDisplayFactoryTest.php +++ b/tests/Audit/Display/AuditLogDisplayFactoryTest.php @@ -649,9 +649,8 @@ private function createAuditRecord( array $attributes, ?\DateTimeImmutable $datetime = null, ?int $userId = null, - ): AuditRecord - { - $datetime = $datetime ?? new \DateTimeImmutable(); + ): AuditRecord { + $datetime ??= new \DateTimeImmutable(); $reflection = new \ReflectionClass(AuditRecord::class); $instance = $reflection->newInstanceWithoutConstructor(); diff --git a/tests/Audit/VersionAuditRecordTest.php b/tests/Audit/VersionAuditRecordTest.php index a26b9533b..a3504b631 100644 --- a/tests/Audit/VersionAuditRecordTest.php +++ b/tests/Audit/VersionAuditRecordTest.php @@ -22,7 +22,6 @@ use Doctrine\DBAL\Connection; use Doctrine\Persistence\ManagerRegistry; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; -use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class VersionAuditRecordTest extends KernelTestCase diff --git a/tests/Command/TransferOwnershipCommandTest.php b/tests/Command/TransferOwnershipCommandTest.php index ea5d8db26..610b9b76b 100644 --- a/tests/Command/TransferOwnershipCommandTest.php +++ b/tests/Command/TransferOwnershipCommandTest.php @@ -39,8 +39,8 @@ protected function setUp(): void $this->store($alice, $bob, $john); $this->package1 = self::createPackage('vendor1/package1', 'https://github.com/vendor1/package1', maintainers: [$john, $alice]); - $this->package2 = self::createPackage('vendor1/package2', 'https://github.com/vendor1/package2',maintainers: [$john, $bob]); - $this->package3 = self::createPackage('vendor2/package1', 'https://github.com/vendor2/package1',maintainers: [$john]); + $this->package2 = self::createPackage('vendor1/package2', 'https://github.com/vendor1/package2', maintainers: [$john, $bob]); + $this->package3 = self::createPackage('vendor2/package1', 'https://github.com/vendor2/package1', maintainers: [$john]); $this->store($this->package1, $this->package2, $this->package3); $command = new TransferOwnershipCommand(self::getContainer()->get(ManagerRegistry::class), self::getContainer()->get(PackageManager::class)); @@ -95,7 +95,6 @@ public function testExecuteSuccessForPackage(): void $callable = fn (User $user) => $user->getUsernameCanonical(); $this->assertEqualsCanonicalizing(['bob', 'john'], array_map($callable, $package2->getMaintainers()->toArray()), 'vendor1 packages should not be changed'); $this->assertEqualsCanonicalizing(['alice', 'john'], array_map($callable, $package3->getMaintainers()->toArray())); - } public function testExecuteWithDryRunDoesNothing(): void diff --git a/tests/Controller/ProfileControllerTest.php b/tests/Controller/ProfileControllerTest.php index 8d83f9538..4c8bea018 100644 --- a/tests/Controller/ProfileControllerTest.php +++ b/tests/Controller/ProfileControllerTest.php @@ -17,7 +17,6 @@ use App\Entity\User; use App\Tests\IntegrationTestCase; use Symfony\Component\Mime\Email; -use Symfony\Component\Mime\RawMessage; class ProfileControllerTest extends IntegrationTestCase { diff --git a/tests/Controller/RegistrationControllerTest.php b/tests/Controller/RegistrationControllerTest.php index d5ce2cfb1..f913fb76a 100644 --- a/tests/Controller/RegistrationControllerTest.php +++ b/tests/Controller/RegistrationControllerTest.php @@ -85,7 +85,7 @@ public function testCheckEmailPageDisplaysCorrectly(): void { $token = $this->registerUserAndGetToken('test@example.com', 'test.user'); - $crawler = $this->client->request('GET', '/register/check-email/' . $token); + $crawler = $this->client->request('GET', '/register/check-email/'.$token); $this->assertResponseStatusCodeSame(200); $this->assertStringContainsString('test@example.com', $crawler->filter('body')->text()); @@ -97,7 +97,7 @@ public function testEmailUpdateAndResend(): void { $token = $this->registerUserAndGetToken('old@example.com', 'test.user2'); - $crawler = $this->client->request('GET', '/register/check-email/' . $token); + $crawler = $this->client->request('GET', '/register/check-email/'.$token); $this->assertResponseStatusCodeSame(200); $form = $crawler->selectButton('Update & Resend Confirmation Email')->form(); @@ -135,7 +135,7 @@ public function testEmailUpdateDoesNotCreateAuditRecordIfEmailIsUnchanged(): voi { $token = $this->registerUserAndGetToken('old@example.com', 'test.user2'); - $crawler = $this->client->request('GET', '/register/check-email/' . $token); + $crawler = $this->client->request('GET', '/register/check-email/'.$token); $this->assertResponseStatusCodeSame(200); $form = $crawler->selectButton('Update & Resend Confirmation Email')->form(); @@ -153,7 +153,7 @@ public function testInvalidEmailRejected(): void { $token = $this->registerUserAndGetToken('test@example.com', 'test.user3'); - $crawler = $this->client->request('GET', '/register/check-email/' . $token); + $crawler = $this->client->request('GET', '/register/check-email/'.$token); $form = $crawler->selectButton('Update & Resend Confirmation Email')->form(); $form->setValues([ 'update_email_form[email]' => 'invalid-email', @@ -172,9 +172,9 @@ public function testExpiredTokenRejected(): void $token = $this->registerUserAndGetToken('test@example.com', 'test.user4'); - $mockClock->sleep(11*60); + $mockClock->sleep(11 * 60); - $this->client->request('GET', '/register/check-email/' . $token); + $this->client->request('GET', '/register/check-email/'.$token); $this->assertResponseStatusCodeSame(302); $this->assertResponseRedirects('/register/'); @@ -198,7 +198,7 @@ public function testEnabledUserCannotUseToken(): void $user->setEnabled(true); $em->flush(); - $this->client->request('GET', '/register/check-email/' . $token); + $this->client->request('GET', '/register/check-email/'.$token); $this->assertResponseStatusCodeSame(302); $this->assertResponseRedirects('/register/'); } @@ -208,9 +208,9 @@ public function testTamperedTokenRejected(): void $token = $this->registerUserAndGetToken('test@example.com', 'test.user6'); // Tamper with the token by changing a character - $tamperedToken = substr($token, 0, -5) . 'XXXXX'; + $tamperedToken = substr($token, 0, -5).'XXXXX'; - $this->client->request('GET', '/register/check-email/' . $tamperedToken); + $this->client->request('GET', '/register/check-email/'.$tamperedToken); $this->assertResponseStatusCodeSame(302); $this->assertResponseRedirects('/register/'); } @@ -244,13 +244,13 @@ public function testEmailConfirmationLinkInvalidatedAfterEmailUpdate(): void // Get the check-email token $redirectUrl = $this->client->getResponse()->headers->get('Location'); - $token = substr($redirectUrl, strlen('/register/check-email/')); + $token = substr($redirectUrl, \strlen('/register/check-email/')); // Re-enable profiler for next request $this->client->enableProfiler(); // Update email to B and resend - $crawler = $this->client->request('GET', '/register/check-email/' . $token); + $crawler = $this->client->request('GET', '/register/check-email/'.$token); $form = $crawler->selectButton('Update & Resend Confirmation Email')->form(); $form->setValues([ 'update_email_form[email]' => 'emailB@example.com', @@ -279,7 +279,7 @@ public function testEmailConfirmationLinkInvalidatedAfterEmailUpdate(): void // Try to activate with the ORIGINAL link for email A (should fail) $urlParts = parse_url($originalVerificationUrl); - $verificationPathA = $urlParts['path'] . '?' . $urlParts['query']; + $verificationPathA = $urlParts['path'].'?'.$urlParts['query']; $this->client->request('GET', $verificationPathA); @@ -293,7 +293,7 @@ public function testEmailConfirmationLinkInvalidatedAfterEmailUpdate(): void // Now activate with the NEW email B's verification link (should succeed) $urlParts = parse_url($newVerificationUrl); - $verificationPathB = $urlParts['path'] . '?' . $urlParts['query']; + $verificationPathB = $urlParts['path'].'?'.$urlParts['query']; $this->client->request('GET', $verificationPathB); $this->assertResponseStatusCodeSame(302); @@ -322,6 +322,6 @@ private function registerUserAndGetToken(string $email, string $username): strin $this->assertStringStartsWith('/register/check-email/', $redirectUrl); // Extract token from redirect URL - return substr($redirectUrl, strlen('/register/check-email/')); + return substr($redirectUrl, \strlen('/register/check-email/')); } } diff --git a/tests/Controller/TransparencyLogControllerTest.php b/tests/Controller/TransparencyLogControllerTest.php index 031261e88..827ef2d13 100644 --- a/tests/Controller/TransparencyLogControllerTest.php +++ b/tests/Controller/TransparencyLogControllerTest.php @@ -33,7 +33,7 @@ public function testViewAuditLogs(array $filters, array $expected): void $this->store($auditRecord1, $auditRecord); $this->client->loginUser($user); - $crawler = $this->client->request('GET', '/transparency-log?' . http_build_query($filters)); + $crawler = $this->client->request('GET', '/transparency-log?'.http_build_query($filters)); static::assertResponseIsSuccessful(); $rows = $crawler->filter('[data-test=audit-log-type]'); @@ -71,7 +71,7 @@ public function testViewAuditLogsWithDateTimeFilter(): void $from = $now->modify('-1 hour')->format('Y-m-d\TH:i:s'); $to = $now->modify('+1 hour')->format('Y-m-d\TH:i:s'); - $crawler = $this->client->request('GET', '/transparency-log?' . http_build_query([ + $crawler = $this->client->request('GET', '/transparency-log?'.http_build_query([ 'datetime_from' => $from, 'datetime_to' => $to, ])); diff --git a/tests/Entity/AuditRecordRepositoryTest.php b/tests/Entity/AuditRecordRepositoryTest.php index c42e58173..01a6fbc2e 100644 --- a/tests/Entity/AuditRecordRepositoryTest.php +++ b/tests/Entity/AuditRecordRepositoryTest.php @@ -14,10 +14,7 @@ use App\Audit\UserRegistrationMethod; use App\Entity\AuditRecord; -use App\Entity\AuditRecordRepository; -use App\Entity\User; use App\Tests\IntegrationTestCase; -use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; diff --git a/tests/Entity/VersionRepositoryTest.php b/tests/Entity/VersionRepositoryTest.php index 8d166db56..e1e672e9b 100644 --- a/tests/Entity/VersionRepositoryTest.php +++ b/tests/Entity/VersionRepositoryTest.php @@ -69,6 +69,5 @@ public function testRemoveVersionMarksForRemovalWithAuditRecord(bool $createAudi } else { $this->assertNull($auditRecord, 'Audit record for version deleted created'); } - } } diff --git a/tests/FilterList/Dump/FilterListDumperProviderTest.php b/tests/FilterList/Dump/FilterListDumperProviderTest.php index 4f622accc..510043151 100644 --- a/tests/FilterList/Dump/FilterListDumperProviderTest.php +++ b/tests/FilterList/Dump/FilterListDumperProviderTest.php @@ -70,7 +70,7 @@ public function testGetMalwareDataForDump(): void new DumpableFilterList('1.0.0', '', 'malware', 'PKFE-test1'), new DumpableFilterList('2.0.0', '', 'malware', 'PKFE-test2'), ], - ] + ], ], $this->filterListDumperProvider->getEntriesForDump(['acme/package'])); } diff --git a/tests/FilterList/FilterListResolverTest.php b/tests/FilterList/FilterListResolverTest.php index e7390e980..5530cf3ce 100644 --- a/tests/FilterList/FilterListResolverTest.php +++ b/tests/FilterList/FilterListResolverTest.php @@ -132,7 +132,7 @@ private function createRemoteFilterListEntry(string $packageName, string $versio $packageName, $version, FilterLists::AIKIDO_MALWARE, - 'https://example.com/' . $packageName, + 'https://example.com/'.$packageName, 'malware', ); } @@ -150,7 +150,7 @@ private function assertEntry(RemoteFilterListEntry $remote, array $new): void private function unsetPublicId(FilterListEntry $entry): void { - $reflectionProperty = new TypedNoDefaultReflectionProperty(get_class($entry), 'publicId'); + $reflectionProperty = new TypedNoDefaultReflectionProperty($entry::class, 'publicId'); $reflectionProperty->setValue($entry, null); } } diff --git a/tests/FilterList/List/AikidoMalwareFilterListTest.php b/tests/FilterList/List/AikidoMalwareFilterListTest.php index 0cac532c7..f38e261fc 100644 --- a/tests/FilterList/List/AikidoMalwareFilterListTest.php +++ b/tests/FilterList/List/AikidoMalwareFilterListTest.php @@ -81,7 +81,7 @@ public function testGetListEntriesReturnsEmptyOnInvalidJson(): void { $feed = new AikidoMalwareFilterList($this->createHttpClient('not valid json'), new NullLogger()); - $this->assertSame(null, $feed->getListEntries()); + $this->assertNull($feed->getListEntries()); } public function testGetListEntriesEmptyArray(): void @@ -98,7 +98,7 @@ public function testGetListEntriesSetsCorrectLink(): void { $feed = new AikidoMalwareFilterList($this->createHttpClient(json_encode([ ['package_name' => 'vendor/malware', 'version' => '1.0.0', 'reason' => 'malware'], - ], JSON_THROW_ON_ERROR)), new NullLogger()); + ], \JSON_THROW_ON_ERROR)), new NullLogger()); $result = $feed->getListEntries(); @@ -112,7 +112,7 @@ public function testGetListEntriesPreservesOriginalVersion(): void { $feed = new AikidoMalwareFilterList($this->createHttpClient(json_encode([ ['package_name' => 'vendor/malware', 'version' => 'v1.2.3-beta', 'reason' => 'malware'], - ], JSON_THROW_ON_ERROR)), new NullLogger()); + ], \JSON_THROW_ON_ERROR)), new NullLogger()); $result = $feed->getListEntries(); diff --git a/tests/FilterListWorkerTest.php b/tests/FilterListWorkerTest.php index e00d5bc72..64d46a5e2 100644 --- a/tests/FilterListWorkerTest.php +++ b/tests/FilterListWorkerTest.php @@ -12,19 +12,19 @@ namespace App\Tests; -use App\Entity\Job; use App\Entity\FilterListEntry; use App\Entity\FilterListEntryRepository; +use App\Entity\Job; use App\Entity\Package; use App\Entity\PackageRepository; -use App\FilterList\FilterLists; -use App\FilterList\List\FilterListInterface; use App\FilterList\FilterListEntryUpdateListener; use App\FilterList\FilterListResolver; +use App\FilterList\FilterLists; +use App\FilterList\List\FilterListInterface; use App\FilterList\RemoteFilterListEntry; use App\Model\DownloadManager; -use App\Service\Locker; use App\Service\FilterListWorker; +use App\Service\Locker; use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManager; use Doctrine\Persistence\ManagerRegistry; @@ -192,7 +192,7 @@ private function createRemoteFilterListEntry(string $packageName, string $versio $packageName, $version, FilterLists::AIKIDO_MALWARE, - 'https://example.com/' . $packageName, + 'https://example.com/'.$packageName, 'malware', ); } diff --git a/tests/Package/UpdaterTest.php b/tests/Package/UpdaterTest.php index 62a77848f..4c056b250 100644 --- a/tests/Package/UpdaterTest.php +++ b/tests/Package/UpdaterTest.php @@ -12,11 +12,8 @@ namespace App\Tests\Package; -use App\Audit\AuditRecordType; -use App\Entity\AuditRecord; use App\Entity\Package; use App\Entity\PackageReadme; -use App\Entity\Version; use App\Model\ProviderManager; use App\Model\VersionIdCache; use App\Package\Updater; @@ -36,7 +33,6 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class UpdaterTest extends IntegrationTestCase { diff --git a/tests/Package/V2DumperTest.php b/tests/Package/V2DumperTest.php index 6f7307f24..b10d0eed1 100644 --- a/tests/Package/V2DumperTest.php +++ b/tests/Package/V2DumperTest.php @@ -47,8 +47,8 @@ protected function setUp(): void $this->webDir = sys_get_temp_dir().'/v2dumper_web_'.uniqid('', true); $this->buildDir = sys_get_temp_dir().'/v2dumper_build_'.uniqid('', true); - mkdir($this->webDir, 0777, true); - mkdir($this->buildDir, 0777, true); + mkdir($this->webDir, 0o777, true); + mkdir($this->buildDir, 0o777, true); // Return a filemtime that does NOT end with '0000' so the Redis counter branch is skipped $cdnClient = $this->createStub(CdnClient::class); @@ -78,8 +78,8 @@ protected function tearDown(): void { parent::tearDown(); - (new Filesystem)->remove($this->webDir); - (new Filesystem)->remove($this->buildDir); + new Filesystem()->remove($this->webDir); + new Filesystem()->remove($this->buildDir); } public function testDumpPackageMetadata(): void diff --git a/tests/QueryFilter/AuditLog/ActorFilterTest.php b/tests/QueryFilter/AuditLog/ActorFilterTest.php index 9f42b3352..c91f2e697 100644 --- a/tests/QueryFilter/AuditLog/ActorFilterTest.php +++ b/tests/QueryFilter/AuditLog/ActorFilterTest.php @@ -14,8 +14,8 @@ use App\Entity\AuditRecord; use App\QueryFilter\AuditLog\ActorFilter; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\QueryBuilder; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; diff --git a/tests/QueryFilter/AuditLog/AuditRecordTypeFilterTest.php b/tests/QueryFilter/AuditLog/AuditRecordTypeFilterTest.php index 42507c353..de58f1a83 100644 --- a/tests/QueryFilter/AuditLog/AuditRecordTypeFilterTest.php +++ b/tests/QueryFilter/AuditLog/AuditRecordTypeFilterTest.php @@ -14,9 +14,8 @@ use App\Audit\AuditRecordType; use App\QueryFilter\AuditLog\AuditRecordTypeFilter; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\EntityManagerInterface; -use PHPUnit\Framework\Attributes\DataProvider; +use Doctrine\ORM\QueryBuilder; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; diff --git a/tests/QueryFilter/AuditLog/PackageNameFilterTest.php b/tests/QueryFilter/AuditLog/PackageNameFilterTest.php index 6502d3866..c219b6e3c 100644 --- a/tests/QueryFilter/AuditLog/PackageNameFilterTest.php +++ b/tests/QueryFilter/AuditLog/PackageNameFilterTest.php @@ -14,8 +14,8 @@ use App\Entity\AuditRecord; use App\QueryFilter\AuditLog\PackageNameFilter; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\QueryBuilder; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; diff --git a/tests/QueryFilter/AuditLog/UserFilterTest.php b/tests/QueryFilter/AuditLog/UserFilterTest.php index 142d87b61..a70da1ef7 100644 --- a/tests/QueryFilter/AuditLog/UserFilterTest.php +++ b/tests/QueryFilter/AuditLog/UserFilterTest.php @@ -14,8 +14,8 @@ use App\Entity\AuditRecord; use App\QueryFilter\AuditLog\UserFilter; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\QueryBuilder; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; diff --git a/tests/QueryFilter/AuditLog/VendorFilterTest.php b/tests/QueryFilter/AuditLog/VendorFilterTest.php index 74c83a52e..2bae29673 100644 --- a/tests/QueryFilter/AuditLog/VendorFilterTest.php +++ b/tests/QueryFilter/AuditLog/VendorFilterTest.php @@ -14,8 +14,8 @@ use App\Entity\AuditRecord; use App\QueryFilter\AuditLog\VendorFilter; -use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\QueryBuilder; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\InputBag; diff --git a/tests/Security/EmailVerifierTest.php b/tests/Security/EmailVerifierTest.php index 5ff26804d..da5268f94 100644 --- a/tests/Security/EmailVerifierTest.php +++ b/tests/Security/EmailVerifierTest.php @@ -14,11 +14,9 @@ use App\Audit\AuditRecordType; use App\Entity\AuditRecord; -use App\Entity\User; use App\Security\EmailVerifier; use App\Tests\IntegrationTestCase; use Symfony\Component\HttpFoundation\Request; -use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface; use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface; class EmailVerifierTest extends IntegrationTestCase diff --git a/tests/SecurityAdvisoryWorkerTest.php b/tests/SecurityAdvisoryWorkerTest.php index f5ebe22f1..1721ce727 100644 --- a/tests/SecurityAdvisoryWorkerTest.php +++ b/tests/SecurityAdvisoryWorkerTest.php @@ -13,8 +13,6 @@ namespace App\Tests; use App\Entity\Job; -use App\Entity\Package; -use App\Entity\PackageRepository; use App\Entity\SecurityAdvisory; use App\Entity\SecurityAdvisoryRepository; use App\EventListener\SecurityAdvisoryUpdateListener; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b1398d953..51b050823 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -15,14 +15,14 @@ require dirname(__DIR__).'/vendor/autoload.php'; if (method_exists(Dotenv::class, 'bootEnv')) { - (new Dotenv())->bootEnv(dirname(__DIR__).'/.env'); + new Dotenv()->bootEnv(dirname(__DIR__).'/.env'); } // hack for PHPUnit 11, see https://github.com/symfony/symfony/issues/53812 set_exception_handler([new Symfony\Component\ErrorHandler\ErrorHandler(), 'handleException']); if ($_SERVER['APP_DEBUG']) { - umask(0000); + umask(0o000); } /**