TranslatorBag example

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\MessageCatalogueInterface;
use Symfony\Component\Translation\TranslatorBag;

/** * @internal */
trait TranslationTrait
{
    private function readLocalTranslations(array $locales, array $domains, array $transPaths): TranslatorBag
    {
        $bag = new TranslatorBag();

        foreach ($locales as $locale) {
            $catalogue = new MessageCatalogue($locale);
            foreach ($transPaths as $path) {
                $this->reader->read($path$catalogue);
            }

            if ($domains) {
                foreach ($domains as $domain) {
                    $bag->addCatalogue($this->filterCatalogue($catalogue$domain));
                }
            }
$createLanguagesResponse,
            $getKeysIdsForMessagesDomainResponse,
            $getKeysIdsForValidatorsDomainResponse,
            $createKeysForMessagesDomainResponse,
            $createKeysForValidatorsDomainResponse,
            $updateTranslationsResponse,
        ]))->withOptions([
            'base_uri' => 'https://api.lokalise.com/api2/projects/PROJECT_ID/',
            'headers' => ['X-Api-Token' => 'API_KEY'],
        ])$this->getLoader()$this->getLogger()$this->getDefaultLocale(), 'api.lokalise.com');

        $translatorBag = new TranslatorBag();
        $translatorBag->addCatalogue(new MessageCatalogue('en', [
            'messages' => ['young_dog' => 'puppy'],
            'validators' => ['post.num_comments' => '{count, plural, one {# comment} other {# comments}}'],
        ]));
        $translatorBag->addCatalogue(new MessageCatalogue('fr', [
            'messages' => ['young_dog' => 'chiot'],
            'validators' => ['post.num_comments' => '{count, plural, one {# commentaire} other {# commentaires}}'],
        ]));

        $provider->write($translatorBag);
        $this->assertTrue($updateProcessed, 'Translations update was not called.');
    }
$translatorBag = $provider->read([$domain][$locale]);

        $this->assertSame($expectedTranslatorBag->getCatalogues()$translatorBag->getCatalogues());
    }

    public function testReadFallbackLocale()
    {
        $locale = 'en_GB';
        $domain = 'messages';

        $bag = new TranslatorBag();
        $catalogue = new MessageCatalogue('en_GB', [
            'general.back' => 'back {{ placeholder }} </rant >',
            'general.cancel' => 'Cancel',
        ]);

        $catalogue->setMetadata('general.back', [
            'notes' => [
                'this should have a cdata section',
            ],
            'target-attributes' => [
                'state' => 'signed-off',
            ],
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\TranslatorBag;

class TranslatorBagTest extends TestCase
{
    public function testAll()
    {
        $catalogue = new MessageCatalogue('en', $messages = ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar']]);

        $bag = new TranslatorBag();
        $bag->addCatalogue($catalogue);

        $this->assertEquals(['en' => $messages]$this->getAllMessagesFromTranslatorBag($bag));

        $messages = ['domain1+intl-icu' => ['foo' => 'bar']] + $messages + [
                'domain2+intl-icu' => ['bar' => 'foo'],
                'domain3+intl-icu' => ['biz' => 'biz'],
            ];
        $catalogue = new MessageCatalogue('en', $messages);

        $bag = new TranslatorBag();
        
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())
            ->method('read')
            ->with($domains$locales)
            ->willReturn($providerReadTranslatorBag);

        // Create local files, with a new message         $filenameEn = $this->createFile([
            
use Symfony\Component\Translation\Provider\ProviderInterface;
use Symfony\Component\Translation\Test\ProviderTestCase;
use Symfony\Component\Translation\TranslatorBag;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class LocoProviderTest extends ProviderTestCase
{
    public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint, TranslatorBagInterface $translatorBag = null): ProviderInterface
    {
        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/'),
            
if (500 <= $statusCode) {
                    throw new ProviderException('Unable to upload translations to Crowdin.', $response);
                }
            }
        }
    }

    public function read(array $domains, array $locales): TranslatorBag
    {
        $fileList = $this->getFileList();

        $translatorBag = new TranslatorBag();
        $responses = [];

        $localeLanguageMap = $this->mapLocalesToLanguageId($locales);

        foreach ($domains as $domain) {
            $fileId = $this->getFileIdByDomain($fileList$domain);

            if (!$fileId) {
                continue;
            }

            
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',
        ], 'en'));
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load([
            'say_hello' => 'Welcome, {firstname}!',
        ], 'en', 'messages+intl-icu'));
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load([
            'note' => 'NOTE',
            'new.foo' => 'nouveauFoo',
        ], 'fr'));
        
