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 Wallabag\CoreBundle\Entity\Entry
;
11 use Wallabag\UserBundle\Entity\User
;
13 class CleanDuplicatesCommand
extends ContainerAwareCommand
15 /** @var OutputInterface */
18 protected $duplicates = 0;
20 protected function configure()
23 ->setName('wallabag:clean-duplicates')
24 ->setDescription('Cleans the database for duplicates')
25 ->setHelp('This command helps you to clean your articles list in case of duplicates')
28 InputArgument
::OPTIONAL
,
33 protected function execute(InputInterface
$input, OutputInterface
$output)
35 $this->output
= $output;
37 $username = $input->getArgument('username');
41 $user = $this->getUser($username);
42 $this->cleanDuplicates($user);
43 } catch (NoResultException
$e) {
44 $output->writeln(sprintf('<error>User "%s" not found.</error>', $username));
49 $users = $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findAll();
51 $output->writeln(sprintf('Cleaning through %d user accounts', count($users)));
53 foreach ($users as $user) {
54 $output->writeln(sprintf('Processing user %s', $user->getUsername()));
55 $this->cleanDuplicates($user);
57 $output->writeln(sprintf('Finished cleaning. %d duplicates found in total', $this->duplicates
));
66 private function cleanDuplicates(User
$user)
68 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
69 $repo = $this->getDoctrine()->getRepository('WallabagCoreBundle:Entry');
71 $entries = $repo->getAllEntriesIdAndUrl($user->getId());
75 foreach ($entries as $entry) {
76 $url = $this->similarUrl($entry['url']);
78 /* @var $entry Entry */
79 if (in_array($url, $urls)) {
82 $em->remove($repo->find($entry['id']));
83 $em->flush(); // Flushing at the end of the loop would require the instance not being online
85 $urls[] = $entry['url'];
89 $this->duplicates +
= $duplicatesCount;
91 $this->output
->writeln(sprintf('Cleaned %d duplicates for user %s', $duplicatesCount, $user->getUserName()));
94 private function similarUrl($url)
96 if (in_array(substr($url, -1), ['/', '#'])) { // get rid of "/" and "#" and the end of urls
97 return substr($url, 0, strlen($url));
104 * Fetches a user from its username.
106 * @param string $username
108 * @return \Wallabag\UserBundle\Entity\User
110 private function getUser($username)
112 return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username);
115 private function getDoctrine()
117 return $this->getContainer()->get('doctrine');