Environment example

/* Basic control characters and null */
        "\r" => '\\D ',
        "\n" => '\\A ',
        "\t" => '\\9 ',
        "\0" => '\\0 ',
        /* Encode spaces for quoteless attribute protection */
        ' ' => '\\20 ',
    ];

    public function testHtmlEscapingConvertsSpecialChars(): void
    {
        $twig = new Environment($this->createMock(LoaderInterface::class));
        foreach ($this->htmlSpecialChars as $key => $value) {
            static::assertEquals($valuesw_escape_filter($twig$key), 'Failed to escape: ' . $key);
        }
    }

    public function testHtmlAttributeEscapingConvertsSpecialChars(): void
    {
        $twig = new Environment($this->createMock(LoaderInterface::class));
        foreach ($this->htmlAttrSpecialChars as $key => $value) {
            static::assertEquals($valuesw_escape_filter($twig$key, 'html_attr'), 'Failed to escape: ' . $key);
        }
    }
use Twig\Node\Expression\NameExpression;
use Twig\Parser;
use Twig\Source;

class FormThemeTokenParserTest extends TestCase
{
    /** * @dataProvider getTestsForFormTheme */
    public function testCompile($source$expected)
    {
        $env = new Environment($this->createMock(LoaderInterface::class)['cache' => false, 'autoescape' => false, 'optimizations' => 0]);
        $env->addTokenParser(new FormThemeTokenParser());
        $source = new Source($source, '');
        $stream = $env->tokenize($source);
        $parser = new Parser($env);

        $expected->setSourceContext($source);

        $this->assertEquals($expected$parser->parse($stream)->getNode('body')->getNode(0));
    }

