addCatalogue example

'query' => $this->readConfig,
                    'headers' => $headers,
                ]);

                if (200 !== ($statusCode = $response->getStatusCode()) && 304 !== $statusCode) {
                    $this->logger->error(sprintf('Unable to get translations for locale "%s" from phrase: "%s".', $locale$response->getContent(false)));

                    $this->throwProviderException($statusCode$response, 'Unable to get translations from phrase.');
                }

                $content = 304 === $statusCode && null !== $cachedResponse ? $cachedResponse['content'] : $response->getContent();
                $translatorBag->addCatalogue($this->loader->load($content$locale$domain));

                // using weak etags, responses for requests with fallback locale enabled can not be reliably cached...                 if (!$this->isFallbackLocaleEnabled) {
                    $headers = $response->getHeaders(false);
                    $cacheItem->set(['etag' => $headers['etag'][0], 'modified' => $headers['last-modified'][0], 'content' => $content]);
                    $this->cache->save($cacheItem);
                }
            }
        }

        return $translatorBag;
    }
foreach ($downloads as [$response$locale$domain]) {
            if (200 !== $statusCode = $response->getStatusCode()) {
                $this->logger->error(sprintf('Unable to download file content: "%s".', $response->getContent(false)));

                if (500 <= $statusCode) {
                    throw new ProviderException('Unable to download file content.', $response);
                }

                continue;
            }

            $translatorBag->addCatalogue($this->loader->load($response->getContent()$locale$domain));
        }

        return $translatorBag;
    }

    public function delete(TranslatorBagInterface $translatorBag): void
    {
        $fileList = $this->getFileList();
        $responses = [];

        $defaultCatalogue = $translatorBag->getCatalogue($this->defaultLocale);

        

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

        return $bag;
    }

    private function filterCatalogue(MessageCatalogue $catalogue, string $domain): MessageCatalogue
    {
        
'target-attributes' => [
                'state' => 'signed-off',
            ],
        ]);

        $catalogue->setMetadata('general.cancel', [
            'target-attributes' => [
                'state' => 'translated',
            ],
        ]);

        $bag->addCatalogue($catalogue);

        $item = $this->createMock(CacheItemInterface::class);
        $item->expects(self::once())->method('isHit')->willReturn(false);
        $item->expects(self::never())->method('set');

        $this->getCache()
            ->expects(self::once())
            ->method('getItem')
            ->with(self::callback(function D$v) use ($locale$domain) {
                $this->assertStringStartsWith($locale.'.'.$domain.'.', $v);

                


    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([
            'note' => 'NOTE',
            
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'));
        $providerReadTranslatorBag->addCatalogue($arrayLoader->load([
            
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();
        $bag->addCatalogue($catalogue);

        
if (!str_ends_with($domain$catalogue::INTL_DOMAIN_SUFFIX)) {
                        $previousMessages = array_diff_key($previousMessages$previousCatalogue->all($domain.$catalogue::INTL_DOMAIN_SUFFIX));
                    }
                    foreach ($previousMessages as $key => $message) {
                        $catalogue->set($this->retrieveKeyFromId($key$domain)$message$domain);
                    }

                    foreach ($previousCatalogue->getCatalogueMetadata('', $domain) as $key => $value) {
                        $catalogue->setCatalogueMetadata($key$value$domain);
                    }

                    $translatorBag->addCatalogue($catalogue);

                    continue;
                }

                $responseContent = $response->getContent(false);

                if (200 !== $response->getStatusCode()) {
                    throw new ProviderException('Unable to read the Loco response: '.$responseContent$response);
                }

                $locoCatalogue = $this->loader->load($responseContent$locale$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;
    }

    public function delete(TranslatorBagInterface $translatorBag): void
    {
        $catalogue = $translatorBag->getCatalogue($this->defaultLocale);

        if (!$catalogue) {
            
use Symfony\Component\Translation\Catalogue\AbstractOperation;
use Symfony\Component\Translation\Catalogue\TargetOperation;

final class TranslatorBag implements TranslatorBagInterface
{
    /** @var MessageCatalogue[] */
    private array $catalogues = [];

    public function addCatalogue(MessageCatalogue $catalogue): void
    {
        if (null !== $existingCatalogue = $this->getCatalogue($catalogue->getLocale())) {
            $catalogue->addCatalogue($existingCatalogue);
        }

        $this->catalogues[$catalogue->getLocale()] = $catalogue;
    }

    public function addBag(TranslatorBagInterface $bag): void
    {
        foreach ($bag->getCatalogues() as $catalogue) {
            $this->addCatalogue($catalogue);
        }
    }

    
if (!is_dir($directory)) {
            return;
        }

        foreach ($this->loaders as $format => $loader) {
            // load any existing translation files             $finder = new Finder();
            $extension = $catalogue->getLocale().'.'.$format;
            $files = $finder->files()->name('*.'.$extension)->in($directory);
            foreach ($files as $file) {
                $domain = substr($file->getFilename(), 0, -1 * \strlen($extension) - 1);
                $catalogue->addCatalogue($loader->load($file->getPathname()$catalogue->getLocale()$domain));
            }
        }
    }
}

            '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->catalogues[$locale] = new MessageCatalogue($locale);

        if (isset($this->resources[$locale])) {
            foreach ($this->resources[$locale] as $resource) {
                if (!isset($this->loaders[$resource[0]])) {
                    if (\is_string($resource[1])) {
                        throw new RuntimeException(sprintf('No loader is registered for the "%s" format when loading the "%s" resource.', $resource[0]$resource[1]));
                    }

                    throw new RuntimeException(sprintf('No loader is registered for the "%s" format.', $resource[0]));
                }
                $this->catalogues[$locale]->addCatalogue($this->loaders[$resource[0]]->load($resource[1]$locale$resource[2]));
            }
        }
    }

    private function loadFallbackCatalogues(string $locale): void
    {
        $current = $this->catalogues[$locale];

        foreach ($this->computeFallbackLocales($locale) as $fallback) {
            if (!isset($this->catalogues[$fallback])) {
                $this->initializeCatalogue($fallback);
            }
'translateAsset4' => function Dstring $method, string $url, array $options = []) use ($expectedAuthHeader): ResponseInterface {
                $this->assertSame('POST', $method);
                $this->assertSame('https://localise.biz/api/translations/validators__post.num_comments/fr', $url);
                $this->assertSame($expectedAuthHeader$options['normalized_headers']['authorization'][0]);
                $this->assertSame('{count, plural, one {# commentaire} other {# commentaires}}', $options['body']);

                return new MockResponse();
            },
        ];

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

        $provider = self::createProvider((new MockHttpClient($responses))->withOptions([
            'base_uri' => 'https://localise.biz/api/',
            'headers' => ['Authorization' => 'Loco API_KEY'],
        ]),
$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.');
    }

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