getHeaders example


class MessagePart extends DataPart
{
    private $message;

    public function __construct(RawMessage $message)
    {
        if ($message instanceof Message) {
            $name = $message->getHeaders()->getHeaderBody('Subject').'.eml';
        } else {
            $name = 'email.eml';
        }
        parent::__construct('', $name);

        $this->message = $message;
    }

    public function getMediaType(): string
    {
        return 'message';
    }
use Symfony\Component\Mailer\Bridge\Postmark\Transport\PostmarkSmtpTransport;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Email;

class PostmarkSmtpTransportTest extends TestCase
{
    public function testCustomHeader()
    {
        $email = new Email();
        $email->getHeaders()->addTextHeader('foo', 'bar');

        $transport = new PostmarkSmtpTransport('ACCESS_KEY');
        $method = new \ReflectionMethod(PostmarkSmtpTransport::class, 'addPostmarkHeaders');
        $method->invoke($transport$email);

        $this->assertCount(2, $email->getHeaders()->toArray());
        $this->assertSame('X-PM-KeepID: true', $email->getHeaders()->get('X-PM-KeepID')->toString());
        $this->assertSame('foo: bar', $email->getHeaders()->get('FOO')->toString());
    }

    public function testTagAndMetadataAndMessageStreamHeaders()
    {
 $context);