    public static function getTestsForFormTheme()
    {
class SearchAndRenderBlockNodeTest extends TestCase
{
    public function testCompileWidget()
    {
        $arguments = new Node([
            new NameExpression('form', 0),
        ]);

        $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0);

        $compiler = new Compiler(new Environment($this->createMock(LoaderInterface::class)));

        $this->assertEquals(
            sprintf(
                '$this->env->getRuntime(\'Symfony\Component\Form\FormRenderer\')->searchAndRenderBlock(%s, \'widget\')',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileWidgetWithVariables()
    {
public function testFailIfStoppingWrongEvent()
    {
        $this->expectException(\Twig\Error\SyntaxError::class);
        $this->testTiming('{% stopwatch "foo" %}{% endstopwatch "bar" %}', []);
    }

    /** * @dataProvider getTimingTemplates */
    public function testTiming($template$events)
    {
        $twig = new Environment(new ArrayLoader(['template' => $template])['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]);
        $twig->addExtension(new StopwatchExtension($this->getStopwatch($events)));

        try {
            $twig->render('template');
        } catch (RuntimeError $e) {
            throw $e->getPrevious();
        }
    }

    public static function getTimingTemplates()
    {
        


        putenv('DUMP_LIGHT_ARRAY=');
        putenv('DUMP_STRING_LENGTH=');
    }

    public function testThrowingCaster()
    {
        $out = fopen('php://memory', 'r+');

        require_once __DIR__.'/../Fixtures/Twig.php';
        $twig = new \__TwigTemplate_VarDumperFixture_u75a09(new Environment(new FilesystemLoader()));

        $dumper = new CliDumper();
        $dumper->setColors(false);
        $cloner = new VarCloner();
        $cloner->addCasters([
            ':stream' => function D$res$a) {
                unset($a['wrapper_data']);

                return $a;
            },
        ]);
        
use Twig\Loader\ArrayLoader;
use Twig\Loader\LoaderInterface;

class DumpExtensionTest extends TestCase
{
    /** * @dataProvider getDumpTags */
    public function testDumpTag($template$debug$expectedOutput$expectedDumped)
    {
        $extension = new DumpExtension(new VarCloner());
        $twig = new Environment(new ArrayLoader(['template' => $template])[
            'debug' => $debug,
            'cache' => false,
            'optimizations' => 0,
        ]);
        $twig->addExtension($extension);

        $dumped = null;
        $exception = null;
        $prevDumper = VarDumper::setHandler(function D$var) use (&$dumped) { $dumped = $var});

        try {
            
private function createFinder(array $bundles): Environment
    {
        $loader = new FilesystemLoader(__DIR__ . '/fixtures/Storefront/Resources/views');

        /** @var BundleFixture $bundle */
        foreach ($bundles as $bundle) {
            $directory = $bundle->getPath() . '/Resources/views';
            $loader->addPath($directory);
            $loader->addPath($directory$bundle->getName());
        }

        $twig = new Environment($loader['cache' => $this->cache]);

        $kernel = $this->createMock(Kernel::class);
        $kernel->expects(static::any())
            ->method('getBundles')
            ->willReturn($bundles);

        $scopeDetector = $this->createMock(TemplateScopeDetector::class);
        $scopeDetector->expects(static::any())
            ->method('getScopes')
            ->willReturn([TemplateScopeDetector::DEFAULT_SCOPE]);

        
private FormRenderer $renderer;

    protected function setUp(): void
    {
        parent::setUp();

        $loader = new FilesystemLoader([
            __DIR__.'/../../Resources/views/Form',
            __DIR__.'/Fixtures/templates/form',
        ]);

        $environment = new Environment($loader['strict_variables' => true]);
        $environment->addExtension(new TranslationExtension(new StubTranslator()));
        $environment->addExtension(new FormExtension());

        $rendererEngine = new TwigRendererEngine([
            'bootstrap_4_layout.html.twig',
            'custom_widgets.html.twig',
        ]$environment);
        $this->renderer = new FormRenderer($rendererEngine$this->createMock(CsrfTokenManagerInterface::class));
        $this->registerTwigRuntimeLoader($environment$this->renderer);
    }

    
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Extension\ExpressionExtension;
use Twig\Environment;
use Twig\Loader\ArrayLoader;

class ExpressionExtensionTest extends TestCase
{
    public function testExpressionCreation()
    {
        $template = "{{ expression('1 == 1') }}";
        $twig = new Environment(new ArrayLoader(['template' => $template])['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]);
        $twig->addExtension(new ExpressionExtension());

        $output = $twig->render('template');
        $this->assertEquals('1 == 1', $output);
    }
}
use Twig\Loader\ArrayLoader;

/** * @internal * * @covers \Shopware\Core\Framework\Adapter\Twig\Filter\ReplaceRecursiveFilter */
class ReplaceRecursiveFilterTest extends TestCase
{
    public function testReplace(): void
    {
        $env = new Environment(new ArrayLoader(['test' => '{{ {"berries": ["blueberry"]}|replace_recursive({"berries": ["strawberry", "blackberry"]})|json_encode|raw }}']));
        $env->addExtension(new ReplaceRecursiveFilter());

        static::assertSame('{"berries":["strawberry","blackberry"]}', $env->render('test'));
    }
}

        yield 'option' => [['--format', '']['txt', 'json', 'github']];
    }

    private function createCommandTester(): CommandTester
    {
        return new CommandTester($this->createCommand());
    }

    private function createCommand(): Command
    {
        $environment = new Environment(new FilesystemLoader(\dirname(__DIR__).'/Fixtures/templates/'));
        $environment->addFilter(new TwigFilter('deprecated_filter', fn ($v) => $v['deprecated' => true]));

        $command = new LintCommand($environment);

        $application = new Application();
        $application->add($command);

        return $application->find('lint:twig');
    }

    private function createFile($content): string
    {
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Node;

class TranslationNodeVisitorTest extends TestCase
{
    /** @dataProvider getMessagesExtractionTestData */
    public function testMessagesExtraction(Node $node, array $expectedMessages)
    {
        $env = new Environment($this->createMock(LoaderInterface::class)['cache' => false, 'autoescape' => false, 'optimizations' => 0]);
        $visitor = new TranslationNodeVisitor();
        $visitor->enable();
        $visitor->enterNode($node$env);
        $visitor->leaveNode($node$env);
        $this->assertEquals($expectedMessages$visitor->getMessages());
    }

    public function testMessageExtractionWithInvalidDomainNode()
    {
        $message = 'new key';

        
'validLines' => '4476',
                ],
            ],
        ]$coverageReport['js']);
    }

    /** * @param mixed[] $parameters */
    private function runCommand(array $parameters): string
    {
        $getClassesCommand = new SummarizeCoverageReports($this->getProjectDir()new Environment(new ArrayLoader()));
        $definition = $getClassesCommand->getDefinition();
        $input = new ArrayInput(
            $parameters,
            $definition
        );
        $input->getOptions();
        $output = new BufferedOutput();

        $refMethod = ReflectionHelper::getMethod(SummarizeCoverageReports::class, 'execute');
        $refMethod->invoke($getClassesCommand$input$output);

        
$this->assertEquals('<b>HTML</b>', $body->getParts()[1]->bodyToString());
    }

    public function testRenderWithContextReservedEmailEntry()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->prepareEmail('Text', '', ['email' => 'reserved!']);
    }

    public function testRenderedOnce()
    {
        $twig = new Environment(new ArrayLoader([
            'text' => 'Text',
        ]));
        $renderer = new BodyRenderer($twig);
        $email = (new TemplatedEmail())
            ->to('fabien@symfony.com')
            ->from('helene@symfony.com')
        ;
        $email->textTemplate('text');

        $renderer->render($email);
        $this->assertEquals('Text', $email->getTextBody());

        
public function testNotRenderedTemplatedEmail()
    {
        $this->expectException(LogicException::class);

        $transport = new NullTransport(new EventDispatcher());
        $transport->send((new TemplatedEmail())->htmlTemplate('Some template'));
    }

    public function testRenderedTemplatedEmail()
    {
        $transport = new NullTransport($dispatcher = new EventDispatcher());
        $dispatcher->addSubscriber(new MessageListener(null, new BodyRenderer(new Environment(new ArrayLoader(['tpl' => 'Some message'])))));

        $sentMessage = $transport->send((new TemplatedEmail())->to('me@example.com')->from('me@example.com')->htmlTemplate('tpl'));
        $this->assertMatchesRegularExpression('/Some message/', $sentMessage->getMessage()->toString());
    }

    public function testRejectMessage()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(MessageEvent::classfn (MessageEvent $event) => $event->reject(), 255);
        $dispatcher->addListener(MessageEvent::classfn () => throw new \RuntimeException('Should never be called.'));

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