ArrayLoader example

$this->assertEquals($sourcetrim($compiler->getSource()));
        }
    }

    protected function getCompiler(Environment $environment = null)
    {
        return new Compiler(null === $environment ? $this->getEnvironment() : $environment);
    }

    protected function getEnvironment()
    {
        return new Environment(new ArrayLoader([]));
    }

    protected function getVariableGetter($name$line = false)
    {
        $line = $line > 0 ? "// line $line\n" : '';

        return sprintf('%s($context["%s"] ?? null)', $line$name);
    }

    protected function getAttributeGetter()
    {
        
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 {
            
'state' => DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK,
            'parameters' => ['foo' => 'bar'],
            'transChoiceNumber' => null,
        ];

        $this->assertEquals($expectedMessages$collector->getCollectedMessages());
    }

    private function createCollector()
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', ['foo' => 'foo (en)'], 'en');
        $translator->addResource('array', ['bar' => 'bar (fr)'], 'fr');
        $translator->addResource('array', ['bar_ru' => 'bar (ru)'], 'ru');

        return new DataCollectorTranslator($translator);
    }
}
public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint, TranslatorBagInterface $translatorBag = null): ProviderInterface
    {
        return new LokaliseProvider($client$loader$logger$defaultLocale$endpoint);
    }

    public static function toStringProvider(): iterable
    {
        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://api.lokalise.com/api2/projects/PROJECT_ID/',
                'headers' => ['X-Api-Token' => 'API_KEY'],
            ])new ArrayLoader()new NullLogger(), 'en', 'api.lokalise.com'),
            'lokalise://api.lokalise.com',
        ];

        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://example.com',
                'headers' => ['X-Api-Token' => 'API_KEY'],
            ])new ArrayLoader()new NullLogger(), 'en', 'example.com'),
            'lokalise://example.com',
        ];

        
$meta = new ClassMetadataFactory(new AnnotationLoader());
        $runtime = new SerializerRuntime(new Serializer([new ObjectNormalizer($meta)][new JsonEncoder()new YamlEncoder()]));

        $mockRuntimeLoader = $this->createMock(RuntimeLoaderInterface::class);
        $mockRuntimeLoader
            ->method('load')
            ->willReturnMap([
                ['Symfony\Bridge\Twig\Extension\SerializerRuntime', $runtime],
            ])
        ;

        $twig = new Environment(new ArrayLoader(['template' => $template]));
        $twig->addExtension(new SerializerExtension());
        $twig->addRuntimeLoader($mockRuntimeLoader);

        return $twig;
    }
}


            'base' => ' {%- block content "" %} ',
        ];

        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', ['foo' => 'foo (messages)'], 'en');
        $translator->addResource('array', ['foo' => 'foo (custom)'], 'en', 'custom');
        $translator->addResource('array', ['foo' => 'foo (foo)'], 'en', 'foo');

        $template = $this->getTemplate($templates$translator);

        $this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render([])));
    }

    public function testDefaultTranslationDomainWithNamedArguments()
    {
        
->method('render')
            ->with($exception)
        ;

        (new TwigErrorRenderer($twig$nativeRenderer, true))->render(new \Exception());
    }

    public function testFallbackToNativeRendererIfCustomTemplateNotFound()
    {
        $exception = new NotFoundHttpException();

        $twig = new Environment(new ArrayLoader([]));

        $nativeRenderer = $this->createMock(HtmlErrorRenderer::class);
        $nativeRenderer
            ->expects($this->once())
            ->method('render')
            ->with($exception)
            ->willReturn(FlattenException::createFromThrowable($exception))
        ;

        (new TwigErrorRenderer($twig$nativeRenderer, false))->render($exception);
    }

    
parent::setUp();
    }

    protected function tearDown(): void
    {
        parent::tearDown();
        putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
    }

    public function testPushNewMessages()
    {
        $arrayLoader = new ArrayLoader();
        $xliffLoader = new XliffFileLoader();
        $locales = ['en', 'fr'];
        $domains = ['messages'];

        // Simulate existing messages on Provider         $providerReadTranslatorBag = new TranslatorBag();
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load(['note' => 'NOTE'], 'en'));
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load(['note' => 'NOTE'], 'fr'));

        $provider = $this->createMock(ProviderInterface::class);
        $provider->expects($this->once())
            
