From 8500f7878c6b5e99d905120754408ae7fcbc86c3 Mon Sep 17 00:00:00 2001 From: Laurent Constantin Date: Sat, 7 Dec 2024 18:19:33 +0100 Subject: [PATCH] feat(rector): Enforce PHP 8.2 with rector --- public/index.php | 4 +-- rector.php | 2 ++ src/Command/BooksCheckCommand.php | 10 +++--- src/Command/BooksExtractCoverCommand.php | 2 +- src/Command/BooksScanCommand.php | 6 ++-- src/Command/CreateUserCommand.php | 7 +--- ...TranslationRetrieveFromProfilerCommand.php | 6 ++-- src/Controller/BookController.php | 2 +- src/Controller/DefaultController.php | 4 +-- src/Controller/GroupController.php | 10 ++---- .../RunCommandManuallyController.php | 4 +-- src/Controller/UserController.php | 2 +- src/Entity/Book.php | 6 ++-- src/Entity/BookInteraction.php | 2 +- src/Entity/BookmarkUser.php | 18 ++++------ src/Entity/KoboDevice.php | 2 +- src/EventListener/LanguageListener.php | 2 +- src/EventListener/LoginListener.php | 2 +- .../KoboLogRequestSubscriber.php | 4 +-- src/Form/BookFilterType.php | 6 ++-- src/Form/KoboType.php | 8 ++--- src/Form/ProfileType.php | 2 +- src/Kobo/BookDownloadInfo.php | 2 +- src/Kobo/ImageProcessor/CoverTransformer.php | 2 +- src/Kobo/Kepubify/KebpubifyCachedData.php | 4 +-- src/Kobo/Proxy/KoboProxyLogger.php | 12 +++---- src/Kobo/Proxy/KoboStoreProxy.php | 6 ++-- src/Kobo/Request/ReadingStates.php | 7 ++-- src/Kobo/Response/ReadingStateResponse.php | 2 +- src/Kobo/Response/SyncResponse.php | 33 +++++++------------ src/Kobo/SyncToken.php | 4 +-- src/Kobo/SyncTokenParser.php | 6 ++-- src/Menu/MenuBuilder.php | 2 +- src/Repository/BookInteractionRepository.php | 2 +- src/Repository/BookRepository.php | 7 ++-- src/Repository/KoboSyncedBookRepository.php | 4 +-- src/Repository/UserRepository.php | 2 +- .../PostAuthenticationTokenWithKoboDevice.php | 5 +-- src/Service/BookFileSystemManager.php | 6 ++-- src/Service/BookManager.php | 4 +-- src/Service/BookProgressionService.php | 6 ++-- src/Service/BookSearch.php | 2 +- src/Service/FilteredBookUrlGenerator.php | 2 +- src/Service/ThemeSelector.php | 2 +- src/Twig/Components/AddBookToShelf.php | 4 +-- src/Twig/Components/FieldGuesser.php | 6 ++-- src/Twig/FilteredBookUrl.php | 6 ++-- src/Twig/Runtime/ThemeExtensionRuntime.php | 2 +- src/Twig/UniqueIdExtension.php | 2 +- tests/Contraints/ArrayHasNestedKey.php | 2 +- .../AssertHasDownloadWithFormat.php | 2 +- tests/Contraints/JSONContainKeys.php | 2 +- tests/Contraints/JSONIsValidSyncResponse.php | 2 +- 53 files changed, 101 insertions(+), 160 deletions(-) diff --git a/public/index.php b/public/index.php index 9982c218..cf18ce02 100644 --- a/public/index.php +++ b/public/index.php @@ -4,6 +4,4 @@ require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; -return function (array $context) { - return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); -}; +return fn(array $context) => new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); diff --git a/rector.php b/rector.php index 5870fc2b..af5cd9cd 100644 --- a/rector.php +++ b/rector.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Rector\Config\RectorConfig; +use Rector\Set\ValueObject\LevelSetList; use Rector\Symfony\Set\SymfonySetList; use Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector; @@ -21,6 +22,7 @@ codeQuality: true ) ->withSets([ + LevelSetList::UP_TO_PHP_82, SymfonySetList::SYMFONY_64, SymfonySetList::SYMFONY_CODE_QUALITY, SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION, diff --git a/src/Command/BooksCheckCommand.php b/src/Command/BooksCheckCommand.php index 8f36a764..e0a7703e 100644 --- a/src/Command/BooksCheckCommand.php +++ b/src/Command/BooksCheckCommand.php @@ -21,10 +21,10 @@ class BooksCheckCommand extends Command { public function __construct( - private BookFileSystemManagerInterface $fileSystemManager, - private BookRepository $bookRepository, - private RouterInterface $router, - private BookProgressionService $bookProgressionService, + private readonly BookFileSystemManagerInterface $fileSystemManager, + private readonly BookRepository $bookRepository, + private readonly RouterInterface $router, + private readonly BookProgressionService $bookProgressionService, ) { parent::__construct(); } @@ -61,7 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int try { $file = $this->fileSystemManager->getBookFile($book); - } catch (\Exception $e) { + } catch (\Exception) { $io->writeln(''); $io->writeln('Book not found: '.$book->getBookPath().'/'.$book->getBookFilename()); $io->writeln('Book not found: '.$this->router->generate('app_book', ['book' => $book->getId(), 'slug' => $book->getSlug()])); diff --git a/src/Command/BooksExtractCoverCommand.php b/src/Command/BooksExtractCoverCommand.php index 33aad16e..3f6a315c 100644 --- a/src/Command/BooksExtractCoverCommand.php +++ b/src/Command/BooksExtractCoverCommand.php @@ -20,7 +20,7 @@ )] class BooksExtractCoverCommand extends Command { - public function __construct(private BookFileSystemManagerInterface $fileSystemManager, private BookRepository $bookRepository, private EntityManagerInterface $entityManager) + public function __construct(private readonly BookFileSystemManagerInterface $fileSystemManager, private readonly BookRepository $bookRepository, private readonly EntityManagerInterface $entityManager) { parent::__construct(); } diff --git a/src/Command/BooksScanCommand.php b/src/Command/BooksScanCommand.php index 454e961a..0e66d0fa 100644 --- a/src/Command/BooksScanCommand.php +++ b/src/Command/BooksScanCommand.php @@ -19,9 +19,9 @@ class BooksScanCommand extends Command { public function __construct( - private EntityManagerInterface $entityManager, - private BookManager $bookManager, - private BookFileSystemManagerInterface $fileSystemManager, + private readonly EntityManagerInterface $entityManager, + private readonly BookManager $bookManager, + private readonly BookFileSystemManagerInterface $fileSystemManager, ) { parent::__construct(); } diff --git a/src/Command/CreateUserCommand.php b/src/Command/CreateUserCommand.php index e3b73055..9bdcb4f5 100644 --- a/src/Command/CreateUserCommand.php +++ b/src/Command/CreateUserCommand.php @@ -18,14 +18,9 @@ )] class CreateUserCommand extends Command { - private UserPasswordHasherInterface $passwordHasher; - private UserRepository $userRepository; - - public function __construct(UserPasswordHasherInterface $passwordHasher, UserRepository $userRepository) + public function __construct(private readonly UserPasswordHasherInterface $passwordHasher, private readonly UserRepository $userRepository) { parent::__construct(); - $this->passwordHasher = $passwordHasher; - $this->userRepository = $userRepository; } protected function configure(): void diff --git a/src/Command/TranslationRetrieveFromProfilerCommand.php b/src/Command/TranslationRetrieveFromProfilerCommand.php index cbd7f883..bbbafe16 100644 --- a/src/Command/TranslationRetrieveFromProfilerCommand.php +++ b/src/Command/TranslationRetrieveFromProfilerCommand.php @@ -22,7 +22,7 @@ )] class TranslationRetrieveFromProfilerCommand extends Command { - public function __construct(private ?Profiler $profiler, private KernelInterface $kernel) + public function __construct(private readonly ?Profiler $profiler, private readonly KernelInterface $kernel) { parent::__construct(); } @@ -60,9 +60,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int continue; } - $filtered_values = array_filter($raw_values, function ($value) { - return $value['state'] !== 0; - }); + $filtered_values = array_filter($raw_values, fn ($value) => $value['state'] !== 0); $grouped = self::groupBy($filtered_values, 'domain'); diff --git a/src/Controller/BookController.php b/src/Controller/BookController.php index 6a0e3cc8..8a228539 100644 --- a/src/Controller/BookController.php +++ b/src/Controller/BookController.php @@ -60,7 +60,7 @@ public function index(Book $book, string $slug, BookRepository $bookRepository, if ($index === 0.0 || floor($index ?? 0.0) !== $index) { $index = '?'; } - $serie[$index] = $serie[$index] ?? []; + $serie[$index] ??= []; $serie[$index][] = $bookInSerie; } $keys = array_filter(array_keys($serie), static fn ($key) => is_numeric($key)); diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index cb684d5f..0d2f6209 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -109,8 +109,8 @@ public function allbooks(Request $request, BookRepository $bookRepository, Filte #[Route('/timeline/{type?}/{year?}', name: 'app_timeline', requirements: ['page' => '\d+'])] public function timeline(?string $type, ?string $year, BookRepository $bookRepository, FilteredBookUrlGenerator $filteredBookUrlGenerator, PaginatorInterface $paginator, int $page = 1): Response { - $redirectType = $type === null ? 'all' : $type; - $redirectYear = $year === null ? date('Y') : $year; + $redirectType = $type ?? 'all'; + $redirectYear = $year ?? date('Y'); if ($redirectYear !== $year || $redirectType !== $type) { return $this->redirectToRoute('app_timeline', ['type' => $redirectType, 'year' => $redirectYear]); } diff --git a/src/Controller/GroupController.php b/src/Controller/GroupController.php index 859ff94c..25cb5809 100644 --- a/src/Controller/GroupController.php +++ b/src/Controller/GroupController.php @@ -11,7 +11,7 @@ #[Route('/groups')] class GroupController extends AbstractController { - public function __construct(private BookRepository $bookRepository) + public function __construct(private readonly BookRepository $bookRepository) { } @@ -48,13 +48,9 @@ public function groups(Request $request, string $type, string $letter = 'a'): Re } if ($search !== '') { - $group = array_filter($group, static function ($item) use ($search) { - return str_contains(strtolower($item['item']), strtolower($search)); - }); + $group = array_filter($group, static fn ($item) => str_contains(strtolower((string) $item['item']), strtolower($search))); } else { - $group = array_filter($group, static function ($item) use ($letter) { - return str_starts_with(strtolower($item['item']), $letter); - }); + $group = array_filter($group, static fn ($item) => str_starts_with(strtolower((string) $item['item']), $letter)); } return $this->render('group/index.html.twig', [ diff --git a/src/Controller/RunCommandManuallyController.php b/src/Controller/RunCommandManuallyController.php index af79793c..5be916c4 100644 --- a/src/Controller/RunCommandManuallyController.php +++ b/src/Controller/RunCommandManuallyController.php @@ -26,9 +26,7 @@ public function index(): Response #[Route('/admin/commands/run/{name}', name: 'run_command')] public function run(string $name): Response { - $commands = array_filter($this->getCommands(), function (array $command) use ($name) { - return $command['action'] == $name; - }); + $commands = array_filter($this->getCommands(), fn (array $command) => $command['action'] == $name); if (count($commands) < 1) { throw $this->createNotFoundException(sprintf('Command "%s" does not exist.', $name)); } diff --git a/src/Controller/UserController.php b/src/Controller/UserController.php index 1795d16d..75d13c34 100644 --- a/src/Controller/UserController.php +++ b/src/Controller/UserController.php @@ -18,7 +18,7 @@ #[Route('/user')] class UserController extends AbstractController { - public function __construct(private UserPasswordHasherInterface $passwordHasher) + public function __construct(private readonly UserPasswordHasherInterface $passwordHasher) { } diff --git a/src/Entity/Book.php b/src/Entity/Book.php index 865e5a0d..cfbc84ff 100644 --- a/src/Entity/Book.php +++ b/src/Entity/Book.php @@ -41,7 +41,7 @@ class Book #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)] #[Gedmo\Timestampable(on: 'update')] - private ?\DateTimeInterface $updated; + private ?\DateTimeInterface $updated = null; #[ORM\Column(length: 255, nullable: true)] private ?string $imagePath = null; @@ -320,9 +320,7 @@ public function setPublishDate(?\DateTimeInterface $publishDate): static */ public function getAuthors(): array { - return array_map(static function ($item) { - return ucwords(strtolower($item), self::UCWORDS_SEPARATORS); - }, $this->authors); + return array_map(static fn ($item) => ucwords(strtolower($item), self::UCWORDS_SEPARATORS), $this->authors); } /** diff --git a/src/Entity/BookInteraction.php b/src/Entity/BookInteraction.php index 1e1e161a..347b13a0 100644 --- a/src/Entity/BookInteraction.php +++ b/src/Entity/BookInteraction.php @@ -41,7 +41,7 @@ class BookInteraction #[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true, options: ['default' => '2024-01-12 00:00:00'])] #[Gedmo\Timestampable(on: 'update')] - private ?\DateTimeImmutable $updated; + private ?\DateTimeImmutable $updated = null; #[ORM\Column] private bool $hidden = false; diff --git a/src/Entity/BookmarkUser.php b/src/Entity/BookmarkUser.php index 978fb095..a77438af 100644 --- a/src/Entity/BookmarkUser.php +++ b/src/Entity/BookmarkUser.php @@ -30,22 +30,16 @@ class BookmarkUser #[ORM\Column(length: 255, nullable: true)] private ?string $locationSource = null; - #[ORM\ManyToOne(inversedBy: 'bookmarkUsers')] - #[ORM\JoinColumn(nullable: false)] - private ?User $user; - - #[ORM\ManyToOne(inversedBy: 'bookmarkUsers')] - #[ORM\JoinColumn(nullable: false)] - private ?Book $book; - #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)] #[Gedmo\Timestampable(on: 'update')] - private ?\DateTimeInterface $updated; + private ?\DateTimeInterface $updated = null; - public function __construct(?Book $book, ?User $user) + public function __construct(#[ORM\ManyToOne(inversedBy: 'bookmarkUsers')] + #[ORM\JoinColumn(nullable: false)] + private ?Book $book, #[ORM\ManyToOne(inversedBy: 'bookmarkUsers')] + #[ORM\JoinColumn(nullable: false)] + private ?User $user) { - $this->book = $book; - $this->user = $user; } public function getId(): ?int diff --git a/src/Entity/KoboDevice.php b/src/Entity/KoboDevice.php index 2beda821..a79c5282 100644 --- a/src/Entity/KoboDevice.php +++ b/src/Entity/KoboDevice.php @@ -29,7 +29,7 @@ class KoboDevice #[Assert\NotBlank(allowNull: false)] #[ORM\Column(length: 255, nullable: true)] - private ?string $name; + private ?string $name = null; #[ORM\ManyToOne(inversedBy: 'kobos')] #[ORM\JoinColumn(nullable: false)] diff --git a/src/EventListener/LanguageListener.php b/src/EventListener/LanguageListener.php index 54a7dd79..af6f2802 100644 --- a/src/EventListener/LanguageListener.php +++ b/src/EventListener/LanguageListener.php @@ -11,7 +11,7 @@ final class LanguageListener { - public function __construct(private RequestStack $requestStack, private Security $security) + public function __construct(private readonly RequestStack $requestStack, private readonly Security $security) { } diff --git a/src/EventListener/LoginListener.php b/src/EventListener/LoginListener.php index 0ab0f125..25104c4f 100644 --- a/src/EventListener/LoginListener.php +++ b/src/EventListener/LoginListener.php @@ -13,7 +13,7 @@ final class LoginListener { - public function __construct(private EntityManagerInterface $entityManager, private RequestStack $requestStack, private Security $security) + public function __construct(private readonly EntityManagerInterface $entityManager, private readonly RequestStack $requestStack, private readonly Security $security) { } diff --git a/src/EventSubscriber/KoboLogRequestSubscriber.php b/src/EventSubscriber/KoboLogRequestSubscriber.php index 6fdf8b3e..81ed7918 100644 --- a/src/EventSubscriber/KoboLogRequestSubscriber.php +++ b/src/EventSubscriber/KoboLogRequestSubscriber.php @@ -29,7 +29,7 @@ public function onKernelResponse(ResponseEvent $event): void try { $content = json_decode($content, true, 512, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + } catch (\JsonException) { $content = $event->getResponse()->getContent(); } @@ -53,7 +53,7 @@ public function onKernelController(ControllerEvent $event): void try { $content = json_decode($content, true, 512, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + } catch (\JsonException) { $content = $event->getRequest()->getContent(); } diff --git a/src/Form/BookFilterType.php b/src/Form/BookFilterType.php index 49076687..bc9fe7e0 100644 --- a/src/Form/BookFilterType.php +++ b/src/Form/BookFilterType.php @@ -20,7 +20,7 @@ class BookFilterType extends AbstractType { public const AUTOCOMPLETE_DELIMITER = '🪓'; - public function __construct(private RouterInterface $router) + public function __construct(private readonly RouterInterface $router) { } @@ -348,9 +348,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $direction = 'ASC'; if ($orderByValue === null) { $params = $qb->getParameters()->toArray(); - $params = array_filter($params, static function ($param) { - return $param->getName() === 'serie0'; - }); + $params = array_filter($params, static fn ($param) => $param->getName() === 'serie0'); if ($params !== []) { $orderByValue = 'serieIndex'; } else { diff --git a/src/Form/KoboType.php b/src/Form/KoboType.php index f0c10b70..6cac7479 100644 --- a/src/Form/KoboType.php +++ b/src/Form/KoboType.php @@ -48,11 +48,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $builder->add('shelves', EntityType::class, [ 'label' => 'Sync with Shelves', 'class' => Shelf::class, - 'query_builder' => function (EntityRepository $er): QueryBuilder { - return $er->createQueryBuilder('u') - ->setParameter('user', $this->security->getUser()) - ->andWhere('u.user = :user'); - }, + 'query_builder' => fn (EntityRepository $er): QueryBuilder => $er->createQueryBuilder('u') + ->setParameter('user', $this->security->getUser()) + ->andWhere('u.user = :user'), 'choice_label' => 'name', 'multiple' => true, 'expanded' => true, diff --git a/src/Form/ProfileType.php b/src/Form/ProfileType.php index 1a2331a5..77a095f6 100644 --- a/src/Form/ProfileType.php +++ b/src/Form/ProfileType.php @@ -14,7 +14,7 @@ class ProfileType extends AbstractType { - public function __construct(private RouterInterface $router) + public function __construct(private readonly RouterInterface $router) { } diff --git a/src/Kobo/BookDownloadInfo.php b/src/Kobo/BookDownloadInfo.php index af6eedab..327e9736 100644 --- a/src/Kobo/BookDownloadInfo.php +++ b/src/Kobo/BookDownloadInfo.php @@ -4,7 +4,7 @@ class BookDownloadInfo { - public function __construct(private int $size, private string $url) + public function __construct(private readonly int $size, private readonly string $url) { } diff --git a/src/Kobo/ImageProcessor/CoverTransformer.php b/src/Kobo/ImageProcessor/CoverTransformer.php index 8cbb7836..e6ec4599 100644 --- a/src/Kobo/ImageProcessor/CoverTransformer.php +++ b/src/Kobo/ImageProcessor/CoverTransformer.php @@ -50,7 +50,7 @@ public function streamFile(string $coverPath, int $maxWidth, int $maxHeight, str return; } - list($originalWidth, $originalHeight) = $sizes; + [$originalWidth, $originalHeight] = $sizes; $aspectRatio = $originalWidth / max(1, $originalHeight); diff --git a/src/Kobo/Kepubify/KebpubifyCachedData.php b/src/Kobo/Kepubify/KebpubifyCachedData.php index 97d529aa..60c572af 100644 --- a/src/Kobo/Kepubify/KebpubifyCachedData.php +++ b/src/Kobo/Kepubify/KebpubifyCachedData.php @@ -4,8 +4,8 @@ class KebpubifyCachedData implements \JsonSerializable { - private string $content; - private int $size; + private readonly string $content; + private readonly int $size; public function __construct(string $filename) { diff --git a/src/Kobo/Proxy/KoboProxyLogger.php b/src/Kobo/Proxy/KoboProxyLogger.php index 25b8b402..33210b23 100644 --- a/src/Kobo/Proxy/KoboProxyLogger.php +++ b/src/Kobo/Proxy/KoboProxyLogger.php @@ -23,12 +23,10 @@ public function __construct( */ public function __invoke(callable $handler): \Closure { - return function ($request, array $options) use ($handler) { - return $handler($request, $options)->then( - $this->onSuccess($request), - $this->onFailure($request) - ); - }; + return fn ($request, array $options) => $handler($request, $options)->then( + $this->onSuccess($request), + $this->onFailure($request) + ); } /** @@ -59,7 +57,7 @@ private function log(RequestInterface $request, ?ResponseInterface $response = n { try { $requestContent = json_decode($request->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + } catch (\JsonException) { $requestContent = $request->getBody()->getContents(); } $responseContent = $response?->getBody()->getContents(); diff --git a/src/Kobo/Proxy/KoboStoreProxy.php b/src/Kobo/Proxy/KoboStoreProxy.php index 1eb123cd..cd08f43b 100644 --- a/src/Kobo/Proxy/KoboStoreProxy.php +++ b/src/Kobo/Proxy/KoboStoreProxy.php @@ -119,7 +119,7 @@ private function transformUrl(ServerRequestInterface $psrRequest, string $hostna { $host = parse_url($hostnameOrUrl, PHP_URL_HOST); $host = $host === false ? $hostnameOrUrl : $host; - $host = $host ?? $hostnameOrUrl; + $host ??= $hostnameOrUrl; $path = $this->tokenExtractor->getOriginalPath($psrRequest, $psrRequest->getUri()->getPath()); return $psrRequest->getUri()->withHost($host)->withPath($path); @@ -149,9 +149,7 @@ public function proxyAsync(Request $request, bool $streamAllowed): PromiseInterf 'http_errors' => false, 'connect_timeout' => 5, 'stream' => $streamAllowed, - ])->then(function (ResponseInterface $response) { - return $this->cleanupPsrResponse($response); - }); + ])->then(fn (ResponseInterface $response) => $this->cleanupPsrResponse($response)); } private function convertRequest(Request $request, string $hostname): RequestInterface diff --git a/src/Kobo/Request/ReadingStates.php b/src/Kobo/Request/ReadingStates.php index 8f30961c..697335ff 100644 --- a/src/Kobo/Request/ReadingStates.php +++ b/src/Kobo/Request/ReadingStates.php @@ -5,12 +5,9 @@ class ReadingStates { /** - * @param array $readingState + * @param array $readingStates */ - public function __construct(array $readingState = []) + public function __construct(public array $readingStates = []) { - $this->readingStates = $readingState; } - /** @var array */ - public array $readingStates = []; } diff --git a/src/Kobo/Response/ReadingStateResponse.php b/src/Kobo/Response/ReadingStateResponse.php index 846311c7..effeacfb 100644 --- a/src/Kobo/Response/ReadingStateResponse.php +++ b/src/Kobo/Response/ReadingStateResponse.php @@ -10,7 +10,7 @@ use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; use Symfony\Component\Serializer\SerializerInterface; -class ReadingStateResponse +class ReadingStateResponse implements \Stringable { public function __construct( protected BookProgressionService $bookProgressionService, diff --git a/src/Kobo/Response/SyncResponse.php b/src/Kobo/Response/SyncResponse.php index 7d5091a0..a8688804 100644 --- a/src/Kobo/Response/SyncResponse.php +++ b/src/Kobo/Response/SyncResponse.php @@ -33,7 +33,7 @@ class SyncResponse public const READING_STATUS_UNREAD = 'ReadyToRead'; public const READING_STATUS_FINISHED = 'Finished'; public const READING_STATUS_IN_PROGRESS = 'Reading'; - private SyncResponseHelper $helper; + private readonly SyncResponseHelper $helper; /** * @var RemoteItems @@ -137,9 +137,7 @@ public function createReadingState(Book $book): array */ private function getChangedEntitlement(): array { - $books = array_filter($this->books, function (Book $book) { - return $this->helper->isChangedEntitlement($book, $this->syncToken); - }); + $books = array_filter($this->books, fn (Book $book) => $this->helper->isChangedEntitlement($book, $this->syncToken)); return array_map(function (Book $book) { $response = new \stdClass(); @@ -154,10 +152,9 @@ private function getChangedEntitlement(): array */ private function getNewEntitlement(): array { - $books = array_filter($this->books, function (Book $book) { + $books = array_filter($this->books, fn (Book $book) => // This book has never been synced before - return $this->helper->isNewEntitlement($book, $this->syncToken); - }); + $this->helper->isNewEntitlement($book, $this->syncToken)); return array_map(function (Book $book) { $response = new \stdClass(); @@ -173,9 +170,7 @@ private function getNewEntitlement(): array */ private function getNewTags(): array { - $shelves = array_filter($this->shelves, function (Shelf $shelf) { - return $this->helper->isNewTag($shelf, $this->syncToken); - }); + $shelves = array_filter($this->shelves, fn (Shelf $shelf) => $this->helper->isNewTag($shelf, $this->syncToken)); return array_map(function (Shelf $shelf) { $response = new \stdClass(); @@ -191,9 +186,7 @@ private function getNewTags(): array */ private function getChangedTag(): array { - $shelves = array_filter($this->shelves, function (Shelf $shelf) { - return $this->helper->isChangedTag($shelf, $this->syncToken); - }); + $shelves = array_filter($this->shelves, fn (Shelf $shelf) => $this->helper->isChangedTag($shelf, $this->syncToken)); return array_map(function (Shelf $shelf) { $response = new \stdClass(); @@ -212,12 +205,10 @@ private function createBookTagFromShelf(Shelf $shelf): array 'Tag' => [ 'Created' => $this->syncToken->maxLastCreated($shelf->getCreated()), 'Id' => $shelf->getUuid(), - 'Items' => array_map(function (Book $book) { - return [ - 'RevisionId' => $book->getUuid(), - 'Type' => 'ProductRevisionTagItem', - ]; - }, $this->books), + 'Items' => array_map(fn (Book $book) => [ + 'RevisionId' => $book->getUuid(), + 'Type' => 'ProductRevisionTagItem', + ], $this->books), 'LastModified' => $this->syncToken->maxLastModified($shelf->getUpdated()), 'Name' => $shelf->getName(), 'Type' => 'UserTag', @@ -242,9 +233,7 @@ private function createBookEntitlement(Book $book): array */ private function getChangedReadingState(): array { - $books = array_filter($this->books, function (Book $book) { - return $this->helper->isChangedReadingState($book, $this->koboDevice, $this->syncToken); - }); + $books = array_filter($this->books, fn (Book $book) => $this->helper->isChangedReadingState($book, $this->koboDevice, $this->syncToken)); return array_map(function (Book $book) { $response = new \stdClass(); diff --git a/src/Kobo/SyncToken.php b/src/Kobo/SyncToken.php index 3a0a7a31..1fe7f0df 100644 --- a/src/Kobo/SyncToken.php +++ b/src/Kobo/SyncToken.php @@ -37,9 +37,7 @@ public function getFilterResolver(): OptionsResolver return null; } }); - $resolver->setNormalizer('PrioritizeRecentReads', function (Options $options, string|bool $value) { - return in_array(strtolower((string) $value), ['true', '1', 'yes'], true); - }); + $resolver->setNormalizer('PrioritizeRecentReads', fn (Options $options, string|bool $value) => in_array(strtolower((string) $value), ['true', '1', 'yes'], true)); return $resolver; } diff --git a/src/Kobo/SyncTokenParser.php b/src/Kobo/SyncTokenParser.php index 2c7e5a3f..e2fc4abc 100644 --- a/src/Kobo/SyncTokenParser.php +++ b/src/Kobo/SyncTokenParser.php @@ -39,7 +39,7 @@ private function timeStampStringToDate(?string $timeStamp): ?\DateTimeInterface } try { return new \DateTimeImmutable('@'.$timeStamp); - } catch (\Exception $e) { + } catch (\Exception) { return null; } } @@ -64,9 +64,7 @@ public function decodeFiltersFromGetParameters(Request $request, SyncToken $sync $keysToKeepLowercase = array_map('strtolower', $resolver->getDefinedOptions()); $params = $request->query->all(); - $options = array_filter($params, function (string $key) use ($keysToKeepLowercase) { - return in_array(strtolower($key), $keysToKeepLowercase, true); - }, ARRAY_FILTER_USE_KEY); + $options = array_filter($params, fn (string $key) => in_array(strtolower($key), $keysToKeepLowercase, true), ARRAY_FILTER_USE_KEY); $syncToken->filters = $resolver->resolve($options); } catch (\Throwable $e) { throw new BadRequestHttpException($e->getMessage(), $e); diff --git a/src/Menu/MenuBuilder.php b/src/Menu/MenuBuilder.php index 85207c4d..fe7a0712 100644 --- a/src/Menu/MenuBuilder.php +++ b/src/Menu/MenuBuilder.php @@ -20,7 +20,7 @@ final class MenuBuilder /** * Add any other dependency you need... */ - public function __construct(private readonly FactoryInterface $factory, private readonly Security $security, private FilteredBookUrlGenerator $filteredBookUrlGenerator, private RequestStack $requestStack) + public function __construct(private readonly FactoryInterface $factory, private readonly Security $security, private readonly FilteredBookUrlGenerator $filteredBookUrlGenerator, private readonly RequestStack $requestStack) { } diff --git a/src/Repository/BookInteractionRepository.php b/src/Repository/BookInteractionRepository.php index 69d04c68..22a61d73 100644 --- a/src/Repository/BookInteractionRepository.php +++ b/src/Repository/BookInteractionRepository.php @@ -17,7 +17,7 @@ */ class BookInteractionRepository extends ServiceEntityRepository { - public function __construct(ManagerRegistry $registry, private Security $security) + public function __construct(ManagerRegistry $registry, private readonly Security $security) { parent::__construct($registry, BookInteraction::class); } diff --git a/src/Repository/BookRepository.php b/src/Repository/BookRepository.php index a34dc180..678c16ad 100644 --- a/src/Repository/BookRepository.php +++ b/src/Repository/BookRepository.php @@ -18,14 +18,11 @@ */ class BookRepository extends ServiceEntityRepository { - private Security $security; - public function __construct( ManagerRegistry $registry, - Security $security, + private readonly Security $security, ) { parent::__construct($registry, Book::class); - $this->security = $security; } public function getAllBooksQueryBuilder(): QueryBuilder @@ -336,7 +333,7 @@ private function convertResults(mixed $intermediateResults): array $results = []; foreach ($intermediateResults as $result) { foreach ($result['item'] ?? [] as $item) { - $key = ucwords(strtolower($item), Book::UCWORDS_SEPARATORS); + $key = ucwords(strtolower((string) $item), Book::UCWORDS_SEPARATORS); if (!array_key_exists($key, $results)) { $results[$key] = [ 'item' => $key, diff --git a/src/Repository/KoboSyncedBookRepository.php b/src/Repository/KoboSyncedBookRepository.php index 2be4ab7d..567f732f 100644 --- a/src/Repository/KoboSyncedBookRepository.php +++ b/src/Repository/KoboSyncedBookRepository.php @@ -58,9 +58,7 @@ public function updateSyncedBooks(KoboDevice $koboDevice, array $books, SyncToke ->from(Book::class, 'book') ->select('book') ->where($qb->expr()->in('book.id', ':booksIds')) - ->setParameter('booksIds', array_map(function (Book $book) { - return $book->getId(); - }, $books)); + ->setParameter('booksIds', array_map(fn (Book $book) => $book->getId(), $books)); if ($updatedBooks !== []) { $qb->andWhere($qb->expr()->notIn('book.id', ':excludedIds')) diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php index 70cb66da..f99b40a3 100644 --- a/src/Repository/UserRepository.php +++ b/src/Repository/UserRepository.php @@ -39,7 +39,7 @@ public function remove(User $entity, bool $flush = false): void public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void { if (!$user instanceof User) { - throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user))); + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class)); } $user->setPassword($newHashedPassword); diff --git a/src/Security/Token/PostAuthenticationTokenWithKoboDevice.php b/src/Security/Token/PostAuthenticationTokenWithKoboDevice.php index 587c9d84..66f9bf30 100644 --- a/src/Security/Token/PostAuthenticationTokenWithKoboDevice.php +++ b/src/Security/Token/PostAuthenticationTokenWithKoboDevice.php @@ -8,12 +8,9 @@ class PostAuthenticationTokenWithKoboDevice extends PostAuthenticationToken { - private KoboDevice $device; - - public function __construct(KoboDevice $device, UserInterface $user, string $firewallName, array $roles) + public function __construct(private readonly KoboDevice $device, UserInterface $user, string $firewallName, array $roles) { parent::__construct($user, $firewallName, $roles); - $this->device = $device; } public function getKoboDevice(): KoboDevice diff --git a/src/Service/BookFileSystemManager.php b/src/Service/BookFileSystemManager.php index 0f2373e7..24ce2419 100644 --- a/src/Service/BookFileSystemManager.php +++ b/src/Service/BookFileSystemManager.php @@ -51,16 +51,14 @@ public function getAllBooksFiles(bool $onlyConsumeDirectory = false): \Iterator { try { $finder = new Finder(); - $finder->files()->name(self::ALLOWED_FILE_EXTENSIONS)->sort(function (\SplFileInfo $a, \SplFileInfo $b): int { - return strcmp($a->getRealPath(), $b->getRealPath()); - }); + $finder->files()->name(self::ALLOWED_FILE_EXTENSIONS)->sort(fn (\SplFileInfo $a, \SplFileInfo $b): int => strcmp($a->getRealPath(), $b->getRealPath())); if ($onlyConsumeDirectory) { $finder->in($this->getBooksDirectory().'/consume'); } else { $finder->in($this->getBooksDirectory()); } $iterator = $finder->getIterator(); - } catch (\Exception $e) { + } catch (\Exception) { $iterator = new \ArrayIterator(); } diff --git a/src/Service/BookManager.php b/src/Service/BookManager.php index 1c8c85b7..13c5ee0c 100644 --- a/src/Service/BookManager.php +++ b/src/Service/BookManager.php @@ -20,7 +20,7 @@ */ class BookManager { - public function __construct(private BookFileSystemManagerInterface $fileSystemManager, private EntityManagerInterface $entityManager, private BookRepository $bookRepository) + public function __construct(private readonly BookFileSystemManagerInterface $fileSystemManager, private readonly EntityManagerInterface $entityManager, private readonly BookRepository $bookRepository) { } @@ -99,7 +99,7 @@ public function extractEbookMetadata(\SplFileInfo $file): array if (!$ebook instanceof Ebook) { throw new \RuntimeException('Could not read ebook'); } - } catch (\Throwable $e) { + } catch (\Throwable) { $ebook = null; return [ diff --git a/src/Service/BookProgressionService.php b/src/Service/BookProgressionService.php index 9027fdca..595b6bf0 100644 --- a/src/Service/BookProgressionService.php +++ b/src/Service/BookProgressionService.php @@ -12,9 +12,9 @@ class BookProgressionService { public function __construct( - private BookFileSystemManagerInterface $fileSystemManager, - private LoggerInterface $logger, - private EntityManagerInterface $em, + private readonly BookFileSystemManagerInterface $fileSystemManager, + private readonly LoggerInterface $logger, + private readonly EntityManagerInterface $em, ) { } diff --git a/src/Service/BookSearch.php b/src/Service/BookSearch.php index bfbfe844..fd63996c 100644 --- a/src/Service/BookSearch.php +++ b/src/Service/BookSearch.php @@ -11,7 +11,7 @@ */ class BookSearch { - public function __construct(private SpecificCollectionFinder $autocompleteBookFinder) + public function __construct(private readonly SpecificCollectionFinder $autocompleteBookFinder) { } diff --git a/src/Service/FilteredBookUrlGenerator.php b/src/Service/FilteredBookUrlGenerator.php index ec280e38..dd5bdcd5 100644 --- a/src/Service/FilteredBookUrlGenerator.php +++ b/src/Service/FilteredBookUrlGenerator.php @@ -27,7 +27,7 @@ class FilteredBookUrlGenerator 'submit' => '', ]; - public function __construct(private RequestStack $request) + public function __construct(private readonly RequestStack $request) { } diff --git a/src/Service/ThemeSelector.php b/src/Service/ThemeSelector.php index 2de25af8..7cea49a9 100644 --- a/src/Service/ThemeSelector.php +++ b/src/Service/ThemeSelector.php @@ -8,7 +8,7 @@ class ThemeSelector { public function __construct( - private Security $security, + private readonly Security $security, ) { } diff --git a/src/Twig/Components/AddBookToShelf.php b/src/Twig/Components/AddBookToShelf.php index 0e91b90a..987aae6a 100644 --- a/src/Twig/Components/AddBookToShelf.php +++ b/src/Twig/Components/AddBookToShelf.php @@ -39,9 +39,7 @@ public function __construct(EntityManagerInterface $entityManager, Security $sec $shelfRepository = $entityManager->getRepository(Shelf::class); $this->shelves = $shelfRepository->findBy(['user' => $security->getUser()]); - $this->shelves = array_filter($this->shelves, static function ($item) { - return $item->getQueryString() === null; - }); + $this->shelves = array_filter($this->shelves, static fn ($item) => $item->getQueryString() === null); } #[LiveAction] diff --git a/src/Twig/Components/FieldGuesser.php b/src/Twig/Components/FieldGuesser.php index ac02d105..a244ee91 100644 --- a/src/Twig/Components/FieldGuesser.php +++ b/src/Twig/Components/FieldGuesser.php @@ -60,7 +60,7 @@ public function acceptIndexAndRename(EntityManagerInterface $entityManager): voi public function guessSerie(): string { - $author = implode($this->book->getAuthors()); + $author = implode('', $this->book->getAuthors()); $parts = explode(' - ', $author); if (3 === count($parts)) { return $parts[1]; @@ -71,7 +71,7 @@ public function guessSerie(): string public function guessIndex(): string { - $author = implode($this->book->getAuthors()); + $author = implode('', $this->book->getAuthors()); $parts = explode(' - ', $author); if (3 === count($parts)) { return $parts[2]; @@ -89,7 +89,7 @@ public function guessIndex(): string public function guessAuthor(): string { - $author = implode($this->book->getAuthors()); + $author = implode('', $this->book->getAuthors()); $parts = explode(' - ', $author); if (3 === count($parts)) { return $parts[0]; diff --git a/src/Twig/FilteredBookUrl.php b/src/Twig/FilteredBookUrl.php index 35b7ff00..a66a6b02 100644 --- a/src/Twig/FilteredBookUrl.php +++ b/src/Twig/FilteredBookUrl.php @@ -11,15 +11,15 @@ class FilteredBookUrl extends AbstractExtension { - public function __construct(private FilteredBookUrlGenerator $filteredBookUrlGenerator, private RouterInterface $router) + public function __construct(private readonly FilteredBookUrlGenerator $filteredBookUrlGenerator, private readonly RouterInterface $router) { } public function getFunctions(): array { return [ - new TwigFunction('filter_book_url', [$this, 'filteredBookUrl']), - new TwigFunction('current_page_filters', [$this, 'currentPageParams']), + new TwigFunction('filter_book_url', $this->filteredBookUrl(...)), + new TwigFunction('current_page_filters', $this->currentPageParams(...)), ]; } diff --git a/src/Twig/Runtime/ThemeExtensionRuntime.php b/src/Twig/Runtime/ThemeExtensionRuntime.php index 5efcee75..ebfef1b0 100644 --- a/src/Twig/Runtime/ThemeExtensionRuntime.php +++ b/src/Twig/Runtime/ThemeExtensionRuntime.php @@ -7,7 +7,7 @@ class ThemeExtensionRuntime implements RuntimeExtensionInterface { - public function __construct(private ThemeSelector $themeSelector) + public function __construct(private readonly ThemeSelector $themeSelector) { } diff --git a/src/Twig/UniqueIdExtension.php b/src/Twig/UniqueIdExtension.php index 531165e2..1868be4a 100644 --- a/src/Twig/UniqueIdExtension.php +++ b/src/Twig/UniqueIdExtension.php @@ -10,7 +10,7 @@ class UniqueIdExtension extends AbstractExtension public function getFunctions(): array { return [ - new TwigFunction('unique_id', [$this, 'uniqueID']), + new TwigFunction('unique_id', $this->uniqueID(...)), ]; } diff --git a/tests/Contraints/ArrayHasNestedKey.php b/tests/Contraints/ArrayHasNestedKey.php index 4622e66a..e1154f7b 100644 --- a/tests/Contraints/ArrayHasNestedKey.php +++ b/tests/Contraints/ArrayHasNestedKey.php @@ -14,7 +14,7 @@ public function matches($other): bool { try { $this->test($other); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return false; } diff --git a/tests/Contraints/AssertHasDownloadWithFormat.php b/tests/Contraints/AssertHasDownloadWithFormat.php index c1e8bf6f..753049a7 100644 --- a/tests/Contraints/AssertHasDownloadWithFormat.php +++ b/tests/Contraints/AssertHasDownloadWithFormat.php @@ -14,7 +14,7 @@ public function matches($other): bool { try { $this->test($other); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return false; } diff --git a/tests/Contraints/JSONContainKeys.php b/tests/Contraints/JSONContainKeys.php index 02ab36c9..829c81af 100644 --- a/tests/Contraints/JSONContainKeys.php +++ b/tests/Contraints/JSONContainKeys.php @@ -14,7 +14,7 @@ public function matches($other): bool { try { $this->test($other); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return false; } diff --git a/tests/Contraints/JSONIsValidSyncResponse.php b/tests/Contraints/JSONIsValidSyncResponse.php index 39d41f18..f1ebb473 100644 --- a/tests/Contraints/JSONIsValidSyncResponse.php +++ b/tests/Contraints/JSONIsValidSyncResponse.php @@ -33,7 +33,7 @@ public function matches($other): bool { try { $this->test($other); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return false; }