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