setCharset example

public function testSend()
    {
        $response = new Response();
        $responseSend = $response->send();
        $this->assertSame($response$responseSend);
    }

    public function testGetCharset()
    {
        $response = new Response();
        $charsetOrigin = 'UTF-8';
        $response->setCharset($charsetOrigin);
        $charset = $response->getCharset();
        $this->assertEquals($charsetOrigin$charset);
    }

    public function testIsCacheable()
    {
        $response = new Response();
        $this->assertFalse($response->isCacheable());
    }

    public function testIsCacheableWithErrorCode()
    {

    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $response = $event->getResponse();

        if (null === $response->getCharset()) {
            $response->setCharset($this->charset);
        }

        if ($this->addContentLanguageHeader && !$response->isInformational() && !$response->isEmpty() && !$response->headers->has('Content-Language')) {
            $response->headers->set('Content-Language', $event->getRequest()->getLocale());
        }

        if ($event->getRequest()->attributes->get('_vary_by_language')) {
            $response->setVary('Accept-Language', false);
        }

        $response->prepare($event->getRequest());
    }


  /** * Copies over the values from the given response. * * @param \Symfony\Component\HttpFoundation\RedirectResponse $response * The redirect response object. */
  protected function fromResponse(RedirectResponse $response) {
    $this->setProtocolVersion($response->getProtocolVersion());
    if ($response->getCharset()) {
      $this->setCharset($response->getCharset());
    }
    // Cookies are separate from other headers and have to be copied over     // directly.     foreach ($response->headers->getCookies() as $cookie) {
      $this->headers->setCookie($cookie);
    }
  }

  /** * {@inheritdoc} */
  
