1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yokai\MessengerBundle\Channel; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManager; |
6
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
7
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
8
|
|
|
use Yokai\MessengerBundle\Delivery; |
9
|
|
|
use Yokai\MessengerBundle\Entity\Notification; |
10
|
|
|
use Yokai\MessengerBundle\Entity\NotificationAttachment; |
11
|
|
|
use Yokai\MessengerBundle\Recipient\IdentifierRecipientInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @author Yann Eugoné <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
class DoctrineChannel implements ChannelInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var EntityManager |
20
|
|
|
*/ |
21
|
|
|
private $manager; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param EntityManager $manager |
25
|
|
|
*/ |
26
|
6 |
|
public function __construct(EntityManager $manager) |
|
|
|
|
27
|
|
|
{ |
28
|
6 |
|
$this->manager = $manager; |
29
|
6 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @inheritdoc |
33
|
|
|
*/ |
34
|
4 |
|
public function supports($recipient) |
35
|
|
|
{ |
36
|
4 |
|
return $recipient instanceof IdentifierRecipientInterface; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @inheritdoc |
41
|
|
|
*/ |
42
|
2 |
|
public function configure(OptionsResolver $resolver) |
43
|
|
|
{ |
44
|
|
|
$resolver |
45
|
2 |
|
->setDefined(['attachments_path']) |
46
|
|
|
; |
47
|
2 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @inheritdoc |
51
|
|
|
*/ |
52
|
1 |
|
public function handle(Delivery $delivery) |
53
|
|
|
{ |
54
|
1 |
|
$options = $delivery->getOptions(); |
55
|
|
|
|
56
|
1 |
|
$notification = new Notification( |
57
|
1 |
|
$delivery->getSubject(), |
58
|
1 |
|
$delivery->getBody(), |
59
|
1 |
|
$delivery->getRecipient() |
60
|
|
|
); |
61
|
|
|
|
62
|
1 |
|
$fs = new Filesystem(); |
63
|
1 |
|
foreach ($delivery->getAttachments() as $attachment) { |
64
|
|
|
$fs->copy( |
65
|
|
|
$attachment->getPathname(), |
66
|
|
|
sprintf('%s/%s', $options['attachments_path'], $attachment->getBasename()) |
67
|
|
|
); |
68
|
|
|
$notificationAttachment = new NotificationAttachment($notification, $attachment->getBasename()); |
69
|
|
|
$notification->addNotificationAttachment($notificationAttachment); |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
$this->manager->persist($notification); |
73
|
1 |
|
$this->manager->flush($notification); |
74
|
1 |
|
} |
75
|
|
|
} |
76
|
|
|
|
The
EntityManager
might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManager
is closed. Any other code which depends on the same instance of theEntityManager
during this request will fail.On the other hand, if you instead inject the
ManagerRegistry
, thegetManager()
method guarantees that you will always get a usable manager instance.