Skip to content

Commit

Permalink
Merge pull request #107 from calien666/feature/support-api-languages
Browse files Browse the repository at this point in the history
[FEATURE] add supported languages automatically from API
  • Loading branch information
NarkNiro authored Jan 27, 2023
2 parents b8c1d49 + 766b968 commit 1bc7802
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 3 deletions.
60 changes: 57 additions & 3 deletions Classes/Service/DeeplService.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
***************************************************************/

use GuzzleHttp\Exception\ClientException;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
Expand All @@ -54,20 +55,25 @@ class DeeplService
* @see https://www.deepl.com/de/docs-api/translating-text/#request
* @var string[]
*/
public array $apiSupportedLanguages = ['BG', 'CS', 'DA', 'DE', 'EL', 'EN', 'ES', 'ET', 'FI', 'FR', 'HU', 'ID', 'IT', 'JA', 'LT', 'LV', 'NL', 'PL', 'PT', 'RO', 'RU', 'SK', 'SL', 'SV', 'TR', 'ZH'];
public array $apiSupportedLanguages = [];

/**
* Formality supported languages
* @var string[]
*/
public array $formalitySupportedLanguages = ['DE', 'FR', 'IT', 'ES', 'NL', 'PL', 'PT-PT', 'PT-BR', 'RU'];
public array $formalitySupportedLanguages = [];

public RequestFactory $requestFactory;

protected SettingsRepository $deeplSettingsRepository;

public function __construct()
protected GlossariesSyncRepository $glossariesSyncRepository;

private FrontendInterface $cache;

public function __construct(?FrontendInterface $cache = null)
{
$this->cache = $cache ?? GeneralUtility::makeInstance(CacheManager::class)->getCache('wvdeepltranslate');
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$this->deeplSettingsRepository = $objectManager->get(SettingsRepository::class);
$this->glossariesSyncRepository = $objectManager->get(GlossariesSyncRepository::class);
Expand All @@ -77,6 +83,8 @@ public function __construct()
$this->apiUrl = $extensionConfiguration['apiUrl'];
$this->apiKey = $extensionConfiguration['apiKey'];
$this->deeplFormality = $extensionConfiguration['deeplFormality'];

$this->loadSupportedLanguages();
$this->apiSupportedLanguages = $this->deeplSettingsRepository->getSupportedLanguages($this->apiSupportedLanguages);
}

Expand Down Expand Up @@ -132,4 +140,50 @@ public function translateRequest($content, $targetLanguage, $sourceLanguage): ob

return json_decode($response->getBody()->getContents());
}

private function loadSupportedLanguages(): void
{
$cacheIdentifier = 'wv-deepl-supported-languages';
if (($supportedLanguages = $this->cache->get($cacheIdentifier)) === false) {
$supportedLanguages = $this->loadSupportedLanguagesFromAPI();

$this->cache->set($cacheIdentifier, $supportedLanguages, [], 86400);
}

foreach ($supportedLanguages as $supportedLanguage) {
$this->apiSupportedLanguages[] = $supportedLanguage['language'];
if ($supportedLanguage['supports_formality'] === true) {
$this->formalitySupportedLanguages[] = $supportedLanguage['language'];
}
}
}

private function loadSupportedLanguagesFromAPI(): array
{
$mainApiUrl = parse_url($this->apiUrl);
$languageApiUrl = sprintf(
'%s://%s/v2/languages?type=target',
$mainApiUrl['scheme'],
$mainApiUrl['host']
);

$headers = [
'Authorization' => sprintf('DeepL-Auth-Key %s', $this->apiKey),
];

try {
$response = $this->requestFactory->request($languageApiUrl, 'GET', [
'headers' => $headers,
]);
} catch (ClientException $e) {
$result = [];
$result['status'] = 'false';
$result['message'] = $e->getMessage();
$result = json_encode($result);
echo $result;
exit;
}

return json_decode($response->getBody()->getContents(), true);
}
}
9 changes: 9 additions & 0 deletions Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ services:

WebVision\WvDeepltranslate\Hooks\DataHandlerHook:
public: true

WebVision\WvDeepltranslate\Service\DeeplService:
arguments:
$cache: '@cache.wvdeepltranslate'

cache.wvdeepltranslate:
class: TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
factory: [ '@TYPO3\CMS\Core\Cache\CacheManager', 'getCache' ]
arguments: [ 'wvdeepltranslate' ]
15 changes: 15 additions & 0 deletions Tests/Functional/Fixtures/ExtensionConfig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

getenv('DEEPL_API_KEY') or die('Environment variable DEEPL_API_KEY is not set. Please set in local Context in ddev config.yaml');

return [
'EXTENSIONS' => [
'wv_deepltranslate' => [
'apiKey' => getenv('DEEPL_API_KEY') ?? '',
'apiUrl' => 'https://api-free.deepl.com/v2/translate',
'deeplFormality' => 'default',
'googleapiKey' => '',
'googleapiUrl' => 'https://translation.googleapis.com/language/translate/v2',
],
],
];
59 changes: 59 additions & 0 deletions Tests/Functional/Services/DeeplServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php declare(strict_types = 1);

namespace Functional\Services;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\TestingFramework\Core\Functional\FunctionalTestCase;
use WebVision\WvDeepltranslate\Service\DeeplService;

class DeeplServiceTest extends FunctionalTestCase
{
/**
* @var string[]
*/
protected $testExtensionsToLoad = [
'typo3conf/ext/wv_deepltranslate',
];

public function __construct()
{
parent::__construct();
$this->configurationToUseInTestInstance = array_merge(
$this->configurationToUseInTestInstance,
require __DIR__ . '/../Fixtures/ExtensionConfig.php'
);
}

protected function setUp(): void
{
parent::setUp();

$this->importDataSet(__DIR__ . '/../Fixtures/Settings.xml');
$this->importDataSet(__DIR__ . '/../Fixtures/Language.xml');
}

/**
* @test
*/
public function checkSupportedLanguages(): void
{
$deeplService = GeneralUtility::makeInstance(DeeplService::class);

static::assertContains('EN-GB', $deeplService->apiSupportedLanguages);
static::assertContains('EN-US', $deeplService->apiSupportedLanguages);
static::assertContains('DE', $deeplService->apiSupportedLanguages);
static::assertContains('UK', $deeplService->apiSupportedLanguages);
}

/**
* @test
*/
public function checkFormalitySupportedLanguages(): void
{
$deeplService = GeneralUtility::makeInstance(DeeplService::class);

static::assertContains('ES', $deeplService->formalitySupportedLanguages);
static::assertContains('DE', $deeplService->formalitySupportedLanguages);
static::assertContains('NL', $deeplService->formalitySupportedLanguages);
}
}
6 changes: 6 additions & 0 deletions ext_localconf.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,10 @@
);
}
}

//add caching for DeepL API supported Languages
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['wvdeepltranslate']
??= [];
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['wvdeepltranslate']['backend']
??= \TYPO3\CMS\Core\Cache\Backend\SimpleFileBackend::class;
})();

0 comments on commit 1bc7802

Please sign in to comment.