]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Command/ExportCommand.php
0cf5de488fa62ee9f8312e076ab58fd4ea307122
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / ExportCommand.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Command;
4
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\Output\StreamOutput;
11
12 class ExportCommand extends ContainerAwareCommand
13 {
14 protected function configure()
15 {
16 $this
17 ->setName('wallabag:export')
18 ->setDescription('Export all entries for an user')
19 ->setHelp('This command helps you to export all entries for an user')
20 ->addArgument(
21 'username',
22 InputArgument::REQUIRED,
23 'User from which to export entries'
24 )
25 ->addArgument(
26 'filepath',
27 InputArgument::OPTIONAL,
28 'Path of the exported file'
29 )
30 ;
31 }
32
33 protected function execute(InputInterface $input, OutputInterface $output)
34 {
35 try {
36 $user = $this->getUser($input->getArgument('username'));
37 } catch (NoResultException $e) {
38 $output->writeln(sprintf('<error>User "%s" not found.</error>', $input->getArgument('username')));
39 return 1;
40 }
41 $entries = $this->getDoctrine()
42 ->getRepository('WallabagCoreBundle:Entry')
43 ->getBuilderForAllByUser($user->getId())
44 ->getQuery()
45 ->getResult();
46
47 $output->write(sprintf('Exporting %d entrie(s) for user « <comment>%s</comment> »... ', count($entries), $user->getUserName()));
48
49 $filePath = $input->getArgument('filepath');
50 if (!$filePath) {
51 $filePath = $this->getContainer()->getParameter('kernel.root_dir') . '/../' . sprintf('%s-export', $user->getUsername());
52 }
53 try {
54 $data = $this->getContainer()->get('wallabag_core.helper.entries_export')
55 ->setEntries($entries)
56 ->updateTitle('All')
57 ->exportJsonData();
58 file_put_contents($filePath, $data);
59 } catch (\InvalidArgumentException $e) {
60 $output->writeln(sprintf('<error>Error: "%s"</error>', $e->getMessage()));
61 }
62
63 $output->writeln('<info>Done.</info>');
64 }
65
66 /**
67 * Fetches a user from its username.
68 *
69 * @param string $username
70 *
71 * @return \Wallabag\UserBundle\Entity\User
72 */
73 private function getUser($username)
74 {
75 return $this->getDoctrine()->getRepository('WallabagUserBundle:User')->findOneByUserName($username);
76 }
77
78 private function getDoctrine()
79 {
80 return $this->getContainer()->get('doctrine');
81 }
82 }