From 5832482a10778f5ebce3e9f6fa1b06f5b1eda16a Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Thu, 15 Dec 2022 20:57:02 +0100 Subject: [PATCH] Remove `ContainerAwareCommand` from commands And use DI to retrieve services in commands (except for `RedisWorkerCommand` where the container is injected, hard to find a better way, at least for now). --- app/config/services.yml | 11 +++ composer.lock | 12 +-- phpstan-baseline.neon | 20 ++-- .../Command/CleanDownloadedImagesCommand.php | 22 +++-- .../Command/CleanDuplicatesCommand.php | 33 ++++--- .../CoreBundle/Command/ExportCommand.php | 27 ++++-- .../Command/GenerateUrlHashesCommand.php | 43 +++++---- .../CoreBundle/Command/InstallCommand.php | 93 ++++++++++--------- .../CoreBundle/Command/ListUserCommand.php | 17 +++- .../CoreBundle/Command/ReloadEntryCommand.php | 45 +++++---- .../CoreBundle/Command/ShowUserCommand.php | 17 +++- .../CoreBundle/Command/TagAllCommand.php | 34 ++++--- .../ImportBundle/Command/ImportCommand.php | 65 +++++++++---- .../Command/RedisWorkerCommand.php | 20 +++- 14 files changed, 290 insertions(+), 169 deletions(-) diff --git a/app/config/services.yml b/app/config/services.yml index a3f5bd7eb..1fc1b8f15 100644 --- a/app/config/services.yml +++ b/app/config/services.yml @@ -197,6 +197,17 @@ services: arguments: $baseFolder: "%kernel.project_dir%/web/assets/images" + Wallabag\CoreBundle\Command\ExportCommand: + arguments: + $projectDir: '%kernel.project_dir%' + + Wallabag\CoreBundle\Command\InstallCommand: + arguments: + $databaseDriver: '%database_driver%' + $databaseName: '%database_name%' + $defaultSettings: '%wallabag_core.default_internal_settings%' + $defaultIgnoreOriginInstanceRules: '%wallabag_core.default_ignore_origin_instance_rules%' + wallabag_core.entry.download_images.client: alias: 'httplug.client.wallabag_core.entry.download_images' diff --git a/composer.lock b/composer.lock index 1c48d1533..1535f2b50 100644 --- a/composer.lock +++ b/composer.lock @@ -7788,16 +7788,16 @@ }, { "name": "phpstan/phpdoc-parser", - "version": "1.15.0", + "version": "1.15.2", "source": { "type": "git", "url": "https://github.com/phpstan/phpdoc-parser.git", - "reference": "6ff970a7101acfe99b3048e4bbfbc094e55c5b04" + "reference": "5941477f100993652218928039d530b75a13a9ca" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/6ff970a7101acfe99b3048e4bbfbc094e55c5b04", - "reference": "6ff970a7101acfe99b3048e4bbfbc094e55c5b04", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/5941477f100993652218928039d530b75a13a9ca", + "reference": "5941477f100993652218928039d530b75a13a9ca", "shasum": "" }, "require": { @@ -7827,9 +7827,9 @@ "description": "PHPDoc parser with support for nullable, intersection and generic types", "support": { "issues": "https://github.com/phpstan/phpdoc-parser/issues", - "source": "https://github.com/phpstan/phpdoc-parser/tree/1.15.0" + "source": "https://github.com/phpstan/phpdoc-parser/tree/1.15.2" }, - "time": "2022-12-07T16:12:39+00:00" + "time": "2022-12-16T06:42:48+00:00" }, { "name": "phpzip/phpzip", diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index a718e8c04..69768400c 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -15,11 +15,6 @@ parameters: count: 3 path: src/Wallabag/ApiBundle/Controller/WallabagRestController.php - - - message: "#^Call to an undefined method Doctrine\\\\Persistence\\\\ObjectManager\\:\\:getConnection\\(\\)\\.$#" - count: 5 - path: src/Wallabag/CoreBundle/Command/InstallCommand.php - - message: "#^Call to an undefined method Wallabag\\\\CoreBundle\\\\Entity\\\\RuleInterface\\:\\:getConfig\\(\\)\\.$#" count: 1 @@ -40,11 +35,6 @@ parameters: count: 10 path: src/Wallabag/CoreBundle/Form/Type/EntryFilterType.php - - - message: "#^Call to an undefined method Doctrine\\\\Persistence\\\\ObjectManager\\:\\:getConnection\\(\\)\\.$#" - count: 1 - path: src/Wallabag/ImportBundle/Command/ImportCommand.php - - message: "#^Call to an undefined method Wallabag\\\\ImportBundle\\\\Import\\\\ImportInterface\\:\\:setFilepath\\(\\)\\.$#" count: 1 @@ -84,3 +74,13 @@ parameters: message: "#^Property Tests\\\\Wallabag\\\\CoreBundle\\\\Helper\\\\RedirectTest\\:\\:\\$routerMock has unknown class PHPUnit_Framework_MockObject_MockObject as its type\\.$#" count: 1 path: tests/Wallabag/CoreBundle/Helper/RedirectTest.php + + - + message: "#^Method Symfony\\\\Contracts\\\\EventDispatcher\\\\EventDispatcherInterface\\:\\:dispatch()#" + count: 1 + path: src/Wallabag/CoreBundle/Command/InstallCommand.php + + - + message: "#^Method Symfony\\\\Contracts\\\\EventDispatcher\\\\EventDispatcherInterface\\:\\:dispatch()#" + count: 1 + path: src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php diff --git a/src/Wallabag/CoreBundle/Command/CleanDownloadedImagesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDownloadedImagesCommand.php index 90af26cb0..fe4f77a70 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDownloadedImagesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDownloadedImagesCommand.php @@ -2,7 +2,7 @@ namespace Wallabag\CoreBundle\Command; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; @@ -11,8 +11,19 @@ use Symfony\Component\Finder\Finder; use Wallabag\CoreBundle\Helper\DownloadImages; use Wallabag\CoreBundle\Repository\EntryRepository; -class CleanDownloadedImagesCommand extends ContainerAwareCommand +class CleanDownloadedImagesCommand extends Command { + private EntryRepository $entryRepository; + private DownloadImages $downloadImages; + + public function __construct(EntryRepository $entryRepository, DownloadImages $downloadImages) + { + $this->entryRepository = $entryRepository; + $this->downloadImages = $downloadImages; + + parent::__construct(); + } + protected function configure() { $this @@ -36,8 +47,7 @@ class CleanDownloadedImagesCommand extends ContainerAwareCommand $io->text('Dry run mode enabled (no images will be removed)'); } - $downloadImages = $this->getContainer()->get(DownloadImages::class); - $baseFolder = $downloadImages->getBaseFolder(); + $baseFolder = $this->downloadImages->getBaseFolder(); $io->text('Retrieve existing images'); @@ -58,12 +68,12 @@ class CleanDownloadedImagesCommand extends ContainerAwareCommand $io->text('Retrieve valid folders attached to a user'); - $entries = $this->getContainer()->get(EntryRepository::class)->findAllEntriesIdByUserId(); + $entries = $this->entryRepository->findAllEntriesIdByUserId(); // retrieve _valid_ folders from existing entries $validPaths = []; foreach ($entries as $entry) { - $path = $downloadImages->getRelativePath($entry['id']); + $path = $this->downloadImages->getRelativePath($entry['id']); if (!file_exists($baseFolder . '/' . $path)) { continue; diff --git a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php index 5af642dd8..045828235 100644 --- a/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php +++ b/src/Wallabag/CoreBundle/Command/CleanDuplicatesCommand.php @@ -4,7 +4,7 @@ namespace Wallabag\CoreBundle\Command; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NoResultException; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -14,12 +14,22 @@ use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Repository\UserRepository; -class CleanDuplicatesCommand extends ContainerAwareCommand +class CleanDuplicatesCommand extends Command { - /** @var SymfonyStyle */ - protected $io; + protected SymfonyStyle $io; + protected int $duplicates = 0; + private EntityManagerInterface $entityManager; + private EntryRepository $entryRepository; + private UserRepository $userRepository; - protected $duplicates = 0; + public function __construct(EntityManagerInterface $entityManager, EntryRepository $entryRepository, UserRepository $userRepository) + { + $this->entityManager = $entityManager; + $this->entryRepository = $entryRepository; + $this->userRepository = $userRepository; + + parent::__construct(); + } protected function configure() { @@ -52,7 +62,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand $this->io->success('Finished cleaning.'); } else { - $users = $this->getContainer()->get(UserRepository::class)->findAll(); + $users = $this->userRepository->findAll(); $this->io->text(sprintf('Cleaning through %d user accounts', \count($users))); @@ -68,10 +78,7 @@ class CleanDuplicatesCommand extends ContainerAwareCommand private function cleanDuplicates(User $user) { - $em = $this->getContainer()->get(EntityManagerInterface::class); - $repo = $this->getContainer()->get(EntryRepository::class); - - $entries = $repo->findAllEntriesIdAndUrlByUserId($user->getId()); + $entries = $this->entryRepository->findAllEntriesIdAndUrlByUserId($user->getId()); $duplicatesCount = 0; $urls = []; @@ -82,8 +89,8 @@ class CleanDuplicatesCommand extends ContainerAwareCommand if (\in_array($url, $urls, true)) { ++$duplicatesCount; - $em->remove($repo->find($entry['id'])); - $em->flush(); // Flushing at the end of the loop would require the instance not being online + $this->entityManager->remove($this->entryRepository->find($entry['id'])); + $this->entityManager->flush(); // Flushing at the end of the loop would require the instance not being online } else { $urls[] = $entry['url']; } @@ -112,6 +119,6 @@ class CleanDuplicatesCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getContainer()->get(UserRepository::class)->findOneByUserName($username); + return $this->userRepository->findOneByUserName($username); } } diff --git a/src/Wallabag/CoreBundle/Command/ExportCommand.php b/src/Wallabag/CoreBundle/Command/ExportCommand.php index a24a7ce2e..a11892ecd 100644 --- a/src/Wallabag/CoreBundle/Command/ExportCommand.php +++ b/src/Wallabag/CoreBundle/Command/ExportCommand.php @@ -3,7 +3,7 @@ namespace Wallabag\CoreBundle\Command; use Doctrine\ORM\NoResultException; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -12,8 +12,23 @@ use Wallabag\CoreBundle\Helper\EntriesExport; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\UserBundle\Repository\UserRepository; -class ExportCommand extends ContainerAwareCommand +class ExportCommand extends Command { + private EntryRepository $entryRepository; + private UserRepository $userRepository; + private EntriesExport $entriesExport; + private string $projectDir; + + public function __construct(EntryRepository $entryRepository, UserRepository $userRepository, EntriesExport $entriesExport, string $projectDir) + { + $this->entryRepository = $entryRepository; + $this->userRepository = $userRepository; + $this->entriesExport = $entriesExport; + $this->projectDir = $projectDir; + + parent::__construct(); + } + protected function configure() { $this @@ -38,14 +53,14 @@ class ExportCommand extends ContainerAwareCommand $io = new SymfonyStyle($input, $output); try { - $user = $this->getContainer()->get(UserRepository::class)->findOneByUserName($input->getArgument('username')); + $user = $this->userRepository->findOneByUserName($input->getArgument('username')); } catch (NoResultException $e) { $io->error(sprintf('User "%s" not found.', $input->getArgument('username'))); return 1; } - $entries = $this->getContainer()->get(EntryRepository::class) + $entries = $this->entryRepository ->getBuilderForAllByUser($user->getId()) ->getQuery() ->getResult(); @@ -55,11 +70,11 @@ class ExportCommand extends ContainerAwareCommand $filePath = $input->getArgument('filepath'); if (!$filePath) { - $filePath = $this->getContainer()->getParameter('kernel.project_dir') . '/' . sprintf('%s-export.json', $user->getUsername()); + $filePath = $this->projectDir . '/' . sprintf('%s-export.json', $user->getUsername()); } try { - $data = $this->getContainer()->get(EntriesExport::class) + $data = $this->entriesExport ->setEntries($entries) ->updateTitle('All') ->updateAuthor('All') diff --git a/src/Wallabag/CoreBundle/Command/GenerateUrlHashesCommand.php b/src/Wallabag/CoreBundle/Command/GenerateUrlHashesCommand.php index 4637b4126..c5980d3fd 100644 --- a/src/Wallabag/CoreBundle/Command/GenerateUrlHashesCommand.php +++ b/src/Wallabag/CoreBundle/Command/GenerateUrlHashesCommand.php @@ -4,19 +4,30 @@ namespace Wallabag\CoreBundle\Command; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NoResultException; -use Doctrine\Persistence\ManagerRegistry; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Helper\UrlHasher; +use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\UserBundle\Entity\User; +use Wallabag\UserBundle\Repository\UserRepository; -class GenerateUrlHashesCommand extends ContainerAwareCommand +class GenerateUrlHashesCommand extends Command { - /** @var OutputInterface */ - protected $output; + protected OutputInterface $output; + private EntityManagerInterface $entityManager; + private EntryRepository $entryRepository; + private UserRepository $userRepository; + + public function __construct(EntityManagerInterface $entityManager, EntryRepository $entryRepository, UserRepository $userRepository) + { + $this->entityManager = $entityManager; + $this->entryRepository = $entryRepository; + $this->userRepository = $userRepository; + + parent::__construct(); + } protected function configure() { @@ -43,7 +54,7 @@ class GenerateUrlHashesCommand extends ContainerAwareCommand return 1; } } else { - $users = $this->getContainer()->get('doctrine')->getRepository(User::class)->findAll(); + $users = $this->userRepository->findAll(); $output->writeln(sprintf('Generating hashed urls for "%d" users', \count($users))); @@ -59,23 +70,20 @@ class GenerateUrlHashesCommand extends ContainerAwareCommand private function generateHashedUrls(User $user) { - $em = $this->getContainer()->get(EntityManagerInterface::class); - $repo = $this->getContainer()->get('doctrine')->getRepository(Entry::class); - - $entries = $repo->findByEmptyHashedUrlAndUserId($user->getId()); + $entries = $this->entryRepository->findByEmptyHashedUrlAndUserId($user->getId()); $i = 1; foreach ($entries as $entry) { $entry->setHashedUrl(UrlHasher::hashUrl($entry->getUrl())); - $em->persist($entry); + $this->entityManager->persist($entry); if (0 === ($i % 20)) { - $em->flush(); + $this->entityManager->flush(); } ++$i; } - $em->flush(); + $this->entityManager->flush(); $this->output->writeln(sprintf('Generated hashed urls for user: %s', $user->getUserName())); } @@ -89,11 +97,6 @@ class GenerateUrlHashesCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getContainer()->get('doctrine')->getRepository(User::class)->findOneByUserName($username); - } - - private function getDoctrine() - { - return $this->getContainer()->get(ManagerRegistry::class); + return $this->userRepository->findOneByUserName($username); } } diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 8373fc95d..928e5aa70 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -5,11 +5,10 @@ namespace Wallabag\CoreBundle\Command; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Exception\DriverException; use Doctrine\ORM\EntityManagerInterface; -use Doctrine\Persistence\ManagerRegistry; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Model\UserManagerInterface; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -22,28 +21,37 @@ use Wallabag\CoreBundle\Entity\IgnoreOriginInstanceRule; use Wallabag\CoreBundle\Entity\InternalSetting; use Wallabag\UserBundle\Entity\User; -class InstallCommand extends ContainerAwareCommand +class InstallCommand extends Command { - /** - * @var InputInterface - */ - private $defaultInput; - - /** - * @var SymfonyStyle - */ - private $io; - - /** - * @var array - */ - private $functionExists = [ + private InputInterface $defaultInput; + private SymfonyStyle $io; + private array $functionExists = [ 'curl_exec', 'curl_multi_init', ]; - private bool $runOtherCommands = true; + private EntityManagerInterface $entityManager; + private EventDispatcherInterface $dispatcher; + private UserManagerInterface $userManager; + private string $databaseDriver; + private string $databaseName; + private array $defaultSettings; + private array $defaultIgnoreOriginInstanceRules; + + public function __construct(EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, UserManagerInterface $userManager, string $databaseDriver, string $databaseName, array $defaultSettings, array $defaultIgnoreOriginInstanceRules) + { + $this->entityManager = $entityManager; + $this->dispatcher = $dispatcher; + $this->userManager = $userManager; + $this->databaseDriver = $databaseDriver; + $this->databaseName = $databaseName; + $this->defaultSettings = $defaultSettings; + $this->defaultIgnoreOriginInstanceRules = $defaultIgnoreOriginInstanceRules; + + parent::__construct(); + } + public function disableRunOtherCommands(): void { $this->runOtherCommands = false; @@ -88,8 +96,6 @@ class InstallCommand extends ContainerAwareCommand { $this->io->section('Step 1 of 4: Checking system requirements.'); - $doctrineManager = $this->getContainer()->get(ManagerRegistry::class)->getManager(); - $rows = []; // testing if database driver exists @@ -98,26 +104,26 @@ class InstallCommand extends ContainerAwareCommand $status = 'OK!'; $help = ''; - if (!\extension_loaded($this->getContainer()->getParameter('database_driver'))) { + if (!\extension_loaded($this->databaseDriver)) { $fulfilled = false; $status = 'ERROR!'; - $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.'; + $help = 'Database driver "' . $this->databaseDriver . '" is not installed.'; } - $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help]; + $rows[] = [sprintf($label, $this->databaseDriver), $status, $help]; // testing if connection to the database can be etablished $label = 'Database connection'; $status = 'OK!'; $help = ''; - $conn = $this->getContainer()->get(ManagerRegistry::class)->getManager()->getConnection(); + $conn = $this->entityManager->getConnection(); try { $conn->connect(); } catch (\Exception $e) { if (false === strpos($e->getMessage(), 'Unknown database') - && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) { + && false === strpos($e->getMessage(), 'database "' . $this->databaseName . '" does not exist')) { $fulfilled = false; $status = 'ERROR!'; $help = 'Can\'t connect to the database: ' . $e->getMessage(); @@ -146,7 +152,7 @@ class InstallCommand extends ContainerAwareCommand // testing if PostgreSQL > 9.1 if ($conn->isConnected() && 'postgresql' === $conn->getDatabasePlatform()->getName()) { // return version should be like "PostgreSQL 9.5.4 on x86_64-apple-darwin15.6.0, compiled by Apple LLVM version 8.0.0 (clang-800.0.38), 64-bit" - $version = $doctrineManager->getConnection()->query('SELECT version();')->fetchColumn(); + $version = $conn->query('SELECT version();')->fetchColumn(); preg_match('/PostgreSQL ([0-9\.]+)/i', $version, $matches); @@ -260,10 +266,7 @@ class InstallCommand extends ContainerAwareCommand return $this; } - $em = $this->getContainer()->get(EntityManagerInterface::class); - - $userManager = $this->getContainer()->get(UserManagerInterface::class); - $user = $userManager->createUser(); + $user = $this->userManager->createUser(); \assert($user instanceof User); $user->setUsername($this->io->ask('Username', 'wallabag')); @@ -277,11 +280,10 @@ class InstallCommand extends ContainerAwareCommand $user->setEnabled(true); $user->addRole('ROLE_SUPER_ADMIN'); - $em->persist($user); + $this->entityManager->persist($user); // dispatch a created event so the associated config will be created - $event = new UserEvent($user); - $this->getContainer()->get(EventDispatcherInterface::class)->dispatch($event, FOSUserEvents::USER_CREATED); + $this->dispatcher->dispatch(new UserEvent($user), FOSUserEvents::USER_CREATED); $this->io->text('Administration successfully setup.'); @@ -291,27 +293,28 @@ class InstallCommand extends ContainerAwareCommand private function setupConfig() { $this->io->section('Step 4 of 4: Config setup.'); - $em = $this->getContainer()->get(EntityManagerInterface::class); // cleanup before insert new stuff - $em->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\InternalSetting')->execute(); - $em->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\IgnoreOriginInstanceRule')->execute(); + $this->entityManager->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\InternalSetting')->execute(); + $this->entityManager->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\IgnoreOriginInstanceRule')->execute(); - foreach ($this->getContainer()->getParameter('wallabag_core.default_internal_settings') as $setting) { + foreach ($this->defaultSettings as $setting) { $newSetting = new InternalSetting(); $newSetting->setName($setting['name']); $newSetting->setValue($setting['value']); $newSetting->setSection($setting['section']); - $em->persist($newSetting); + + $this->entityManager->persist($newSetting); } - foreach ($this->getContainer()->getParameter('wallabag_core.default_ignore_origin_instance_rules') as $ignore_origin_instance_rule) { + foreach ($this->defaultIgnoreOriginInstanceRules as $ignore_origin_instance_rule) { $newIgnoreOriginInstanceRule = new IgnoreOriginInstanceRule(); $newIgnoreOriginInstanceRule->setRule($ignore_origin_instance_rule['rule']); - $em->persist($newIgnoreOriginInstanceRule); + + $this->entityManager->persist($newIgnoreOriginInstanceRule); } - $em->flush(); + $this->entityManager->flush(); $this->io->text('Config successfully setup.'); @@ -350,7 +353,7 @@ class InstallCommand extends ContainerAwareCommand // PDO does not always close the connection after Doctrine commands. // See https://github.com/symfony/symfony/issues/11750. - $this->getContainer()->get(ManagerRegistry::class)->getManager()->getConnection()->close(); + $this->entityManager->getConnection()->close(); if (0 !== $exitCode) { $this->getApplication()->setAutoExit(true); @@ -368,7 +371,7 @@ class InstallCommand extends ContainerAwareCommand */ private function isDatabasePresent() { - $connection = $this->getContainer()->get(ManagerRegistry::class)->getManager()->getConnection(); + $connection = $this->entityManager->getConnection(); $databaseName = $connection->getDatabase(); try { @@ -389,7 +392,7 @@ class InstallCommand extends ContainerAwareCommand // custom verification for sqlite, since `getListDatabasesSQL` doesn't work for sqlite if ('sqlite' === $schemaManager->getDatabasePlatform()->getName()) { - $params = $this->getContainer()->get(Connection::class)->getParams(); + $params = $connection->getParams(); if (isset($params['path']) && file_exists($params['path'])) { return true; @@ -415,7 +418,7 @@ class InstallCommand extends ContainerAwareCommand */ private function isSchemaPresent() { - $schemaManager = $this->getContainer()->get(ManagerRegistry::class)->getManager()->getConnection()->getSchemaManager(); + $schemaManager = $this->entityManager->getConnection()->getSchemaManager(); return \count($schemaManager->listTableNames()) > 0 ? true : false; } diff --git a/src/Wallabag/CoreBundle/Command/ListUserCommand.php b/src/Wallabag/CoreBundle/Command/ListUserCommand.php index d26fba30c..f4898c48c 100644 --- a/src/Wallabag/CoreBundle/Command/ListUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ListUserCommand.php @@ -2,7 +2,7 @@ namespace Wallabag\CoreBundle\Command; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -10,8 +10,17 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Wallabag\UserBundle\Repository\UserRepository; -class ListUserCommand extends ContainerAwareCommand +class ListUserCommand extends Command { + private UserRepository $userRepository; + + public function __construct(UserRepository $userRepository) + { + $this->userRepository = $userRepository; + + parent::__construct(); + } + protected function configure() { $this @@ -27,13 +36,13 @@ class ListUserCommand extends ContainerAwareCommand { $io = new SymfonyStyle($input, $output); - $users = $this->getContainer()->get(UserRepository::class) + $users = $this->userRepository ->getQueryBuilderForSearch($input->getArgument('search')) ->setMaxResults($input->getOption('limit')) ->getQuery() ->getResult(); - $nbUsers = $this->getContainer()->get(UserRepository::class) + $nbUsers = $this->userRepository ->getSumUsers(); $rows = []; diff --git a/src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php b/src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php index 3f9fcc08c..f62a76180 100644 --- a/src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php +++ b/src/Wallabag/CoreBundle/Command/ReloadEntryCommand.php @@ -2,9 +2,9 @@ namespace Wallabag\CoreBundle\Command; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NoResultException; -use Doctrine\Persistence\ManagerRegistry; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -15,8 +15,25 @@ use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Repository\EntryRepository; use Wallabag\UserBundle\Repository\UserRepository; -class ReloadEntryCommand extends ContainerAwareCommand +class ReloadEntryCommand extends Command { + private EntryRepository $entryRepository; + private UserRepository $userRepository; + private EntityManagerInterface $entityManager; + private ContentProxy $contentProxy; + private EventDispatcherInterface $dispatcher; + + public function __construct(EntryRepository $entryRepository, UserRepository $userRepository, EntityManagerInterface $entityManager, ContentProxy $contentProxy, EventDispatcherInterface $dispatcher) + { + $this->entryRepository = $entryRepository; + $this->userRepository = $userRepository; + $this->entityManager = $entityManager; + $this->contentProxy = $contentProxy; + $this->dispatcher = $dispatcher; + + parent::__construct(); + } + protected function configure() { $this @@ -34,8 +51,7 @@ class ReloadEntryCommand extends ContainerAwareCommand $userId = null; if ($username = $input->getArgument('username')) { try { - $userId = $this->getContainer() - ->get(UserRepository::class) + $userId = $this->userRepository ->findOneByUserName($username) ->getId(); } catch (NoResultException $e) { @@ -45,8 +61,7 @@ class ReloadEntryCommand extends ContainerAwareCommand } } - $entryRepository = $this->getContainer()->get(EntryRepository::class); - $entryIds = $entryRepository->findAllEntriesIdByUserId($userId); + $entryIds = $this->entryRepository->findAllEntriesIdByUserId($userId); $nbEntries = \count($entryIds); if (!$nbEntries) { @@ -68,22 +83,18 @@ class ReloadEntryCommand extends ContainerAwareCommand $progressBar = $io->createProgressBar($nbEntries); - $contentProxy = $this->getContainer()->get(ContentProxy::class); - $em = $this->getContainer()->get(ManagerRegistry::class)->getManager(); - $dispatcher = $this->getContainer()->get(EventDispatcherInterface::class); - $progressBar->start(); foreach ($entryIds as $entryId) { - $entry = $entryRepository->find($entryId); + $entry = $this->entryRepository->find($entryId); - $contentProxy->updateEntry($entry, $entry->getUrl()); - $em->persist($entry); - $em->flush(); + $this->contentProxy->updateEntry($entry, $entry->getUrl()); + $this->entityManager->persist($entry); + $this->entityManager->flush(); - $dispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); + $this->dispatcher->dispatch(new EntrySavedEvent($entry), EntrySavedEvent::NAME); $progressBar->advance(); - $em->detach($entry); + $this->entityManager->detach($entry); } $progressBar->finish(); diff --git a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php index f982db734..61a882634 100644 --- a/src/Wallabag/CoreBundle/Command/ShowUserCommand.php +++ b/src/Wallabag/CoreBundle/Command/ShowUserCommand.php @@ -3,7 +3,7 @@ namespace Wallabag\CoreBundle\Command; use Doctrine\ORM\NoResultException; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -11,10 +11,17 @@ use Symfony\Component\Console\Style\SymfonyStyle; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Repository\UserRepository; -class ShowUserCommand extends ContainerAwareCommand +class ShowUserCommand extends Command { - /** @var SymfonyStyle */ - protected $io; + protected SymfonyStyle $io; + private UserRepository $userRepository; + + public function __construct(UserRepository $userRepository) + { + $this->userRepository = $userRepository; + + parent::__construct(); + } protected function configure() { @@ -69,6 +76,6 @@ class ShowUserCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getContainer()->get(UserRepository::class)->findOneByUserName($username); + return $this->userRepository->findOneByUserName($username); } } diff --git a/src/Wallabag/CoreBundle/Command/TagAllCommand.php b/src/Wallabag/CoreBundle/Command/TagAllCommand.php index 7ca7279f2..ec1b0ee67 100644 --- a/src/Wallabag/CoreBundle/Command/TagAllCommand.php +++ b/src/Wallabag/CoreBundle/Command/TagAllCommand.php @@ -2,9 +2,9 @@ namespace Wallabag\CoreBundle\Command; +use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NoResultException; -use Doctrine\Persistence\ManagerRegistry; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -13,8 +13,21 @@ use Wallabag\CoreBundle\Helper\RuleBasedTagger; use Wallabag\UserBundle\Entity\User; use Wallabag\UserBundle\Repository\UserRepository; -class TagAllCommand extends ContainerAwareCommand +class TagAllCommand extends Command { + private EntityManagerInterface $entityManager; + private RuleBasedTagger $ruleBasedTagger; + private UserRepository $userRepository; + + public function __construct(EntityManagerInterface $entityManager, RuleBasedTagger $ruleBasedTagger, UserRepository $userRepository) + { + $this->entityManager = $entityManager; + $this->ruleBasedTagger = $ruleBasedTagger; + $this->userRepository = $userRepository; + + parent::__construct(); + } + protected function configure() { $this @@ -39,19 +52,17 @@ class TagAllCommand extends ContainerAwareCommand return 1; } - $tagger = $this->getContainer()->get(RuleBasedTagger::class); $io->text(sprintf('Tagging entries for user %s...', $user->getUserName())); - $entries = $tagger->tagAllForUser($user); + $entries = $this->ruleBasedTagger->tagAllForUser($user); $io->text('Persist ' . \count($entries) . ' entries... '); - $em = $this->getContainer()->get('doctrine')->getManager(); foreach ($entries as $entry) { - $em->persist($entry); + $this->entityManager->persist($entry); } - $em->flush(); + $this->entityManager->flush(); $io->success('Done.'); @@ -67,11 +78,6 @@ class TagAllCommand extends ContainerAwareCommand */ private function getUser($username) { - return $this->getContainer()->get(UserRepository::class)->findOneByUserName($username); - } - - private function getDoctrine() - { - return $this->getContainer()->get(ManagerRegistry::class); + return $this->userRepository->findOneByUserName($username); } } diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index 8413a3c6c..1031e5675 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -2,9 +2,9 @@ namespace Wallabag\ImportBundle\Command; -use Doctrine\Persistence\ManagerRegistry; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; +use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Config\Definition\Exception\Exception; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -20,9 +20,39 @@ use Wallabag\ImportBundle\Import\ReadabilityImport; use Wallabag\ImportBundle\Import\WallabagV1Import; use Wallabag\ImportBundle\Import\WallabagV2Import; use Wallabag\UserBundle\Entity\User; +use Wallabag\UserBundle\Repository\UserRepository; -class ImportCommand extends ContainerAwareCommand +class ImportCommand extends Command { + private EntityManagerInterface $entityManager; + private TokenStorageInterface $tokenStorage; + private UserRepository $userRepository; + private WallabagV2Import $wallabagV2Import; + private FirefoxImport $firefoxImport; + private ChromeImport $chromeImport; + private ReadabilityImport $readabilityImport; + private InstapaperImport $instapaperImport; + private PinboardImport $pinboardImport; + private DeliciousImport $deliciousImport; + private WallabagV1Import $wallabagV1Import; + + public function __construct(EntityManagerInterface $entityManager, TokenStorageInterface $tokenStorage, UserRepository $userRepository, WallabagV2Import $wallabagV2Import, FirefoxImport $firefoxImport, ChromeImport $chromeImport, ReadabilityImport $readabilityImport, InstapaperImport $instapaperImport, PinboardImport $pinboardImport, DeliciousImport $deliciousImport, WallabagV1Import $wallabagV1Import) + { + $this->entityManager = $entityManager; + $this->tokenStorage = $tokenStorage; + $this->userRepository = $userRepository; + $this->wallabagV2Import = $wallabagV2Import; + $this->firefoxImport = $firefoxImport; + $this->chromeImport = $chromeImport; + $this->readabilityImport = $readabilityImport; + $this->instapaperImport = $instapaperImport; + $this->pinboardImport = $pinboardImport; + $this->deliciousImport = $deliciousImport; + $this->wallabagV1Import = $wallabagV1Import; + + parent::__construct(); + } + protected function configure() { $this @@ -45,14 +75,13 @@ class ImportCommand extends ContainerAwareCommand throw new Exception(sprintf('File "%s" not found', $input->getArgument('filepath'))); } - $em = $this->getContainer()->get(ManagerRegistry::class)->getManager(); // Turning off doctrine default logs queries for saving memory - $em->getConnection()->getConfiguration()->setSQLLogger(null); + $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); if ($input->getOption('useUserId')) { - $entityUser = $em->getRepository(User::class)->findOneById($input->getArgument('username')); + $entityUser = $this->userRepository->findOneById($input->getArgument('username')); } else { - $entityUser = $em->getRepository(User::class)->findOneByUsername($input->getArgument('username')); + $entityUser = $this->userRepository->findOneByUsername($input->getArgument('username')); } if (!\is_object($entityUser)) { @@ -66,33 +95,33 @@ class ImportCommand extends ContainerAwareCommand 'main', $entityUser->getRoles()); - $this->getContainer()->get(TokenStorageInterface::class)->setToken($token); - $user = $this->getContainer()->get(TokenStorageInterface::class)->getToken()->getUser(); + $this->tokenStorage->setToken($token); + $user = $this->tokenStorage->getToken()->getUser(); switch ($input->getOption('importer')) { case 'v2': - $import = $this->getContainer()->get(WallabagV2Import::class); + $import = $this->wallabagV2Import; break; case 'firefox': - $import = $this->getContainer()->get(FirefoxImport::class); + $import = $this->firefoxImport; break; case 'chrome': - $import = $this->getContainer()->get(ChromeImport::class); + $import = $this->chromeImport; break; case 'readability': - $import = $this->getContainer()->get(ReadabilityImport::class); + $import = $this->readabilityImport; break; case 'instapaper': - $import = $this->getContainer()->get(InstapaperImport::class); + $import = $this->instapaperImport; break; case 'pinboard': - $import = $this->getContainer()->get(PinboardImport::class); + $import = $this->pinboardImport; break; case 'delicious': - $import = $this->getContainer()->get(DeliciousImport::class); + $import = $this->deliciousImport; break; default: - $import = $this->getContainer()->get(WallabagV1Import::class); + $import = $this->wallabagV1Import; } $import->setMarkAsRead($input->getOption('markAsRead')); @@ -109,7 +138,7 @@ class ImportCommand extends ContainerAwareCommand $output->writeln('' . $summary['skipped'] . ' already saved'); } - $em->clear(); + $this->entityManager->clear(); $output->writeln('End : ' . (new \DateTime())->format('d-m-Y G:i:s') . ' ---'); diff --git a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php index d5f9d3338..5c19d30b3 100644 --- a/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php +++ b/src/Wallabag/ImportBundle/Command/RedisWorkerCommand.php @@ -3,15 +3,25 @@ namespace Wallabag\ImportBundle\Command; use Simpleue\Worker\QueueWorker; -use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; -class RedisWorkerCommand extends ContainerAwareCommand +class RedisWorkerCommand extends Command { + private $container; + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + + parent::__construct(); + } + protected function configure() { $this @@ -29,13 +39,13 @@ class RedisWorkerCommand extends ContainerAwareCommand $serviceName = $input->getArgument('serviceName'); - if (!$this->getContainer()->has('wallabag_import.queue.redis.' . $serviceName) || !$this->getContainer()->has('wallabag_import.consumer.redis.' . $serviceName)) { + if (!$this->container->has('wallabag_import.queue.redis.' . $serviceName) || !$this->container->has('wallabag_import.consumer.redis.' . $serviceName)) { throw new Exception(sprintf('No queue or consumer found for service name: "%s"', $input->getArgument('serviceName'))); } $worker = new QueueWorker( - $this->getContainer()->get('wallabag_import.queue.redis.' . $serviceName), - $this->getContainer()->get('wallabag_import.consumer.redis.' . $serviceName), + $this->container->get('wallabag_import.queue.redis.' . $serviceName), + $this->container->get('wallabag_import.consumer.redis.' . $serviceName), (int) $input->getOption('maxIterations') );