return new LocoProvider($client$loader$logger$defaultLocale$endpoint$translatorBag ?? new TranslatorBag());
    }

    public static function toStringProvider(): iterable
    {
        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://localise.biz/api/',
                'headers' => [
                    'Authorization' => 'Loco API_KEY',
                ],
            ])new ArrayLoader()new NullLogger(), 'en', 'localise.biz/api/'),
            'loco://localise.biz/api/',
        ];

        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://example.com',
                'headers' => [
                    'Authorization' => 'Loco API_KEY',
                ],
            ])new ArrayLoader()new NullLogger(), 'en', 'example.com'),
            'loco://example.com',
        ];
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()
    {
        

    public function createTemplate(string $template, string $name = null): TemplateWrapper
    {
        $hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $template, false);
        if (null !== $name) {
            $name = sprintf('%s (string template %s)', $name$hash);
        } else {
            $name = sprintf('__string_template__%s', $hash);
        }

        $loader = new ChainLoader([
            new ArrayLoader([$name => $template]),
            $current = $this->getLoader(),
        ]);

        $this->setLoader($loader);
        try {
            return new TemplateWrapper($this$this->loadTemplate($this->getTemplateClass($name)$name));
        } finally {
            $this->setLoader($current);
        }
    }

    

        if (!class_exists(\MessageFormatter::class)) {
            $this->markTestSkipped(sprintf('Skipping test as the required "%s" class does not exist. Consider installing the "intl" PHP extension or the "symfony/polyfill-intl-messageformatter" package.', \MessageFormatter::class));
        }

        $locale = 'any_locale';
        $format = 'some_format';
        $msgid = 'test';

        // Prime the cache         $translator = new Translator($locale, null, $this->tmpDir, $debug);
        $translator->addLoader($formatnew ArrayLoader());
        $translator->addResource($format[$msgid => 'OK']$locale);
        $translator->addResource($format[$msgid.'+intl' => 'OK']$locale, 'messages+intl-icu');
        $translator->trans($msgid);
        $translator->trans($msgid.'+intl', [], 'messages+intl-icu');

        // Try again and see we get a valid result whilst no loader can be used         $translator = new Translator($locale, null, $this->tmpDir, $debug);
        $translator->addLoader($format$this->createFailingLoader());
        $translator->addResource($format[$msgid => 'OK']$locale);
        $translator->addResource($format[$msgid.'+intl' => 'OK']$locale, 'messages+intl-icu');
        $this->assertEquals('OK', $translator->trans($msgid), '-> caching does not work in '.($debug ? 'debug' : 'production'));
        
// with attributes         $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/')['default' => 'default', 'attributes' => ['p1' => 'v1', 'p2' => 'v2']])->getContent());

        // with id & attributes         $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/')['default' => 'default', 'id' => 'bar', 'attributes' => ['p1' => 'v1', 'p2' => 'v2']])->getContent());
    }

    public function testRenderWithTwigAndDefaultText()
    {
        $twig = new Environment($loader = new ArrayLoader());
        $strategy = new HIncludeFragmentRenderer($twig);
        $this->assertEquals('<hx:include src="/foo">loading...</hx:include>', $strategy->render('/foo', Request::create('/')['default' => 'loading...'])->getContent());
    }
}
public function testGetCatalogueReturnsConsolidatedCatalogue()
    {
        /* * This will be useful once we refactor so that different domains will be loaded lazily (on-demand). * In that case, getCatalogue() will probably have to load all missing domains in order to return * one complete catalogue. */

        $locale = 'whatever';
        $translator = new Translator($locale);
        $translator->addLoader('loader-a', new ArrayLoader());
        $translator->addLoader('loader-b', new ArrayLoader());
        $translator->addResource('loader-a', ['foo' => 'foofoo']$locale, 'domain-a');
        $translator->addResource('loader-b', ['bar' => 'foobar']$locale, 'domain-b');

        /* * Test that we get a single catalogue comprising messages * from different loaders and different domains */
        $catalogue = $translator->getCatalogue($locale);
        $this->assertTrue($catalogue->defines('foo', 'domain-a'));
        $this->assertTrue($catalogue->defines('bar', 'domain-b'));
    }
parent::setUp();
    }

    protected function tearDown(): void
    {
        parent::tearDown();
        putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
    }

    public function testPullNewXlf12Messages()
    {
        $arrayLoader = new ArrayLoader();
        $filenameEn = $this->createFile();
        $filenameEnIcu = $this->createFile(['say_hello' => 'Welcome, {firstname}!'], 'en', 'messages+intl-icu.%locale%.xlf');
        $filenameFr = $this->createFile(['note' => 'NOTE'], 'fr');
        $filenameFrIcu = $this->createFile(['say_hello' => 'Bonjour, {firstname}!'], 'fr', 'messages+intl-icu.%locale%.xlf');
        $locales = ['en', 'fr'];
        $domains = ['messages', 'messages+intl-icu'];

        $providerReadTranslatorBag = new TranslatorBag();
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load([
            'note' => 'NOTE',
            'new.foo' => 'newFoo',
        ],
Home | Imprint | This part of the site doesn't use cookies.