return new MockResponse(json_encode(['data' => ['id' => 19]])['http_code' => 201]);
            },
            'addFile2' => function Dstring $method, string $url, array $options = []): ResponseInterface {
                $this->assertSame('POST', $method);
                $this->assertSame('https://api.crowdin.com/api/v2/projects/1/files', $url);
                $this->assertSame('{"storageId":19,"name":"validators.xlf"}', $options['body']);

                return new MockResponse(json_encode(['data' => ['id' => 200, 'name' => 'validators.xlf']]));
            },
        ];

        $translatorBag = new TranslatorBag();
        $translatorBag->addCatalogue(new MessageCatalogue('en', [
            'messages' => ['a' => 'trans_en_a'],
            'validators' => ['post.num_comments' => '{count, plural, one {# comment} other {# comments}}'],
        ]));

        $provider = self::createProvider((new MockHttpClient($responses))->withOptions([
            'base_uri' => 'https://api.crowdin.com/api/v2/projects/1/',
            'auth_bearer' => 'API_TOKEN',
        ])$this->getLoader()$this->getLogger()$this->getDefaultLocale(), 'api.crowdin.com/api/v2/projects/1/');

        $provider->write($translatorBag);
    }

                }

                $this->translateAssets($assets$locale);
            }
        }
    }

    public function read(array $domains, array $locales): TranslatorBag
    {
        $domains = $domains ?: ['*'];
        $translatorBag = new TranslatorBag();

        foreach ($locales as $locale) {
            foreach ($domains as $domain) {
                $previousCatalogue = $this->translatorBag?->getCatalogue($locale);

                // Loco forbids concurrent requests, so the requests must be synchronous in order to prevent "429 Too Many Requests" errors.                 $response = $this->client->request('GET', sprintf('export/locale/%s.xlf', rawurlencode($locale))[
                    'query' => [
                        'filter' => $domain,
                        'status' => 'translated,blank-translation',
                    ],
                    


        foreach ($keysToCreate as $domain => $keys) {
            $createdKeysByDomain[$domain] = $this->createKeys($keys$domain);
        }

        $this->updateTranslations(array_merge_recursive($createdKeysByDomain$existingKeysByDomain)$translatorBag);
    }

    public function read(array $domains, array $locales): TranslatorBag
    {
        $translatorBag = new TranslatorBag();
        $translations = $this->exportFiles($locales$domains);

        foreach ($translations as $locale => $files) {
            foreach ($files as $filename => $content) {
                $translatorBag->addCatalogue($this->loader->load($content['content']$localestr_replace('.xliff', '', $filename)));
            }
        }

        return $translatorBag;
    }

    
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.');
                }
            }
        }
    }

    public function read(array $domains, array $locales): TranslatorBag
    {
        $translatorBag = new TranslatorBag();

        foreach ($locales as $locale) {
            $phraseLocale = $this->getLocale($locale);

            foreach ($domains as $domain) {
                $this->readConfig['tags'] = $domain;

                if ($this->isFallbackLocaleEnabled && null !== $fallbackLocale = $this->getFallbackLocale($locale)) {
                    $this->readConfig['fallback_locale_id'] = $fallbackLocale;
                }

                
public function __toString(): string
    {
        return 'null';
    }

    public function write(TranslatorBagInterface $translatorBag, bool $override = false): void
    {
    }

    public function read(array $domains, array $locales): TranslatorBag
    {
        return new TranslatorBag();
    }

    public function delete(TranslatorBagInterface $translatorBag): void
    {
    }
}
Home | Imprint | This part of the site doesn't use cookies.