Envelope example


    }

    public function testPayloadFormat()
    {
        $email = (new Email())
            ->subject('Sending email to mailjet API')
            ->replyTo(new Address('qux@example.com', 'Qux'));
        $email->getHeaders()
            ->addTextHeader('X-authorized-header', 'authorized')
            ->addTextHeader('X-MJ-TemplateLanguage', 'forbidden'); // This header is forbidden         $envelope = new Envelope(new Address('foo@example.com', 'Foo')[new Address('bar@example.com', 'Bar')new Address('baz@example.com', 'Baz')]);

        $transport = new MailjetApiTransport(self::USER, self::PASSWORD);
        $method = new \ReflectionMethod(MailjetApiTransport::class, 'getPayload');
        $payload = $method->invoke($transport$email$envelope);

        $this->assertArrayHasKey('Messages', $payload);
        $this->assertNotEmpty($payload['Messages']);

        $message = $payload['Messages'][0];
        $this->assertArrayHasKey('Subject', $message);
        $this->assertEquals('Sending email to mailjet API', $message['Subject']);

        
$connection = $this->createMock(Connection::class)
        );

        $decodedMessage = new DummyMessage('Decoded.');

        $sqsEnvelope = [
            'id' => '5',
            'body' => 'body',
            'headers' => ['my' => 'header'],
        ];

        $serializer->method('decode')->with(['body' => 'body', 'headers' => ['my' => 'header']])->willReturn(new Envelope($decodedMessage));
        $connection->method('get')->willReturn($sqsEnvelope);

        $envelopes = iterator_to_array($transport->get());
        $this->assertSame($decodedMessage$envelopes[0]->getMessage());
    }

    public function testTransportIsAMessageCountAware()
    {
        $transport = $this->getTransport();

        $this->assertInstanceOf(MessageCountAwareInterface::class$transport);
    }
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Exception\InvalidArgumentException;
use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;
use Symfony\Component\Messenger\Transport\Receiver\ListableReceiverInterface;

