]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php
Merge pull request #2180 from wallabag/download-pictures
[github/wallabag/wallabag.git] / src / Wallabag / ImportBundle / Consumer / AbstractConsumer.php
1 <?php
2
3 namespace Wallabag\ImportBundle\Consumer;
4
5 use Doctrine\ORM\EntityManager;
6 use Wallabag\ImportBundle\Import\AbstractImport;
7 use Wallabag\UserBundle\Repository\UserRepository;
8 use Wallabag\CoreBundle\Entity\Entry;
9 use Wallabag\CoreBundle\Entity\Tag;
10 use Psr\Log\LoggerInterface;
11 use Psr\Log\NullLogger;
12 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13 use Wallabag\CoreBundle\Event\EntrySavedEvent;
14
15 abstract class AbstractConsumer
16 {
17 protected $em;
18 protected $userRepository;
19 protected $import;
20 protected $logger;
21
22 public function __construct(EntityManager $em, UserRepository $userRepository, AbstractImport $import, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null)
23 {
24 $this->em = $em;
25 $this->userRepository = $userRepository;
26 $this->import = $import;
27 $this->eventDispatcher = $eventDispatcher;
28 $this->logger = $logger ?: new NullLogger();
29 }
30
31 /**
32 * Handle a message and save it.
33 *
34 * @param string $body Message from the queue (in json)
35 *
36 * @return bool
37 */
38 protected function handleMessage($body)
39 {
40 $storedEntry = json_decode($body, true);
41
42 $user = $this->userRepository->find($storedEntry['userId']);
43
44 // no user? Drop message
45 if (null === $user) {
46 $this->logger->warning('Unable to retrieve user', ['entry' => $storedEntry]);
47
48 return false;
49 }
50
51 $this->import->setUser($user);
52
53 $entry = $this->import->parseEntry($storedEntry);
54
55 if (null === $entry) {
56 $this->logger->warning('Entry already exists', ['entry' => $storedEntry]);
57
58 // return true to skip message
59 return true;
60 }
61
62 try {
63 $this->em->flush();
64
65 // entry saved, dispatch event about it!
66 $this->eventDispatcher->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
67
68 // clear only affected entities
69 $this->em->clear(Entry::class);
70 $this->em->clear(Tag::class);
71 } catch (\Exception $e) {
72 $this->logger->warning('Unable to save entry', ['entry' => $storedEntry, 'exception' => $e]);
73
74 return false;
75 }
76
77 $this->logger->info('Content with url imported! ('.$entry->getUrl().')');
78
79 return true;
80 }
81 }