3 namespace Wallabag\CoreBundle\Command
;
5 use Doctrine\ORM\NoResultException
;
6 use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand
;
7 use Symfony\Component\Console\Input\InputArgument
;
8 use Symfony\Component\Console\Input\InputInterface
;
9 use Symfony\Component\Console\Output\OutputInterface
;
10 use Symfony\Component\Console\Style\SymfonyStyle
;
11 use Wallabag\CoreBundle\Entity\Entry
;
12 use Wallabag\UserBundle\Entity\User
;
14 class CleanDuplicatesCommand
extends ContainerAwareCommand
16 /** @var SymfonyStyle */
19 protected $duplicates = 0;
21 protected function configure()
24 ->setName('wallabag:clean-duplicates')
25 ->setDescription('Cleans the database for duplicates')
26 ->setHelp('This command helps you to clean your articles list in case of duplicates')
29 InputArgument
::OPTIONAL
,
34 protected function execute(InputInterface
$input, OutputInterface
$output)
36 $this->io
= new SymfonyStyle($input, $output);
38 $username = $input->getArgument('username');
42 $user = $this->getUser($username);
43 $this->cleanDuplicates($user);
44 } catch (NoResultException
$e) {
45 $this->io
->error(sprintf('User "%s" not found.', $username));
50 $this->io
->success('Finished cleaning.');
52 $users = $this->getContainer()->get('wallabag_user.user_repository')->findAll();
54 $this->io
->text(sprintf('Cleaning through <info>%d</info> user accounts', count($users)));
56 foreach ($users as $user) {
57 $this->io
->text(sprintf('Processing user <info>%s</info>', $user->getUsername()));
58 $this->cleanDuplicates($user);
60 $this->io
->success(sprintf('Finished cleaning. %d duplicates found in total', $this->duplicates
));
69 private function cleanDuplicates(User
$user)
71 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
72 $repo = $this->getContainer()->get('wallabag_core.entry_repository');
74 $entries = $repo->findAllEntriesIdAndUrlByUserId($user->getId());
78 foreach ($entries as $entry) {
79 $url = $this->similarUrl($entry['url']);
81 /* @var $entry Entry */
82 if (in_array($url, $urls, true)) {
85 $em->remove($repo->find($entry['id']));
86 $em->flush(); // Flushing at the end of the loop would require the instance not being online
88 $urls[] = $entry['url'];
92 $this->duplicates +
= $duplicatesCount;
94 $this->io
->text(sprintf('Cleaned <info>%d</info> duplicates for user <info>%s</info>', $duplicatesCount, $user->getUserName()));
97 private function similarUrl($url)
99 if (in_array(substr($url, -1), ['/', '#'], true)) { // get rid of "/" and "#" and the end of urls
100 return substr($url, 0, strlen($url));
107 * Fetches a user from its username.
109 * @param string $username
111 * @return \Wallabag\UserBundle\Entity\User
113 private function getUser($username)
115 return $this->getContainer()->get('wallabag_user.user_repository')->findOneByUserName($username);