]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ImportBundle/Consumer/AbstractConsumer.php
Merge pull request #2481 from wallabag/some-fixes
[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
13 abstract class AbstractConsumer
14 {
15 protected $em;
16 protected $userRepository;
17 protected $import;
18 protected $logger;
19
20 public function __construct(EntityManager $em, UserRepository $userRepository, AbstractImport $import, LoggerInterface $logger = null)
21 {
22 $this->em = $em;
23 $this->userRepository = $userRepository;
24 $this->import = $import;
25 $this->logger = $logger ?: new NullLogger();
26 }
27
28 /**
29 * Handle a message and save it.
30 *
31 * @param string $body Message from the queue (in json)
32 *
33 * @return bool
34 */
35 protected function handleMessage($body)
36 {
37 $storedEntry = json_decode($body, true);
38
39 $user = $this->userRepository->find($storedEntry['userId']);
40
41 // no user? Drop message
42 if (null === $user) {
43 $this->logger->warning('Unable to retrieve user', ['entry' => $storedEntry]);
44
45 return false;
46 }
47
48 $this->import->setUser($user);
49
50 $entry = $this->import->parseEntry($storedEntry);
51
52 if (null === $entry) {
53 $this->logger->warning('Entry already exists', ['entry' => $storedEntry]);
54
55 // return true to skip message
56 return true;
57 }
58
59 try {
60 $this->em->flush();
61
62 // clear only affected entities
63 $this->em->clear(Entry::class);
64 $this->em->clear(Tag::class);
65 } catch (\Exception $e) {
66 $this->logger->warning('Unable to save entry', ['entry' => $storedEntry, 'exception' => $e]);
67
68 return false;
69 }
70
71 $this->logger->info('Content with url imported! ('.$entry->getUrl().')');
72
73 return true;
74 }
75 }