Headers example

/** * @author Fabien Potencier <fabien@symfony.com> */
class Message extends RawMessage
{
    private Headers $headers;
    private ?AbstractPart $body;

    public function __construct(Headers $headers = null, AbstractPart $body = null)
    {
        $this->headers = $headers ? clone $headers : new Headers();
        $this->body = $body;
    }

    public function __clone()
    {
        $this->headers = clone $this->headers;

        if (null !== $this->body) {
            $this->body = clone $this->body;
        }
    }

    
use Symfony\Component\Mime\Header\Headers;

/** * @author Fabien Potencier <fabien@symfony.com> */
abstract class AbstractPart
{
    private $headers;

    public function __construct()
    {
        $this->headers = new Headers();
    }

    public function getHeaders(): Headers
    {
        return $this->headers;
    }

    public function getPreparedHeaders(): Headers
    {
        $headers = clone $this->headers;
        $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype());

        

    public function testDefaultTransport()
    {
        $transport = new Transports([
            'foo' => $foo = $this->createMock(TransportInterface::class),
            'bar' => $bar = $this->createMock(TransportInterface::class),
        ]);

        $foo->expects($this->once())->method('send');
        $bar->expects($this->never())->method('send');

        $email = new Message(new Headers()new TextPart('...'));
        $transport->send($email);
    }

    public function testOverrideTransport()
    {
        $transport = new Transports([
            'foo' => $foo = $this->createMock(TransportInterface::class),
            'bar' => $bar = $this->createMock(TransportInterface::class),
        ]);

        $foo->expects($this->never())->method('send');
        
use Symfony\Component\Messenger\Stamp\TransportNamesStamp;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\Message;

class MessengerTransportListenerTest extends TestCase
{
    public function testNoMessengerTransportStampsByDefault()
    {
        $l = new MessengerTransportListener();
        $envelope = new Envelope(new Address('sender@example.com')[new Address('recipient@example.com')]);
        $message = new Message(new Headers());
        $event = new MessageEvent($message$envelope, 'smtp', true);
        $l->onMessage($event);
        $this->assertEmpty($event->getStamps());
    }

    public function testMessengerTransportStampViaHeader()
    {
        $l = new MessengerTransportListener();
        $envelope = new Envelope(new Address('sender@example.com')[new Address('recipient@example.com')]);
        $headers = (new Headers())->addTextHeader('X-Bus-Transport', 'async');
        $message = new Message($headers);
        
$p = new MessagePart((new Email())->from('fabien@symfony.com')->to('you@example.com')->text('content'));
        $this->assertStringContainsString('content', $p->getBody());
        $this->assertStringContainsString('content', $p->bodyToString());
        $this->assertStringContainsString('content', implode('', iterator_to_array($p->bodyToIterable())));
        $this->assertEquals('message', $p->getMediaType());
        $this->assertEquals('rfc822', $p->getMediaSubType());
    }

    public function testHeaders()
    {
        $p = new MessagePart((new Email())->from('fabien@symfony.com')->text('content')->subject('Subject'));
        $this->assertEquals(new Headers(
            new ParameterizedHeader('Content-Type', 'message/rfc822', ['name' => 'Subject.eml']),
            new UnstructuredHeader('Content-Transfer-Encoding', 'base64'),
            new ParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'Subject.eml', 'filename' => 'Subject.eml'])
        )$p->getPreparedHeaders());
    }

