bodyToIterable example



        $this->client = $client ?? HttpClient::create();
    }

    public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
    {
        $headers = $this->getHeaders($request);
        $body = '';
        if (null !== $part = $this->getBody($request)) {
            $headers = array_merge($headers$part->getPreparedHeaders()->toArray());
            $body = $part->bodyToIterable();
        }
        $response = $this->client->request($request->getMethod()$request->getUri()[
            'headers' => $headers,
            'body' => $body,
        ] + $request->attributes->get('http_client_options', []));

        $response = new Response($response->getContent(!$catch)$response->getStatusCode()$response->getHeaders(!$catch));

        $response->headers->remove('X-Body-File');
        $response->headers->remove('X-Body-Eval');
        $response->headers->remove('X-Content-Digest');

        
foreach (\is_array($options['body'] ?? null) ? $options['body'] : [] as $v) {
            if (!$v instanceof DataPart) {
                continue;
            }

            $formDataPart = new FormDataPart($options['body']);

            foreach ($formDataPart->getPreparedHeaders()->all() as $header) {
                $options['headers'][] = $header->toString();
            }

            $options['body'] = $formDataPart->bodyToIterable();

            break;
        }

        $oauth = [
            'oauth_consumer_key' => $this->apiKey,
            'oauth_nonce' => self::$nonce = hash('xxh128', self::$nonce ??= random_bytes(16)),
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp' => time(),
            'oauth_token' => $this->accessToken,
            'oauth_version' => '1.0',
        ];

        $body = new FormDataPart($this->getPayload($email$envelope));
        $headers = [];
        foreach ($body->getPreparedHeaders()->all() as $header) {
            $headers[] = $header->toString();
        }

        $endpoint = sprintf('%s/v3/%s/messages', $this->getEndpoint()urlencode($this->domain));
        $response = $this->client->request('POST', 'https://'.$endpoint[
            'auth_basic' => 'api:'.$this->key,
            'headers' => $headers,
            'body' => $body->bodyToIterable(),
        ]);

        try {
            $statusCode = $response->getStatusCode();
            $result = $response->toArray(false);
        } catch (DecodingExceptionInterface) {
            throw new HttpTransportException('Unable to send an email: '.$response->getContent(false).sprintf(' (code %d).', $statusCode)$response);
        } catch (TransportExceptionInterface $e) {
            throw new HttpTransportException('Could not reach the remote Mailgun server.', $response, 0, $e);
        }

        
$formData = $this->formDataPart($email$envelope);

        $headers = $formData->getPreparedHeaders()->toArray();
        $headers[] = 'Authorization: App '.$this->key;
        $headers[] = 'Accept: application/json';

        $response = $this->client->request(
            'POST',
            sprintf('https://%s/email/%s/send', $this->getEndpoint(), self::API_VERSION),
            [
                'headers' => $headers,
                'body' => $formData->bodyToIterable(),
            ]
        );

        try {
            $statusCode = $response->getStatusCode();
        } catch (TransportExceptionInterface $e) {
            throw new HttpTransportException('Could not reach the remote Infobip server.', $response, 0, $e);
        }

        if (200 !== $statusCode) {
            throw new HttpTransportException(sprintf('Unable to send an email: "%s" (code %d).', $response->getContent(false)$statusCode)$response);
        }
use Symfony\Component\Mime\Header\UnstructuredHeader;
use Symfony\Component\Mime\Part\File;
use Symfony\Component\Mime\Part\TextPart;

class TextPartTest extends TestCase
{
    public function testConstructor()
    {
        $p = new TextPart('content');
        $this->assertEquals('content', $p->getBody());
        $this->assertEquals('content', $p->bodyToString());
        $this->assertEquals('content', implode('', iterator_to_array($p->bodyToIterable())));
        // bodyToIterable() can be called several times         $this->assertEquals('content', implode('', iterator_to_array($p->bodyToIterable())));
        $this->assertEquals('text', $p->getMediaType());
        $this->assertEquals('plain', $p->getMediaSubType());

        $p = new TextPart('content', null, 'html');
        $this->assertEquals('html', $p->getMediaSubType());
    }

    public function testConstructorWithResource()
    {
        
$content = $this->xliffFileDumper->formatCatalogue($catalogue$domain['default_locale' => $this->defaultLocale]);
                $filename = sprintf('%d-%s-%s.xlf', date('YmdHis')$domain$catalogue->getLocale());

                $this->writeConfig['tags'] = $domain;
                $this->writeConfig['locale_id'] = $phraseLocale;
                $fields = array_merge($this->writeConfig, ['file' => new DataPart($content$filename, 'application/xml')]);

                $formData = new FormDataPart($fields);

                $response = $this->httpClient->request('POST', 'uploads', [
                    'body' => $formData->bodyToIterable(),
                    'headers' => $formData->getPreparedHeaders()->toArray(),
                ]);

                if (201 !== $statusCode = $response->getStatusCode()) {
                    $this->logger->error(sprintf('Unable to upload translations for domain "%s" to phrase: "%s".', $domain$response->getContent(false)));

                    $this->throwProviderException($statusCode$response, 'Unable to upload translations to phrase.');
                }
            }
        }
    }

    