class FailedMessagesRemoveCommandTest extends TestCase
{
    public function testRemoveSingleMessageWithServiceLocator()
    {
        $globalFailureReceiverName = 'failure_receiver';
        $receiver = $this->createMock(ListableReceiverInterface::class);
        $receiver->expects($this->once())->method('find')->with(20)->willReturn(new Envelope(new \stdClass()));
        $serviceLocator = $this->createMock(ServiceLocator::class);
        $serviceLocator->expects($this->once())->method('has')->with($globalFailureReceiverName)->willReturn(true);
        $serviceLocator->expects($this->any())->method('get')->with($globalFailureReceiverName)->willReturn($receiver);

        $command = new FailedMessagesRemoveCommand(
            $globalFailureReceiverName,
            $serviceLocator
        );

        $tester = new CommandTester($command);
        $tester->execute(['id' => 20, '--force' => true]);

        
use Symfony\Component\Messenger\EventListener\StopWorkerOnCustomStopExceptionListener;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Exception\StopWorkerException;
use Symfony\Component\Messenger\Exception\StopWorkerExceptionInterface;
use Symfony\Component\Messenger\Worker;

class StopWorkerOnCustomStopExceptionListenerTest extends TestCase
{
    public static function provideTests(): \Generator
    {
        yield 'it should not stop (1)' => [new \Exception(), false];
        yield 'it should not stop (2)' => [new HandlerFailedException(new Envelope(new \stdClass())[new \Exception()]), false];

        $t = new class() extends \Exception implements StopWorkerExceptionInterface {};
        yield 'it should stop with custom exception' => [$t, true];
        yield 'it should stop with core exception' => [new StopWorkerException(), true];

        yield 'it should stop with custom exception wrapped (1)' => [new HandlerFailedException(new Envelope(new \stdClass())[new StopWorkerException()]), true];
        yield 'it should stop with custom exception wrapped (2)' => [new HandlerFailedException(new Envelope(new \stdClass())[new \Exception()new StopWorkerException()]), true];
        yield 'it should stop with core exception wrapped (1)' => [new HandlerFailedException(new Envelope(new \stdClass())[$t]), true];
        yield 'it should stop with core exception wrapped (2)' => [new HandlerFailedException(new Envelope(new \stdClass())[new \Exception()$t]), true];
    }

    
$middleware = new DispatchAfterCurrentBusMiddleware();
        $handlingMiddleware = $this->createMock(MiddlewareInterface::class);

        $eventBus = new MessageBus([
            $middleware,
            $handlingMiddleware,
        ]);

        $messageBus = new MessageBus([
            $middleware,
            new DispatchingMiddleware($eventBus[
                new Envelope($firstEvent[new DispatchAfterCurrentBusStamp()]),
                new Envelope($secondEvent[new DispatchAfterCurrentBusStamp()]),
                $thirdEvent, // Not in a new transaction             ]),
            $handlingMiddleware,
        ]);

        $series = [
            // Third event is dispatch within main dispatch, but before its handling:             $thirdEvent,
            // Then expect main dispatched message to be handled first:             $message,
            
$this->assertSame($stamp$envelopes[0]->last(ScheduledStamp::class));
        $this->assertSame('default', $stamp->messageContext->name);
        $this->assertSame('id', $stamp->messageContext->id);
    }

    public function testAckIgnored()
    {
        $transport = new SchedulerTransport($this->createMock(MessageGeneratorInterface::class));

        $this->expectNotToPerformAssertions();
        $transport->ack(new Envelope(new \stdClass()));
    }

    public function testRejectException()
    {
        $transport = new SchedulerTransport($this->createMock(MessageGeneratorInterface::class));

        $this->expectNotToPerformAssertions();
        $transport->reject(new Envelope(new \stdClass()));
    }

    public function testSendException()
    {
use Symfony\Component\Messenger\Test\Middleware\MiddlewareTestCase;
use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage;

/** * @author Maxime Steinhausser <maxime.steinhausser@gmail.com> */
class ActivationMiddlewareTest extends MiddlewareTestCase
{
    public function testExecuteMiddlewareOnActivated()
    {
        $message = new DummyMessage('Hello');
        $envelope = new Envelope($message);

        $stack = $this->getStackMock(false);

        $middleware = $this->createMock(MiddlewareInterface::class);
        $middleware->expects($this->once())->method('handle')->with($envelope$stack)->willReturn($envelope);

        $decorator = new ActivationMiddleware($middleware, true);

        $decorator->handle($envelope$stack);
    }

    

        $this->connection->expects($this->once())
            ->method('beginTransaction')
        ;
        $this->connection->expects($this->once())
            ->method('commit')
        ;
        $this->entityManager->expects($this->once())
            ->method('flush')
        ;

        $this->middleware->handle(new Envelope(new \stdClass())$this->getStackMock());
    }

    public function testTransactionIsRolledBackOnException()
    {
        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Thrown from next middleware.');
        $this->connection->expects($this->once())
            ->method('beginTransaction')
        ;
        $this->connection->expects($this->once())
            ->method('rollBack')
        ;
$message = new DummyMessage();

        $this->transport
            ->expects($this->never())
            ->method('send')
            ->with($message);

        $this->bus
            ->expects($this->once())
            ->method('dispatch')
            ->with($message)
            ->willReturn(new Envelope(new \stdClass()));

        $chatter = new Chatter($this->transport, $this->bus);
        $this->assertNull($chatter->send($message));
    }
}
use Symfony\Component\Mailer\Exception\LogicException;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\Header\PathHeader;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mime\RawMessage;

class EnvelopeTest extends TestCase
{
    public function testConstructorWithAddressSender()
    {
        $e = new Envelope(new Address('fabien@symfony.com')[new Address('thomas@symfony.com')]);
        $this->assertEquals(new Address('fabien@symfony.com')$e->getSender());
    }

    public function testConstructorWithAddressSenderAndNonAsciiCharactersInLocalPartOfAddress()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid sender "fabièn@symfony.com": non-ASCII characters not supported in local-part of email.');
        new Envelope(new Address('fabièn@symfony.com')[new Address('thomas@symfony.com')]);
    }

    public function testConstructorWithNamedAddressSender()
    {
use Symfony\Component\Messenger\Bridge\Doctrine\Transport\Connection;
use Symfony\Component\Messenger\Bridge\Doctrine\Transport\DoctrineSender;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Stamp\DelayStamp;
use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;

class DoctrineSenderTest extends TestCase
{
    public function testSend()
    {
        $envelope = new Envelope(new DummyMessage('Oy'));
        $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]];

        $connection = $this->createMock(Connection::class);
        $connection->expects($this->once())->method('send')->with($encoded['body']$encoded['headers'])->willReturn('15');

        $serializer = $this->createMock(SerializerInterface::class);
        $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded);

        $sender = new DoctrineSender($connection$serializer);
        $actualEnvelope = $sender->send($envelope);

        
use Symfony\Component\Messenger\Tests\Fixtures\TestTracesWithHandleTraitAction;
use Symfony\Component\Messenger\TraceableMessageBus;

class TraceableMessageBusTest extends TestCase
{
    public function testItTracesDispatch()
    {
        $message = new DummyMessage('Hello');

        $stamp = new DelayStamp(5);
        $bus = $this->createMock(MessageBusInterface::class);
        $bus->expects($this->once())->method('dispatch')->with($message[$stamp])->willReturn(new Envelope($message[$stamp]));

        $traceableBus = new TraceableMessageBus($bus);
        $line = __LINE__ + 1;
        $traceableBus->dispatch($message[$stamp]);
        $this->assertCount(1, $tracedMessages = $traceableBus->getDispatchedMessages());
        $actualTracedMessage = $tracedMessages[0];
        unset($actualTracedMessage['callTime']); // don't check, too variable         $this->assertEquals([
            'message' => $message,
            'stamps' => [$stamp],
            'stamps_after_dispatch' => [$stamp],
            
private CliDumper $dumper;

    protected function setUp(): void
    {
        $this->dumper = new CliDumper();
        $this->dumper->setColors(false);
    }

    public function testHandle()
    {
        $message = new DummyMessage('dummy message');
        $envelope = new Envelope($message);

        $bus = $this->createMock(MessageBusInterface::class);
        $bus->method('dispatch')->with($message)->willReturn($envelope);
        $bus = new TraceableMessageBus($bus);

        $collector = new MessengerDataCollector();
        $collector->registerBus('default', $bus);

        $bus->dispatch($message);

        $collector->lateCollect();

        
$queryBus->query($query);
    }

    public function testHandleReturnsHandledStampResult()
    {
        $bus = $this->createMock(MessageBus::class);
        $queryBus = new TestQueryBus($bus);

        $query = new DummyMessage('Hello');
        $bus->expects($this->once())->method('dispatch')->willReturn(
            new Envelope($query[new HandledStamp('result', 'DummyHandler::__invoke')])
        );

        $this->assertSame('result', $queryBus->query($query));
    }

    public function testHandleAcceptsEnvelopes()
    {
        $bus = $this->createMock(MessageBus::class);
        $queryBus = new TestQueryBus($bus);

        $envelope = new Envelope(new DummyMessage('Hello')[new HandledStamp('result', 'DummyHandler::__invoke')]);
        
$this->assertSame($receiverName$sentToFailureTransportStamp->getOriginalReceiverName());

            return true;
        }))->willReturnArgument(0);

        $serviceLocator = $this->createMock(ServiceLocator::class);
        $serviceLocator->expects($this->once())->method('has')->willReturn(true);
        $serviceLocator->expects($this->once())->method('get')->with($receiverName)->willReturn($sender);
        $listener = new SendFailedMessageToFailureTransportListener($serviceLocator);

        $exception = new \Exception('no!');
        $envelope = new Envelope(new \stdClass());
        $event = new WorkerMessageFailedEvent($envelope, 'my_receiver', $exception);

        $listener->onMessageFailed($event);
    }

    public function testDoNothingOnRetryWithServiceLocator()
    {
        $sender = $this->createMock(SenderInterface::class);
        $sender->expects($this->never())->method('send');

        $serviceLocator = $this->createMock(ServiceLocator::class);
        
Home | Imprint | This part of the site doesn't use cookies.