    public function testSerialize()
    {
        $email = (new Email())->from('fabien@symfony.com')->to('you@example.com')->text('content');
        $email->getHeaders()->addIdHeader('Message-ID', $email->generateMessageId());

        
use Symfony\Component\Mime\Header\Headers;

/** * @author Fabien Potencier <fabien@symfony.com> */
abstract class AbstractPart
{
    private Headers $headers;

    public function __construct()
    {
        $this->headers = new Headers();
    }

    public function getHeaders(): Headers
    {
        return $this->headers;
    }

    public function getPreparedHeaders(): Headers
    {
        $headers = clone $this->headers;
        $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype());

        
public function mail(array $message) {
    // If 'Return-Path' isn't already set in php.ini, we pass it separately     // as an additional parameter instead of in the header.     if (isset($message['headers']['Return-Path'])) {
      $return_path_set = strpos(ini_get('sendmail_path'), ' -f');
      if (!$return_path_set) {
        $message['Return-Path'] = $message['headers']['Return-Path'];
        unset($message['headers']['Return-Path']);
      }
    }

    $headers = new Headers();
    foreach ($message['headers'] as $name => $value) {
      if (in_array(strtolower($name), self::MAILBOX_LIST_HEADERS, TRUE)) {
        // Split values by comma, but ignore commas encapsulated in double         // quotes.         $value = str_getcsv($value, ',');
      }
      $headers->addHeader($name$value);
    }
    $line_endings = Settings::get('mail_line_endings', PHP_EOL);
    // Prepare mail commands.     $mail_subject = (new UnstructuredHeader('subject', $message['subject']))->getBodyAsString();
    
/** * Cookies from the request * * @var \WpOrg\Requests\Cookie\Jar Array-like object representing a cookie jar */
    public $cookies = [];

    /** * Constructor */
    public function __construct() {
        $this->headers = new Headers();
        $this->cookies = new Jar();
    }

    /** * Is the response a redirect? * * @return boolean True if redirect (3xx status), false if not. */
    public function is_redirect() {
        $code = $this->status_code;
        return in_array($code[300, 301, 302, 303, 307], true) || $code > 307 && $code < 400;
    }
public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        if (Headers::class === $type) {
            $ret = [];
            foreach ($data as $headers) {
                foreach ($headers as $header) {
                    $ret[] = $this->serializer->denormalize($header$this->headerClassMap[strtolower($header['name'])] ?? UnstructuredHeader::class$format$context);
                }
            }

            return new Headers(...$ret);
        }

        if (AbstractPart::class === $type) {
            $type = $data['class'];
            unset($data['class']);
            $data['headers'] = $this->serializer->denormalize($data['headers'], Headers::class$format$context);
        }

        return $this->normalizer->denormalize($data$type$format$context);
    }

    
/** @var \DOMElement $actions */
        $actions = $this->document->getElementsByTagName('flow-actions')->item(0);
        /** @var \DOMElement $action */
        $action = $actions->getElementsByTagName('flow-action')->item(0);
        /** @var \DOMElement $meta */
        $meta = $action->getElementsByTagName('meta')->item(0);

        $meta = Metadata::fromXml($meta);

        $parameter = new Parameter(['id' => 'key']);
        $this->parameters = new Parameters([$parameter]);
        $this->headers = new Headers([$parameter]);
        $inputFiled = new InputField(['id' => 'key']);
        $this->config = new Config([$inputFiled]);

        $this->action = new Action([
            'meta' => $meta,
            'headers' => $this->headers,
            'parameters' => $this->parameters,
            'config' => $this->config,
        ]);
    }

    
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\TextPart;

/** * @requires extension openssl */
class SMimeSignerTest extends SMimeTestCase
{
    public function testSignedMessage()
    {
        $message = new Message(
            (new Headers())
                ->addDateHeader('Date', new \DateTimeImmutable('2019-04-07 10:36:30', new \DateTimeZone('Europe/Paris')))
                ->addMailboxListHeader('From', ['fabien@symfony.com']),
            new TextPart('content')
        );

        $signer = new SMimeSigner($this->samplesDir.'sign.crt', $this->samplesDir.'sign.key');
        $signedMessage = $signer->sign($message);

        $this->assertMessageSignatureIsValid($signedMessage$message);
    }

    
return $converted;
    }

    /** * Sets all header values. * * @since 4.6.0 * * @param array $headers Map of header name to header value. */
    public function set_headers( $headers ) {
        $this->response->headers = new WpOrg\Requests\Response\Headers( $headers );
    }

    /** * Sets a single HTTP header. * * @since 4.6.0 * * @param string $key Header name. * @param string $value Header value. * @param bool $replace Optional. Whether to replace an existing header of the same name. * Default true. */
new Envelope(new Address('fabien@symfony.com')[]);
    }

    public function testConstructorWithWrongRecipients()
    {
        $this->expectException(\InvalidArgumentException::class);
        new Envelope(new Address('fabien@symfony.com')['lucas@symfony.com']);
    }

    public function testSenderFromHeaders()
    {
        $headers = new Headers();
        $headers->addPathHeader('Return-Path', $return = new Address('return@symfony.com', 'return'));
        $headers->addMailboxListHeader('To', ['to@symfony.com']);
        $e = Envelope::create(new Message($headers));
        $this->assertEquals($return$e->getSender());

        $headers = new Headers();
        $headers->addMailboxHeader('Sender', $sender = new Address('sender@symfony.com', 'sender'));
        $headers->addMailboxListHeader('To', ['to@symfony.com']);
        $e = Envelope::create(new Message($headers));
        $this->assertEquals($sender$e->getSender());

        

        $message = new Message($initialHeaders);
        $listener = new MessageListener($defaultHeaders, null, $rules);
        $event = new MessageEvent($messagenew Envelope(new Address('sender@example.com')[new Address('recipient@example.com')]), 'smtp');
        $listener->onMessage($event);

        $this->assertEquals($expectedHeaders$event->getMessage()->getHeaders());
    }

    public static function provideHeaders(): iterable
    {
        $initialHeaders = new Headers();
        $defaultHeaders = (new Headers())
            ->add(new MailboxListHeader('from', [new Address('from-default@example.com')]))
        ;
        yield 'No defaults, all headers copied over' => [$initialHeaders$defaultHeaders$defaultHeaders];

        $initialHeaders = new Headers();
        $defaultHeaders = (new Headers())
            ->add(new UnstructuredHeader('foo', 'bar'))
            ->add(new UnstructuredHeader('bar', 'foo'))
        ;
        yield 'No defaults, default is to set if empty' => [$initialHeaders$defaultHeaders$defaultHeaders];

        


    public function testConstructorWithNonStringOrResource()
    {
        $this->expectException(\TypeError::class);
        new TextPart(new \stdClass());
    }

    public function testHeaders()
    {
        $p = new TextPart('content');
        $this->assertEquals(new Headers(
            new ParameterizedHeader('Content-Type', 'text/plain', ['charset' => 'utf-8']),
            new UnstructuredHeader('Content-Transfer-Encoding', 'quoted-printable')
        )$p->getPreparedHeaders());

        $p = new TextPart('content', 'iso-8859-1');
        $this->assertEquals(new Headers(
            new ParameterizedHeader('Content-Type', 'text/plain', ['charset' => 'iso-8859-1']),
            new UnstructuredHeader('Content-Transfer-Encoding', 'quoted-printable')
        )$p->getPreparedHeaders());
    }

    
Home | Imprint | This part of the site doesn't use cookies.