return $name.':'.$value."\r\n";
    }

    private function hashBody(AbstractPart $body, string $bodyCanon, int $maxLength): array
    {
        $hash = hash_init('sha256');
        $relaxed = self::CANON_RELAXED === $bodyCanon;
        $currentLine = '';
        $emptyCounter = 0;
        $isSpaceSequence = false;
        $length = 0;
        foreach ($body->bodyToIterable() as $chunk) {
            $canon = '';
            for ($i = 0, $len = \strlen($chunk)$i < $len; ++$i) {
                switch ($chunk[$i]) {
                    case "\r":
                        break;
                    case "\n":
                        // previous char is always \r                         if ($relaxed) {
                            $isSpaceSequence = false;
                        }
                        if ('' === $currentLine) {
                            


    public function toString(): string
    {
        return $this->getPreparedHeaders()->toString()."\r\n".$this->bodyToString();
    }

    public function toIterable(): iterable
    {
        yield $this->getPreparedHeaders()->toString();
        yield "\r\n";
        yield from $this->bodyToIterable();
    }

    public function asDebugString(): string
    {
        return $this->getMediaType().'/'.$this->getMediaSubtype();
    }

    abstract public function bodyToString(): string;

    abstract public function bodyToIterable(): iterable;

    
'description' => $description,
                'focus' => $focus,
            ]));

            $headers = [];
            foreach ($formDataPart->getPreparedHeaders()->all() as $header) {
                $headers[] = $header->toString();
            }

            $responses[] = $this->request('POST', '/api/v2/media', [
                'headers' => $headers,
                'body' => $formDataPart->bodyToIterable(),
            ]);
        }

        $mediaIds = [];

        try {
            foreach ($responses as $i => $response) {
                unset($responses[$i]);
                $result = $response->toArray(false);

                if (300 <= $response->getStatusCode()) {
                    


    public function toString(): string
    {
        return $this->getPreparedHeaders()->toString()."\r\n".$this->bodyToString();
    }

    public function toIterable(): iterable
    {
        yield $this->getPreparedHeaders()->toString();
        yield "\r\n";
        yield from $this->bodyToIterable();
    }

    public function asDebugString(): string
    {
        return $this->getMediaType().'/'.$this->getMediaSubtype();
    }

    abstract public function bodyToString(): string;

    abstract public function bodyToIterable(): iterable;

    
return $name.':'.$value."\r\n";
    }

    private function hashBody(AbstractPart $body, string $bodyCanon, int $maxLength): array
    {
        $hash = hash_init('sha256');
        $relaxed = self::CANON_RELAXED === $bodyCanon;
        $currentLine = '';
        $emptyCounter = 0;
        $isSpaceSequence = false;
        $length = 0;
        foreach ($body->bodyToIterable() as $chunk) {
            $canon = '';
            for ($i = 0, $len = \strlen($chunk)$i < $len; ++$i) {
                switch ($chunk[$i]) {
                    case "\r":
                        break;
                    case "\n":
                        // previous char is always \r                         if ($relaxed) {
                            $isSpaceSequence = false;
                        }
                        if ('' === $currentLine) {
                            
'message' => new DataPart($message->toString(), 'message.mime'),
        ]);
        $headers = [];
        foreach ($body->getPreparedHeaders()->all() as $header) {
            $headers[] = $header->toString();
        }

        $endpoint = sprintf('%s/v3/%s/messages.mime', $this->getEndpoint()urlencode($this->domain));
        $response = $this->client->request('POST', 'https://'.$endpoint[
            'auth_basic' => 'api:'.$this->key,
            'headers' => $headers,
            'body' => $body->bodyToIterable(),
        ]);

        try {
            $statusCode = $response->getStatusCode();
            $result = $response->toArray(false);
        } catch (DecodingExceptionInterface) {
            throw new HttpTransportException('Unable to send an email: '.$response->getContent(false).sprintf(' (code %d).', $statusCode)$response);
        } catch (TransportExceptionInterface $e) {
            throw new HttpTransportException('Could not reach the remote Mailgun server.', $response, 0, $e);
        }

        
use Symfony\Component\Mime\Header\ParameterizedHeader;
use Symfony\Component\Mime\Header\UnstructuredHeader;
use Symfony\Component\Mime\Part\DataPart;

class DataPartTest extends TestCase
{
    public function testConstructor()
    {
        $p = new DataPart('content');
        $this->assertEquals('content', $p->getBody());
        $this->assertEquals(base64_encode('content')$p->bodyToString());
        $this->assertEquals(base64_encode('content')implode('', iterator_to_array($p->bodyToIterable())));
        // bodyToIterable() can be called several times         $this->assertEquals(base64_encode('content')implode('', iterator_to_array($p->bodyToIterable())));
        $this->assertEquals('application', $p->getMediaType());
        $this->assertEquals('octet-stream', $p->getMediaSubType());

        $p = new DataPart('content', null, 'text/html');
        $this->assertEquals('text', $p->getMediaType());
        $this->assertEquals('html', $p->getMediaSubType());
    }

    public function testConstructorWithResource()
    {


        $this->client = $client ?? HttpClient::create();
    }

    public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
    {
        $headers = $this->getHeaders($request);
        $body = '';
        if (null !== $part = $this->getBody($request)) {
            $headers = array_merge($headers$part->getPreparedHeaders()->toArray());
            $body = $part->bodyToIterable();
        }
        $response = $this->client->request($request->getMethod()$request->getUri()[
            'headers' => $headers,
            'body' => $body,
        ] + $request->attributes->get('http_client_options', []));

        $response = new Response($response->getContent(!$catch)$response->getStatusCode()$response->getHeaders(!$catch));

        $response->headers->remove('X-Body-File');
        $response->headers->remove('X-Body-Eval');
        $response->headers->remove('X-Content-Digest');

        
use Symfony\Component\Mime\Header\ParameterizedHeader;
use Symfony\Component\Mime\Header\UnstructuredHeader;
use Symfony\Component\Mime\Part\MessagePart;

class MessagePartTest extends TestCase
{
    public function testConstructor()
    {
        $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'])
        ),
Home | Imprint | This part of the site doesn't use cookies.