MessageCatalogue example


        $extractor = new PhpAstExtractor([
            new TransMethodVisitor(),
            new TranslatableMessageVisitor(),
            new ConstraintVisitor([
                'NotBlank',
                'Isbn',
                'Length',
            ]new TranslatableMessageVisitor()),
        ]);
        $extractor->setPrefix('prefix');
        $catalogue = new MessageCatalogue('en');

        $extractor->extract($resource$catalogue);

        $expectedHeredoc = <<<EOF heredoc key with whitespace and escaped \$\n sequences EOF;
        $expectedNowdoc = <<<'EOF' nowdoc key with whitespace and nonescaped \$\n sequences EOF;
        $expectedCatalogue = [
            'messages' => [
                

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

    
namespace Symfony\Component\Translation\Tests\Dumper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Dumper\MoFileDumper;
use Symfony\Component\Translation\MessageCatalogue;

class MoFileDumperTest extends TestCase
{
    public function testFormatCatalogue()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(['foo' => 'bar']);

        $dumper = new MoFileDumper();

        $this->assertStringEqualsFile(__DIR__.'/../fixtures/resources.mo', $dumper->formatCatalogue($catalogue, 'messages'));
    }
}
$dom = XmlUtils::loadFile($resource);
        } catch (\InvalidArgumentException $e) {
            throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource)$e->getCode()$e);
        }

        $internalErrors = libxml_use_internal_errors(true);
        libxml_clear_errors();

        $xpath = new \DOMXPath($dom);
        $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');

        $catalogue = new MessageCatalogue($locale);
        if (1 == $nodes->length) {
            $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
            foreach ($translations as $translation) {
                $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;

                if (!empty($translationValue)) {
                    $catalogue->set(
                        (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
                        $translationValue,
                        $domain
                    );
                }
return;
        }

        if ($input->mustSuggestOptionValuesFor('sort')) {
            $suggestions->suggestValues(self::SORT_ORDERS);
        }
    }

    private function filterCatalogue(MessageCatalogue $catalogue, string $domain): MessageCatalogue
    {
        $filteredCatalogue = new MessageCatalogue($catalogue->getLocale());

        // extract intl-icu messages only         $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX;
        if ($intlMessages = $catalogue->all($intlDomain)) {
            $filteredCatalogue->add($intlMessages$intlDomain);
        }

        // extract all messages and subtract intl-icu messages         if ($messages = array_diff($catalogue->all($domain)$intlMessages)) {
            $filteredCatalogue->add($messages$domain);
        }
        
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Dumper\FileDumper;
use Symfony\Component\Translation\MessageCatalogue;

class FileDumperTest extends TestCase
{
    public function testDump()
    {
        $tempDir = sys_get_temp_dir();

        $catalogue = new MessageCatalogue('en');
        $catalogue->add(['foo' => 'bar']);

        $dumper = new ConcreteFileDumper();
        $dumper->dump($catalogue['path' => $tempDir]);

        $this->assertFileExists($tempDir.'/messages.en.concrete');

        @unlink($tempDir.'/messages.en.concrete');
    }

    public function testDumpIntl()
    {
namespace Symfony\Component\Translation\Tests\Catalogue;

use Symfony\Component\Translation\Catalogue\TargetOperation;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\MessageCatalogueInterface;

class TargetOperationTest extends AbstractOperationTestCase
{
    public function testGetMessagesFromSingleDomain()
    {
        $operation = $this->createOperation(
            new MessageCatalogue('en', ['messages' => ['a' => 'old_a', 'b' => 'old_b']]),
            new MessageCatalogue('en', ['messages' => ['a' => 'new_a', 'c' => 'new_c']])
        );

        $this->assertEquals(
            ['a' => 'old_a', 'c' => 'new_c'],
            $operation->getMessages('messages')
        );

        $this->assertEquals(
            ['c' => 'new_c'],
            $operation->getNewMessages('messages')
        );
class TranslationWriterTest extends TestCase
{
    public function testWrite()
    {
        $dumper = $this->createMock(DumperInterface::class);
        $dumper
            ->expects($this->once())
            ->method('dump');

        $writer = new TranslationWriter();
        $writer->addDumper('test', $dumper);
        $writer->write(new MessageCatalogue('en'), 'test');
    }
}
$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',
            ],
        ]);
namespace Symfony\Component\Translation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\Translation\Exception\LogicException;
use Symfony\Component\Translation\MessageCatalogue;

class MessageCatalogueTest extends TestCase
{
    public function testGetLocale()
    {
        $catalogue = new MessageCatalogue('en');

        $this->assertEquals('en', $catalogue->getLocale());
    }

    public function testGetDomains()
    {
        $catalogue = new MessageCatalogue('en', ['domain1' => [], 'domain2' => [], 'domain2+intl-icu' => [], 'domain3+intl-icu' => []]);

        $this->assertEquals(['domain1', 'domain2', 'domain3']$catalogue->getDomains());
    }

    
/** * @throws LogicException */
    public function __construct(MessageCatalogueInterface $source, MessageCatalogueInterface $target)
    {
        if ($source->getLocale() !== $target->getLocale()) {
            throw new LogicException('Operated catalogues must belong to the same locale.');
        }

        $this->source = $source;
        $this->target = $target;
        $this->result = new MessageCatalogue($source->getLocale());
        $this->messages = [];
    }

    public function getDomains(): array
    {
        if (!isset($this->domains)) {
            $domains = [];
            foreach ([$this->source, $this->target] as $catalogue) {
                foreach ($catalogue->getDomains() as $domain) {
                    $domains[$domain] = $domain;

                    
/** * @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));
                }
            } else {
                $bag->addCatalogue($catalogue);
            }
        }
'/Fixtures/Resources/translations/',
                    '/Fixtures/Resources/translations2/',
                ],
            ],
        ], 'yml');

        $this->assertSame('bar', $translator->trans('foo', [], 'ccc', 'fr'));
    }

    protected function getCatalogue($locale$messages$resources = [])
    {
        $catalogue = new MessageCatalogue($locale);
        foreach ($messages as $key => $translation) {
            $catalogue->set($key$translation);
        }
        foreach ($resources as $resource) {
            $catalogue->addResource($resource);
        }

        return $catalogue;
    }

    protected function getLoader()
    {
'inline' => $asTree,
        ];

        if (!$domains) {
            $domains = $provider->getDomains();
        }

        $providerTranslations = $provider->read($domains$locales);

        if ($force) {
            foreach ($providerTranslations->getCatalogues() as $catalogue) {
                $operation = new TargetOperation(new MessageCatalogue($catalogue->getLocale())$catalogue);
                if ($intlIcu) {
                    $operation->moveMessagesToIntlDomainsIfPossible();
                }
                $this->writer->write($operation->getResult()$format$writeOptions);
            }

            $io->success(sprintf('Local translations has been updated from "%s" (for "%s" locale(s), and "%s" domain(s)).', parse_url($provider, \PHP_URL_SCHEME)implode(', ', $locales)implode(', ', $domains)));

            return 0;
        }

        
namespace Symfony\Component\Translation\Tests\Dumper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Dumper\IniFileDumper;
use Symfony\Component\Translation\MessageCatalogue;

class IniFileDumperTest extends TestCase
{
    public function testFormatCatalogue()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(['foo' => 'bar']);

        $dumper = new IniFileDumper();

        $this->assertStringEqualsFile(__DIR__.'/../fixtures/resources.ini', $dumper->formatCatalogue($catalogue, 'messages'));
    }
}
Home | Imprint | This part of the site doesn't use cookies.