$exportNotGeneratedException = new ExportNotGeneratedException();
            $this->logException($context->getContext()$exportNotGeneratedException);

            throw $exportNotGeneratedException;
        }

        $content = $this->fileSystem->read($filePath);
        $contentType = $this->getContentType($productExport->getFileFormat());
        $encoding = $productExport->getEncoding();

        return (new Response($content ?: null, 200, ['Content-Type' => $contentType . ';charset=' . $encoding]))
            ->setCharset($encoding);
    }

    private function getContentType(string $fileFormat): string
    {
        $contentType = 'text/plain';

        switch ($fileFormat) {
            case ProductExportEntity::FILE_FORMAT_CSV:
                $contentType = 'text/csv';

                break;
            
public function testMultipleAddressesAsMailboxStrings()
    {
        $header = new MailboxListHeader('From', [new Address('chris@swiftmailer.org')new Address('mark@swiftmailer.org')]);
        $this->assertEquals(['chris@swiftmailer.org', 'mark@swiftmailer.org']$header->getAddressStrings());
    }

    public function testNameIsEncodedIfNonAscii()
    {
        $name = 'C'.pack('C', 0x8F).'rbyn';
        $header = new MailboxListHeader('From', [new Address('chris@swiftmailer.org', 'Chris '.$name)]);
        $header->setCharset('iso-8859-1');
        $addresses = $header->getAddressStrings();
        $this->assertEquals('Chris =?'.$header->getCharset().'?Q?C=8Frbyn?= <chris@swiftmailer.org>', array_shift($addresses));
    }

    public function testEncodingLineLengthCalculations()
    {
        /* -- RFC 2047, 2. An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters. */

        

    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $response = $event->getResponse();

        if (null === $response->getCharset()) {
            $response->setCharset($this->charset);
        }

        if ($this->addContentLanguageHeader && !$response->isInformational() && !$response->isEmpty() && !$response->headers->has('Content-Language')) {
            $response->headers->set('Content-Language', $event->getRequest()->getLocale());
        }

        if ($event->getRequest()->attributes->get('_vary_by_language')) {
            $response->setVary('Accept-Language', false);
        }

        $response->prepare($event->getRequest());
    }
private string $charset = '';

    /** * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput * @param string|null $charset The default character encoding to use for non-UTF8 strings * @param int $flags A bit field of static::DUMP_* constants to fine tune dumps representation */
    public function __construct($output = null, string $charset = null, int $flags = 0)
    {
        $this->flags = $flags;
        $this->setCharset($charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8');
        $this->setOutput($output ?: static::$defaultOutput);
        if (!$output && \is_string(static::$defaultOutput)) {
            static::$defaultOutput = $this->outputStream;
        }
    }

    /** * Sets the output destination of the dumps. * * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path * * @return callable|resource|string|null The previous output destination */
$header = new MailboxHeader('Sender', new Address('fabien@symfony.com', 'Fabien Potencier'));
        $this->assertEquals('Fabien Potencier <fabien@symfony.com>', $header->getBodyAsString());

        $header = new MailboxHeader('Sender', new Address('fabien@symfony.com', 'Fabien Potencier, "from Symfony"'));
        $this->assertEquals('"Fabien Potencier, \"from Symfony\"" <fabien@symfony.com>', $header->getBodyAsString());

        $header = new MailboxHeader('From', new Address('fabien@symfony.com', 'Fabien Potencier, \\escaped\\'));
        $this->assertEquals('"Fabien Potencier, \\\\escaped\\\\" <fabien@symfony.com>', $header->getBodyAsString());

        $name = 'P'.pack('C', 0x8F).'tencier';
        $header = new MailboxHeader('Sender', new Address('fabien@symfony.com', 'Fabien '.$name));
        $header->setCharset('iso-8859-1');
        $this->assertEquals('Fabien =?'.$header->getCharset().'?Q?P=8Ftencier?= <fabien@symfony.com>', $header->getBodyAsString());
    }

    public function testUtf8CharsInLocalPart()
    {
        $header = new MailboxHeader('Sender', new Address('fabïen@symfony.com'));
        $this->assertSame('fabïen@symfony.com', $header->getBodyAsString());
    }

    public function testToString()
    {
        

        /* -- RFC 2047, 2. An 'encoded-word' is defined by the following ABNF grammar. The notation of RFC 822 is used, with the exception that white space characters MUST NOT appear between components of an 'encoded-word'. encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" */

        $nonAsciiChar = pack('C', 0x8F);
        $header = new UnstructuredHeader('X-Test', $nonAsciiChar);
        $header->setCharset('iso-8859-1');
        $this->assertEquals('X-Test: =?'.$header->getCharset().'?Q?=8F?=', $header->toString());
    }

    public function testEncodedWordsAreUsedToEncodedNonPrintableAscii()
    {
        // SPACE and TAB permitted         $nonPrintableBytes = array_merge(range(0x00, 0x08)range(0x10, 0x19)[0x7F]);
        foreach ($nonPrintableBytes as $byte) {
            $char = pack('C', $byte);
            $encodedChar = sprintf('=%02X', $byte);
            $header = new UnstructuredHeader('X-A', $char);
            
$this->dispatcher->dispatch($event, KernelEvents::RESPONSE);

        $this->assertEquals('ISO-8859-15', $response->getCharset());
    }

    public function testFilterDoesNothingIfCharsetIsOverridden()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...), 1);

        $response = new Response('foo');
        $response->setCharset('ISO-8859-1');

        $event = new ResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MAIN_REQUEST, $response);
        $this->dispatcher->dispatch($event, KernelEvents::RESPONSE);

        $this->assertEquals('ISO-8859-1', $response->getCharset());
    }

    public function testFiltersSetsNonDefaultCharsetIfNotOverriddenOnNonTextContentType()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener->onKernelResponse(...), 1);

        
class SecuredRedirectResponseTest extends TestCase {

