Skip to content

[Translation] Added PoEditor Provider #40926

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\Translation\Bridge\Crowdin\CrowdinProviderFactory;
use Symfony\Component\Translation\Bridge\Loco\LocoProviderFactory;
use Symfony\Component\Translation\Bridge\PoEditor\PoEditorProviderFactory;
use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
use Symfony\Component\Translation\PseudoLocalizationTranslator;
use Symfony\Component\Translation\Translator;
Expand Down Expand Up @@ -1344,14 +1345,17 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
$classToServices = [
CrowdinProviderFactory::class => 'translation.provider_factory.crowdin',
LocoProviderFactory::class => 'translation.provider_factory.loco',
PoEditorProviderFactory::class => 'translation.provider_factory.poeditor',
];

$parentPackages = ['symfony/framework-bundle', 'symfony/translation', 'symfony/http-client'];

foreach ($classToServices as $class => $service) {
$package = sprintf('symfony/%s-translation-provider', substr($service, \strlen('translation.provider_factory.')));
switch ($package = substr($service, \strlen('translation.provider_factory.'))) {
case 'poeditor': $package = 'po-editor'; break;
}

if (!$container->hasDefinition('http_client') || !ContainerBuilder::willBeAvailable($package, $class, $parentPackages)) {
if (!$container->hasDefinition('http_client') || !ContainerBuilder::willBeAvailable(sprintf('symfony/%s-translation-provider', $package), $class, $parentPackages)) {
$container->removeDefinition($service);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Translation\Bridge\Crowdin\CrowdinProviderFactory;
use Symfony\Component\Translation\Bridge\Loco\LocoProviderFactory;
use Symfony\Component\Translation\Bridge\PoEditor\PoEditorProviderFactory;
use Symfony\Component\Translation\Provider\NullProviderFactory;
use Symfony\Component\Translation\Provider\TranslationProviderCollection;
use Symfony\Component\Translation\Provider\TranslationProviderCollectionFactory;
Expand Down Expand Up @@ -52,5 +53,14 @@
service('translation.loader.xliff'),
])
->tag('translation.provider_factory')

->set('translation.provider_factory.poeditor', PoEditorProviderFactory::class)
->args([
service('http_client'),
service('logger'),
param('kernel.default_locale'),
service('translation.loader.xliff'),
])
->tag('translation.provider_factory')
;
};
8 changes: 4 additions & 4 deletions src/Symfony/Component/Translation/Bridge/Crowdin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ where:
Resources
---------

* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
n the [main Symfony repository](https://github.com/symfony/symfony)
8 changes: 4 additions & 4 deletions src/Symfony/Component/Translation/Bridge/Loco/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ where:
Resources
---------

* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Translation/Bridge/PoEditor/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

5.3
---

* Create the bridge
19 changes: 19 additions & 0 deletions src/Symfony/Component/Translation/Bridge/PoEditor/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2021 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
239 changes: 239 additions & 0 deletions src/Symfony/Component/Translation/Bridge/PoEditor/PoEditorProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Translation\Bridge\PoEditor;

use Psr\Log\LoggerInterface;
use Symfony\Component\Translation\Exception\ProviderException;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\Provider\ProviderInterface;
use Symfony\Component\Translation\TranslatorBag;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Mathieu Santostefano <msantostefano@protonmail.com>
*
* In PoEditor:
* * Terms refer to Symfony's translation keys;
* * Translations refer to Symfony's translated messages;
* * Context fields refer to Symfony's translation domains
*
* PoEditor's API always returns 200 status code, even in case of failure.
*
* @experimental in 5.3
*/
final class PoEditorProvider implements ProviderInterface
{
private $apiKey;
private $projectId;
private $client;
private $loader;
private $logger;
private $defaultLocale;
private $endpoint;

public function __construct(string $apiKey, string $projectId, HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint)
{
$this->apiKey = $apiKey;
$this->projectId = $projectId;
$this->client = $client;
$this->loader = $loader;
$this->logger = $logger;
$this->defaultLocale = $defaultLocale;
$this->endpoint = $endpoint;
}

public function __toString(): string
{
return sprintf('poeditor://%s', $this->endpoint);
}

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

if (!$defaultCatalogue) {
$defaultCatalogue = $translatorBag->getCatalogues()[0];
}

$terms = $translationsToAdd = [];
foreach ($defaultCatalogue->all() as $domain => $messages) {
foreach ($messages as $id => $message) {
$terms[] = [
'term' => $id,
'reference' => $id,
// tags field is mandatory to export all translations in read method.
'tags' => [$domain],
'context' => $domain,
];
}
}
$this->addTerms($terms);

foreach ($translatorBag->getCatalogues() as $catalogue) {
$locale = $catalogue->getLocale();
foreach ($catalogue->all() as $domain => $messages) {
foreach ($messages as $id => $message) {
$translationsToAdd[$locale][] = [
'term' => $id,
'context' => $domain,
'translation' => [
'content' => $message,
],
];
}
}
}

$this->addTranslations($translationsToAdd);
}

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

foreach ($locales as $locale) {
foreach ($domains as $domain) {
$exportResponses[] = [
'response' => $this->client->request('POST', 'projects/export', [
'body' => [
'api_token' => $this->apiKey,
'id' => $this->projectId,
'language' => $locale,
'type' => 'xlf',
'filters' => json_encode(['translated']),
'tags' => json_encode([$domain]),
],
]),
'locale' => $locale,
'domain' => $domain,
];
}
}

foreach ($exportResponses as $exportResponse) {
$response = $exportResponse['response'];
$responseContent = $response->toArray(false);

if (200 !== $response->getStatusCode() || '200' !== (string) $responseContent['response']['code']) {
$this->logger->error('Unable to read the PoEditor response: '.$response->getContent(false));
continue;
}

$fileUrl = $responseContent['result']['url'];
$downloadResponses[] = [
'response' => $this->client->request('GET', $fileUrl),
'locale' => $exportResponse['locale'],
'domain' => $exportResponse['domain'],
'fileUrl' => $fileUrl,
];
}

foreach ($downloadResponses as $downloadResponse) {
$response = $downloadResponse['response'];
$locale = $downloadResponse['locale'];
$domain = $downloadResponse['domain'];
$fileUrl = $downloadResponse['fileUrl'];
$responseContent = $response->getContent(false);

if (200 !== $response->getStatusCode()) {
$this->logger->error('Unable to download the PoEditor exported file: '.$responseContent);
continue;
}

if (!$responseContent) {
$this->logger->error(sprintf('The exported file "%s" from PoEditor is empty.', $fileUrl));
continue;
}

$translatorBag->addCatalogue($this->loader->load($responseContent, $locale, $domain));
}

return $translatorBag;
}

public function delete(TranslatorBagInterface $translatorBag): void
{
$deletedIds = $termsToDelete = [];

foreach ($translatorBag->getCatalogues() as $catalogue) {
foreach ($catalogue->all() as $domain => $messages) {
foreach ($messages as $id => $message) {
if (\array_key_exists($domain, $deletedIds) && \in_array($id, $deletedIds[$domain], true)) {
continue;
}

$deletedIds[$domain][] = $id;
$termsToDelete[] = [
'term' => $id,
'context' => $domain,
];
}
}
}

$this->deleteTerms($termsToDelete);
}

private function addTerms(array $terms): void
{
$response = $this->client->request('POST', 'terms/add', [
'body' => [
'api_token' => $this->apiKey,
'id' => $this->projectId,
'data' => json_encode($terms),
],
]);

if (200 !== $response->getStatusCode() || '200' !== (string) $response->toArray(false)['response']['code']) {
throw new ProviderException(sprintf('Unable to add new translation keys to PoEditor: (status code: "%s") "%s".', $response->getStatusCode(), $response->getContent(false)), $response);
}
}

private function addTranslations(array $translationsPerLocale): void
{
$responses = [];

foreach ($translationsPerLocale as $locale => $translations) {
$responses = $this->client->request('POST', 'translations/add', [
'body' => [
'api_token' => $this->apiKey,
'id' => $this->projectId,
'language' => $locale,
'data' => json_encode($translations),
],
]);
}

foreach ($responses as $response) {
if (200 !== $response->getStatusCode() || '200' !== (string) $response->toArray(false)['response']['code']) {
$this->logger->error(sprintf('Unable to add translation messages to PoEditor: "%s".', $response->getContent(false)));
}
}
}

private function deleteTerms(array $ids): void
{
$response = $this->client->request('POST', 'terms/delete', [
'body' => [
'api_token' => $this->apiKey,
'id' => $this->projectId,
'data' => json_encode($ids),
],
]);

if (200 !== $response->getStatusCode() || '200' !== (string) $response->toArray(false)['response']['code']) {
throw new ProviderException(sprintf('Unable to delete translation keys on PoEditor: "%s".', $response->getContent(false)), $response);
}
}
}
Loading