3 namespace Wallabag\ImportBundle\Consumer
;
5 use Doctrine\ORM\EntityManager
;
6 use Psr\Log\LoggerInterface
;
7 use Psr\Log\NullLogger
;
8 use Symfony\Component\EventDispatcher\EventDispatcherInterface
;
9 use Wallabag\CoreBundle\Entity\Entry
;
10 use Wallabag\CoreBundle\Entity\Tag
;
11 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
12 use Wallabag\ImportBundle\Import\AbstractImport
;
13 use Wallabag\UserBundle\Repository\UserRepository
;
15 abstract class AbstractConsumer
18 protected $userRepository;
20 protected $eventDispatcher;
23 public function __construct(EntityManager
$em, UserRepository
$userRepository, AbstractImport
$import, EventDispatcherInterface
$eventDispatcher, LoggerInterface
$logger = null)
26 $this->userRepository
= $userRepository;
27 $this->import
= $import;
28 $this->eventDispatcher
= $eventDispatcher;
29 $this->logger
= $logger ?: new NullLogger();
33 * Handle a message and save it.
35 * @param string $body Message from the queue (in json)
39 protected function handleMessage($body)
41 $storedEntry = json_decode($body, true);
43 $user = $this->userRepository
->find($storedEntry['userId']);
45 // no user? Drop message
47 $this->logger
->warning('Unable to retrieve user', ['entry' => $storedEntry]);
49 // return true to skip message
53 $this->import
->setUser($user);
55 if (false === $this->import
->validateEntry($storedEntry)) {
56 $this->logger
->warning('Entry is invalid', ['entry' => $storedEntry]);
58 // return true to skip message
62 $entry = $this->import
->parseEntry($storedEntry);
64 if (null === $entry) {
65 $this->logger
->warning('Entry already exists', ['entry' => $storedEntry]);
67 // return true to skip message
74 // entry saved, dispatch event about it!
75 $this->eventDispatcher
->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
77 // clear only affected entities
78 $this->em
->clear(Entry
::class);
79 $this->em
->clear(Tag
::class);
80 } catch (\Exception
$e) {
81 $this->logger
->warning('Unable to save entry', ['entry' => $storedEntry, 'exception' => $e]);
86 $this->logger
->info('Content with url imported! (' . $entry->getUrl() . ')');