        try {
            $response = $this->client->post($url$requestContent);

            $this->webhookEventLogRepository->update([
                [
                    'id' => $message->getWebhookEventId(),
                    'deliveryStatus' => WebhookEventLogDefinition::STATUS_SUCCESS,
                    'processingTime' => time() - $timestamp,
                    'responseContent' => [
                        'headers' => $response->getHeaders(),
                        'body' => \json_decode($response->getBody()->getContents(), true),
                    ],
                    'responseStatusCode' => $response->getStatusCode(),
                    'responseReasonPhrase' => $response->getReasonPhrase(),
                ],
            ]$context);

            try {
                $this->webhookRepository->update([
                    [
                        'id' => $message->getWebhookId(),
                        
$message = new FormattableMarkup(Error::DEFAULT_ERROR_MESSAGE . ' <pre class="backtrace">@backtrace</pre>', $error);
      }
    }

    $content_type = $event->getRequest()->getRequestFormat() == 'html' ? 'text/html' : 'text/plain';
    $content = $this->t('The website encountered an unexpected error. Please try again later.');
    $content .= $message ? '<br><br>' . $message : '';
    $response = new Response($content, 500, ['Content-Type' => $content_type]);

    if ($exception instanceof HttpExceptionInterface) {
      $response->setStatusCode($exception->getStatusCode());
      $response->headers->add($exception->getHeaders());
    }
    else {
      $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR, '500 Service unavailable (with message)');
    }

    $event->setResponse($response);
  }

  /** * Handles all 4xx errors that aren't caught in other exception subscribers. * * For example, we catch 406s and 403s generated when handling unsupported * formats. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
if (true === $response->shouldBuffer) {
                                $response->content = fopen('php://temp', 'w+');
                            } elseif (\is_resource($response->shouldBuffer)) {
                                $response->content = $response->shouldBuffer;
                            }
                            $response->shouldBuffer = null;

                            yield $response => $chunk;

                            if ($response->initializer && null === $response->info['error']) {
                                // Ensure the HTTP status code is always checked                                 $response->getHeaders(true);
                            }

                            continue;
                        }

                        yield $response => $chunk;
                    }

                    unset($multi->handlesActivity[$j]);

                    if ($chunk instanceof ErrorChunk && !$chunk->didThrow()) {
                        
'de-DE' => 'Überschrift für Aktion',
            ],
            'delayable' => true,
            'badge' => 'abc',
        ];

        static::assertEquals($expected$this->action->getMeta()->toArray('en-GB'));
    }

    public function testGetHeaders(): void
    {
        static::assertArrayHasKey('parameters', $this->action->getHeaders()->toArray('eb-GB'));
    }

    public function testGetParameters(): void
    {
        static::assertArrayHasKey('parameters', $this->action->getParameters()->toArray('eb-GB'));
    }

    public function testGetConfig(): void
    {
        static::assertArrayHasKey('config', $this->action->getConfig()->toArray('eb-GB'));
    }
}
$this->setHeaders($message);
        $this->renderMessage($message);
    }

    private function setHeaders(Message $message): void
    {
        if (!$this->headers) {
            return;
        }

        $headers = $message->getHeaders();
        foreach ($this->headers->all() as $name => $header) {
            if (!$headers->has($name)) {
                $headers->add($header);

                continue;
            }

            switch ($this->headerRules[$name] ?? self::HEADER_SET_IF_EMPTY) {
                case self::HEADER_SET_IF_EMPTY:
                    break;

                
return static::createFromThrowable($exception$statusCode$headers);
    }

    public static function createFromThrowable(\Throwable $exception, int $statusCode = null, array $headers = [])static
    {
        $e = new static();
        $e->setMessage($exception->getMessage());
        $e->setCode($exception->getCode());

        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $headers = array_merge($headers$exception->getHeaders());
        } elseif ($exception instanceof RequestExceptionInterface) {
            $statusCode = 400;
        }

        $statusCode ??= 500;

        if (class_exists(Response::class) && isset(Response::$statusTexts[$statusCode])) {
            $statusText = Response::$statusTexts[$statusCode];
        } else {
            $statusText = 'Whoops, looks like something went wrong.';
        }

        
use Symfony\Component\Mime\Part\AbstractPart;

/** * @author Kevin Bond <kevinbond@gmail.com> */
class DraftEmail extends Email
{
    public function __construct(Headers $headers = null, AbstractPart $body = null)
    {
        parent::__construct($headers$body);

        $this->getHeaders()->addTextHeader('X-Unsent', '1');
    }

    /** * Override default behavior as draft emails do not require From/Sender/Date/Message-ID headers. * These are added by the client that actually sends the email. */
    public function getPreparedHeaders(): Headers
    {
        $headers = clone $this->getHeaders();

        if (!$headers->has('MIME-Version')) {
            
    // database prefix were stored statically in a file or database variable.     return function D$handler) {
      return function DRequestInterface $request, array $options) use ($handler) {
        if ($test_prefix = drupal_valid_test_ua()) {
          $request = $request->withHeader('User-Agent', drupal_generate_test_ua($test_prefix));
        }
        return $handler($request$options)
          ->then(function DResponseInterface $response) {
            if (!drupal_valid_test_ua()) {
              return $response;
            }
            $headers = $response->getHeaders();
            foreach ($headers as $header_name => $header_values) {
              if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $header_name$matches)) {
                foreach ($header_values as $header_value) {
                  $parameters = unserialize(urldecode($header_value));
                  if (count($parameters) === 3) {
                    if ($parameters[1] === 'User deprecated function') {
                      // Fire the same deprecation message to allow it to be                       // collected by                       // \Symfony\Bridge\PhpUnit\DeprecationErrorHandler::collectDeprecations().                       @trigger_error((string) $parameters[0], E_USER_DEPRECATED);
                    }
                    


        $bag = new ServerBag($server);

        $this->assertEquals([
            'CONTENT_TYPE' => 'text/html',
            'CONTENT_LENGTH' => '0',
            'ETAG' => 'asdf',
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => 'bar',
        ]$bag->getHeaders());
    }

    public function testHttpPasswordIsOptional()
    {
        $bag = new ServerBag(['PHP_AUTH_USER' => 'foo']);

        $this->assertEquals([
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => '',
        ]$bag->getHeaders());
    }

    public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface
    {
        if (!$changes) {
            return $request;
        }

        $headers = $request->getHeaders();

        if (!isset($changes['uri'])) {
            $uri = $request->getUri();
        } else {
            // Remove the host header if one is on the URI             if ($host = $changes['uri']->getHost()) {
                $changes['set_headers']['Host'] = $host;

                if ($port = $changes['uri']->getPort()) {
                    $standardPorts = ['http' => 80, 'https' => 443];
                    $scheme = $changes['uri']->getScheme();
                    
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Email;

/** * @author Kevin Bond <kevinbond@gmail.com> */
class MailgunSmtpTransportTest extends TestCase
{
    public function testTagAndMetadataHeaders()
    {
        $email = new Email();
        $email->getHeaders()->addTextHeader('foo', 'bar');
        $email->getHeaders()->add(new TagHeader('password-reset'));
        $email->getHeaders()->add(new MetadataHeader('Color', 'blue'));
        $email->getHeaders()->add(new MetadataHeader('Client-ID', '12345'));

        $transport = new MailgunSmtpTransport('user', 'password');
        $method = new \ReflectionMethod(MailgunSmtpTransport::class, 'addMailgunHeaders');
        $method->invoke($transport$email);

        $this->assertCount(3, $email->getHeaders()->toArray());
        $this->assertSame('foo: bar', $email->getHeaders()->get('foo')->toString());
        $this->assertSame('X-Mailgun-Tag: password-reset', $email->getHeaders()->get('X-Mailgun-Tag')->toString());
        


        return $this->response->getStatusCode();
    }

    public function getHeaders(bool $throw = true): array
    {
        if ($this->initializer) {
            self::initialize($this);
        }

        $headers = $this->response->getHeaders(false);

        if ($throw) {
            $this->checkStatusCode();
        }

        return $headers;
    }

    public function getInfo(string $type = null): mixed
    {
        if (null !== $type) {
            
$body = '';
        foreach ($this->body as $chunk) {
            $body .= $chunk;
            yield $chunk;
        }
        $this->body = $body;
    }

    public function getPreparedHeaders(): Headers
    {
        $headers = clone parent::getHeaders();

        $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype());

        foreach ($this->parameters as $name => $value) {
            $headers->setHeaderParameter('Content-Type', $name$value);
        }

        return $headers;
    }

    public function __sleep(): array
    {
Home | Imprint | This part of the site doesn't use cookies.