  /** * Tests copying of redirect response. * * @covers ::createFromRedirectResponse * @covers ::fromResponse */
  public function testRedirectCopy() {
    $redirect = new RedirectResponse('/magic_redirect_url', 301, ['x-cache-foobar' => 123]);
    $redirect->setProtocolVersion('2.0');
    $redirect->setCharset('ibm-943_P14A-2000');
    $redirect->headers->setCookie(new Cookie('name', 'value', 0, '/', NULL, FALSE, TRUE, FALSE, NULL));

    // Make a cloned redirect.     $secureRedirect = SecuredRedirectStub::createFromRedirectResponse($redirect);
    $this->assertEquals('/magic_redirect_url', $secureRedirect->getTargetUrl());
    $this->assertEquals(301, $secureRedirect->getStatusCode());
    // We pull the headers from the original redirect because there are default headers applied.     $headers1 = $redirect->headers->allPreserveCase();
    $headers2 = $secureRedirect->headers->allPreserveCase();
    // We unset cache headers so we don't test arcane Symfony weirdness.     // https://github.com/symfony/symfony/issues/16171
$foo = new \stdClass();
        $this->assertEquals($foo$engine->escape($foo), '->escape() does nothing on non strings');
    }

    public function testGetSetCharset()
    {
        $helper = new SlotsHelper();
        $engine = new ProjectTemplateEngine(new TemplateNameParser()$this->loader, [$helper]);
        $this->assertEquals('UTF-8', $engine->getCharset(), 'EngineInterface::getCharset() returns UTF-8 by default');
        $this->assertEquals('UTF-8', $helper->getCharset(), 'HelperInterface::getCharset() returns UTF-8 by default');

        $engine->setCharset('ISO-8859-1');
        $this->assertEquals('ISO-8859-1', $engine->getCharset(), 'EngineInterface::setCharset() changes the default charset to use');
        $this->assertEquals('ISO-8859-1', $helper->getCharset(), 'EngineInterface::setCharset() changes the default charset of helper');
    }

    public function testGlobalVariables()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser()$this->loader);
        $engine->addGlobal('global_variable', 'lorem ipsum');

        $this->assertEquals([
            'global_variable' => 'lorem ipsum',
        ],
// Set default dirs         $this->setTemplateDir('.' . DS . 'templates' . DS)
            ->setCompileDir('.' . DS . 'templates_c' . DS)
            ->setPluginsDir([\dirname(__FILE__) . '/Plugins/', SMARTY_PLUGINS_DIR])
            ->setCacheDir('.' . DS . 'cache' . DS)
            ->setConfigDir('.' . DS . 'configs' . DS);

        $this->debug_tpl = 'file:' . SMARTY_DIR . '/debug.tpl';

        $this->setOptions($options);
        $this->setCharset();
    }

    /** * Technically smarty security is enabled, if a security policy is set for the template manager instance. The * security policy holds a reference to the template manager instance. When cloning the template manager, the * reference of the security_policy to the Smarty instance has be updated to the new cloned Smarty instance. * * Without doing this, every self::fetch() after a directory was added with self::addTemplateDir(), would lead to a * SmartyException with message 'directory [...] not allowed by security setting'. This is because * the security_policy still holds a reference to the old Smarty instance that does not know this new directories * as template sources. * * The security_policy is also cloned so other instances of the Enlight_Template_Manager do not get affected. */
$options = array_merge([
            'debug' => false,
            'charset' => 'UTF-8',
            'strict_variables' => false,
            'autoescape' => 'html',
            'cache' => false,
            'auto_reload' => null,
            'optimizations' => -1,
        ]$options);

        $this->debug = (bool) $options['debug'];
        $this->setCharset($options['charset'] ?? 'UTF-8');
        $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
        $this->strictVariables = (bool) $options['strict_variables'];
        $this->setCache($options['cache']);
        $this->extensionSet = new ExtensionSet();

        $this->addExtension(new CoreExtension());
        $this->addExtension(new EscaperExtension($options['autoescape']));
        $this->addExtension(new OptimizerExtension($options['optimizations']));
    }

    /** * Enables debugging mode. */
use PHPUnit\Framework\TestCase;
use Symfony\Component\Templating\Tests\Fixtures\ProjectTemplateHelper;

/** * @group legacy */
class HelperTest extends TestCase
{
    public function testGetSetCharset()
    {
        $helper = new ProjectTemplateHelper();
        $helper->setCharset('ISO-8859-1');
        $this->assertSame('ISO-8859-1', $helper->getCharset(), '->setCharset() sets the charset set related to this helper');
    }
}
Home | Imprint | This part of the site doesn't use cookies.