fromNotification example


        $notification = (new Notification($subject = 'Subject'))
            ->content($content = 'Content');

        $this->assertSame(
            [
                'title' => $subject,
                'text' => $content,
                '@type' => 'MessageCard',
                '@context' => 'https://schema.org/extensions',
            ],
            MicrosoftTeamsOptions::fromNotification($notification)->toArray()
        );
    }

    public function testGetRecipientIdReturnsRecipientWhenSetViaConstructor()
    {
        $options = new MicrosoftTeamsOptions([
            'recipient_id' => $recipient = '/webhookb2/foo',
        ]);

        $this->assertSame($recipient$options->getRecipientId());
    }

    
$response = $this->createMock(ResponseInterface::class);

        $response->expects($this->exactly(2))
            ->method('getStatusCode')
            ->willReturn(201);

        $response->expects($this->once())
            ->method('getContent')
            ->willReturn(json_encode(['id' => '42']));

        $notification = new Notification($message);
        $chatMessage = ChatMessage::fromNotification($notification);

        $expectedBody = json_encode([
            'specificContent' => [
                'com.linkedin.ugc.ShareContent' => [
                    'shareCommentary' => [
                        'attributes' => [],
                        'text' => 'testMessage',
                    ],
                    'shareMediaCategory' => 'NONE',
                ],
            ],
            

class SmsChannel extends AbstractChannel
{
    public function notify(Notification $notification, RecipientInterface $recipient, string $transportName = null): void
    {
        $message = null;
        if ($notification instanceof SmsNotificationInterface) {
            $message = $notification->asSmsMessage($recipient$transportName);
        }

        $message ??= SmsMessage::fromNotification($notification$recipient);

        if (null !== $transportName) {
            $message->transport($transportName);
        }

        if (null === $this->bus) {
            $this->transport->send($message);
        } else {
            $this->bus->dispatch($message);
        }
    }

    

class PushChannel extends AbstractChannel
{
    public function notify(Notification $notification, RecipientInterface $recipient, string $transportName = null): void
    {
        $message = null;
        if ($notification instanceof PushNotificationInterface) {
            $message = $notification->asPushMessage($recipient$transportName);
        }

        $message ??= PushMessage::fromNotification($notification);

        if (null !== $transportName) {
            $message->transport($transportName);
        }

        if (null === $this->bus) {
            $this->transport->send($message);
        } else {
            $this->bus->dispatch($message);
        }
    }

    
return new MockResponse('1', ['response_headers' => ['request-id' => ['testRequestId']], 'http_code' => 200]);
        });

        $transport = self::createTransport($client);

        $transport->send(new ChatMessage($message$options));
    }

    public function testSendFromNotification()
    {
        $notification = new Notification($message = 'testMessage');
        $chatMessage = ChatMessage::fromNotification($notification);

        $expectedBody = json_encode([
            'text' => $message,
        ]);

        $client = new MockHttpClient(function Dstring $method, string $url, array $options = []) use ($expectedBody): ResponseInterface {
            $this->assertJsonStringEqualsJsonString($expectedBody$options['body']);

            return new MockResponse('1', ['response_headers' => ['request-id' => ['testRequestId']], 'http_code' => 200]);
        });

        
protected function doSend(MessageInterface $message): SentMessage
    {
        if (!$message instanceof ChatMessage) {
            throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class$message);
        }

        if (($options = $message->getOptions()) && !$options instanceof LinkedInOptions) {
            throw new LogicException(sprintf('The "%s" transport only supports instances of "%s" for options.', __CLASS__, LinkedInOptions::class));
        }

        if (!$options && $notification = $message->getNotification()) {
            $options = LinkedInOptions::fromNotification($notification);
            $options->author(new AuthorShare($this->accountId));
        }

        $endpoint = sprintf('https://%s/v2/ugcPosts', $this->getEndpoint());

        $response = $this->client->request('POST', $endpoint[
            'auth_bearer' => $this->authToken,
            'headers' => ['X-Restli-Protocol-Version' => '2.0.0'],
            'json' => array_filter($options?->toArray() ?? $this->bodyFromMessageWithNoOption($message)),
        ]);

        
/** * @see https://documentation.onesignal.com/reference/create-notification */
    protected function doSend(MessageInterface $message): SentMessage
    {
        if (!$message instanceof PushMessage) {
            throw new UnsupportedMessageTypeException(__CLASS__, PushMessage::class$message);
        }

        if (!($options = $message->getOptions()) && $notification = $message->getNotification()) {
            $options = OneSignalOptions::fromNotification($notification);
        }

        $recipientId = $message->getRecipientId() ?? $this->defaultRecipientId;

        if (null === $recipientId) {
            throw new LogicException(sprintf('The "%s" transport should have configured `defaultRecipientId` via DSN or provided with message options.', __CLASS__));
        }

        $options = $options?->toArray() ?? [];
        $options['app_id'] = $this->appId;
        $options['include_player_ids'] = [$recipientId];
        
use Symfony\Component\Notifier\Notification\Notification;

final class MobytOptionsTest extends TestCase
{
    /** * @dataProvider fromNotificationDataProvider */
    public function testFromNotification(string $importance, string $expectedMessageType)
    {
        $notification = (new Notification('Foo'))->importance($importance);

        $options = MobytOptions::fromNotification($notification)->toArray();

        $this->assertSame($expectedMessageType$options['message_type']);
    }

    /** * @return \Generator<array{0: string, 1: string}> */
    public static function fromNotificationDataProvider(): \Generator
    {
        yield [Notification::IMPORTANCE_URGENT, MobytOptions::MESSAGE_TYPE_QUALITY_HIGH];
        yield [Notification::IMPORTANCE_HIGH, MobytOptions::MESSAGE_TYPE_QUALITY_HIGH];
        

        if (!$message instanceof ChatMessage) {
            throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class$message);
        }

        if (($options = $message->getOptions()) && !$options instanceof GoogleChatOptions) {
            throw new LogicException(sprintf('The "%s" transport only supports instances of "%s" for options.', __CLASS__, GoogleChatOptions::class));
        }

        if (!$options) {
            if ($notification = $message->getNotification()) {
                $options = GoogleChatOptions::fromNotification($notification);
            } else {
                $options = GoogleChatOptions::fromMessage($message);
            }
        }

        $threadKey = $options->getThreadKey() ?: $this->threadKey;

        $url = sprintf('https://%s/v1/spaces/%s/messages?key=%s&token=%s%s',
            $this->getEndpoint(),
            $this->space,
            urlencode($this->accessKey),
            
$message = new PushMessage('Hello', 'World');
        $message->transport('next_one');

        $this->assertSame('next_one', $message->getTransport());
    }

    public function testCreateFromNotification()
    {
        $notification = new Notification('Hello');
        $notification->content('World');

        $message = PushMessage::fromNotification($notification);

        $this->assertSame('Hello', $message->getSubject());
        $this->assertSame('World', $message->getContent());
        $this->assertSame($notification$message->getNotification());
    }
}
/** * @author Jan Schädlich <jan.schaedlich@sensiolabs.de> */
class EmailMessageTest extends TestCase
{
    public function testEnsureNonEmptyEmailOnCreationFromNotification()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('"Symfony\Component\Notifier\Message\EmailMessage" needs an email, it cannot be empty.');

        EmailMessage::fromNotification(new Notification()new Recipient('', '+3312345678'));
    }
}
$this->from = $from ?: $envelope?->getSender();
        $this->envelope = $envelope;
    }

    public function notify(Notification $notification, RecipientInterface $recipient, string $transportName = null): void
    {
        $message = null;
        if ($notification instanceof EmailNotificationInterface) {
            $message = $notification->asEmailMessage($recipient$transportName);
        }

        $message ??= EmailMessage::fromNotification($notification$recipient$transportName);
        $email = $message->getMessage();
        if ($email instanceof Email) {
            if (!$email->getFrom()) {
                if (null === $this->from) {
                    throw new LogicException(sprintf('To send the "%s" notification by email, you should either configure a global "from" header, set a sender in the global "envelope" of the mailer configuration or set a "from" header in the "asEmailMessage()" method.', get_debug_type($notification)));
                }

                $email->from($this->from);
            }

            if (!$email->getTo()) {
                
$response = $this->createMock(ResponseInterface::class);

        $response->expects($this->exactly(2))
            ->method('getStatusCode')
            ->willReturn(200);

        $response->expects($this->once())
            ->method('getContent')
            ->willReturn(json_encode(['status' => 1, 'request' => 'uuid']));

        $notification = (new Notification($messageSubject))->content($messageContent);
        $pushMessage = PushMessage::fromNotification($notification);

        $expectedBody = http_build_query([
            'message' => 'testMessageContent',
            'title' => 'testMessageSubject',
            'token' => 'appToken',
            'user' => 'userKey',
        ]);

        $client = new MockHttpClient(function Dstring $method, string $url, array $options = []) use (
            $response,
            $expectedBody
        ):
$response = $this->createMock(ResponseInterface::class);

        $response->expects($this->exactly(2))
            ->method('getStatusCode')
            ->willReturn(200);

        $response->expects($this->once())
            ->method('getContent')
            ->willReturn(json_encode(['ok' => true, 'ts' => '1503435956.000247', 'channel' => 'C123456']));

        $notification = new Notification($message);
        $chatMessage = ChatMessage::fromNotification($notification);
        $options = SlackOptions::fromNotification($notification);

        $expectedBody = json_encode([
            'blocks' => $options->toArray()['blocks'],
            'channel' => $channel,
            'text' => $message,
        ]);

        $client = new MockHttpClient(function Dstring $method, string $url, array $options = []) use ($response$expectedBody): ResponseInterface {
            $this->assertJsonStringEqualsJsonString($expectedBody$options['body']);

            
/** * @see https://api.slack.com/methods/chat.postMessage */
    protected function doSend(MessageInterface $message): SlackSentMessage
    {
        if (!$message instanceof ChatMessage) {
            throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class$message);
        }

        if (!($options = $message->getOptions()) && $notification = $message->getNotification()) {
            $options = SlackOptions::fromNotification($notification);
        }

        $options = $options?->toArray() ?? [];
        $options['channel'] ??= $message->getRecipientId() ?: $this->chatChannel;
        $options['text'] = $message->getSubject();

        $apiMethod = $message->getOptions() instanceof UpdateMessageSlackOptions ? 'chat.update' : 'chat.postMessage';
        $response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/api/'.$apiMethod[
            'json' => array_filter($options),
            'auth_bearer' => $this->accessToken,
            'headers' => [
                
Home | Imprint | This part of the site doesn't use cookies.