]>
Commit | Line | Data |
---|---|---|
7d862f83 JB |
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; | |
7816eb62 JB |
12 | use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
13 | use Wallabag\CoreBundle\Event\EntrySavedEvent; | |
7d862f83 JB |
14 | |
15 | abstract class AbstractConsumer | |
16 | { | |
17 | protected $em; | |
18 | protected $userRepository; | |
19 | protected $import; | |
20 | protected $logger; | |
21 | ||
7816eb62 | 22 | public function __construct(EntityManager $em, UserRepository $userRepository, AbstractImport $import, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger = null) |
7d862f83 JB |
23 | { |
24 | $this->em = $em; | |
25 | $this->userRepository = $userRepository; | |
26 | $this->import = $import; | |
7816eb62 | 27 | $this->eventDispatcher = $eventDispatcher; |
7d862f83 JB |
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) { | |
1e3d74a9 | 56 | $this->logger->warning('Entry already exists', ['entry' => $storedEntry]); |
7d862f83 | 57 | |
1e3d74a9 JB |
58 | // return true to skip message |
59 | return true; | |
7d862f83 JB |
60 | } |
61 | ||
62 | try { | |
63 | $this->em->flush(); | |
64 | ||
7816eb62 JB |
65 | // entry saved, dispatch event about it! |
66 | $this->eventDispatcher->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); | |
67 | ||
7d862f83 JB |
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 | } |