Skip to content

Commit

Permalink
[FEATURE] Add Event for Glossary detection
Browse files Browse the repository at this point in the history
  • Loading branch information
calien666 committed Dec 18, 2024
1 parent 2a89749 commit 55f7748
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 51 deletions.
26 changes: 26 additions & 0 deletions Classes/Domain/Dto/CurrentPage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace WebVision\Deepltranslate\Core\Domain\Dto;

use WebVision\Deepltranslate\Core\Event\DeepLGlossaryIdEvent;

/**
* This class holds the current working page
* while processing inside the DataHandler
*
* It is the main entry point for extensions during events
* detecting the right page,
* for example, while detecting a glossary.
*
* @see DeepLGlossaryIdEvent for an usage example
*/
final class CurrentPage
{
public function __construct(
public readonly int $uid,
public readonly string $title
) {
}
}
28 changes: 28 additions & 0 deletions Classes/Event/DeepLGlossaryIdEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace WebVision\Deepltranslate\Core\Event;

use WebVision\Deepltranslate\Core\Domain\Dto\CurrentPage;

/**
* Entry point for external synchronized DeepL glossaries.
*
* The event is fired right before the translation handling from the DeepL translation.
* As entry, you get the source language, target language and the current page.
*
* Expects a string on parameter glossaryId. This ID is used for glossary-flavoured
* translation. No check for synchronized glossary, the ID is taken "AS IS".
*/
final class DeepLGlossaryIdEvent
{
public string $glossaryId = '';

public function __construct(
public readonly string $sourceLanguage,
public readonly string $targetLanguage,
public readonly ?CurrentPage $currentPage
) {
}
}
31 changes: 12 additions & 19 deletions Classes/Service/DeeplService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
use WebVision\Deepltranslate\Core\ClientInterface;
use WebVision\Deepltranslate\Core\Domain\Dto\TranslateContext;
use WebVision\Deepltranslate\Core\Domain\Repository\GlossaryRepository;
use WebVision\Deepltranslate\Core\Event\DeepLGlossaryIdEvent;
use WebVision\Deepltranslate\Core\Exception\ApiKeyNotSetException;
use WebVision\Deepltranslate\Core\Utility\DeeplBackendUtility;

final class DeeplService implements LoggerAwareInterface
{
use LoggerAwareTrait;

protected GlossaryRepository $glossaryRepository;

private FrontendInterface $cache;

private ClientInterface $client;
Expand All @@ -28,12 +27,11 @@ final class DeeplService implements LoggerAwareInterface
public function __construct(
FrontendInterface $cache,
ClientInterface $client,
GlossaryRepository $glossaryRepository,
ProcessingInstruction $processingInstruction
ProcessingInstruction $processingInstruction,
private readonly EventDispatcher $eventDispatcher
) {
$this->cache = $cache;
$this->client = $client;
$this->glossaryRepository = $glossaryRepository;
$this->processingInstruction = $processingInstruction;
}

Expand Down Expand Up @@ -61,22 +59,20 @@ public function translateRequest(
public function translateContent(TranslateContext $translateContext): string
{
if ($this->processingInstruction->isDeeplMode() === false) {
// @todo Can be replaced with `$this->logger?->` when TYPO3 v11 and therefore PHP 7.4/8.0 support is dropped.
if ($this->logger !== null) {
$this->logger->warning('DeepL mode not set. Exit.');
}
$this->logger?->warning('DeepL mode not set. Exit.');
return $translateContext->getContent();
}
// If the source language is set to Autodetect, no glossary can be detected.
if ($translateContext->getSourceLanguageCode() !== null) {
// @todo Make glossary findable by current site.
$glossary = $this->glossaryRepository->getGlossaryBySourceAndTarget(
$glossaryEvent = $this->eventDispatcher->dispatch(new DeepLGlossaryIdEvent(
$translateContext->getSourceLanguageCode(),
$translateContext->getTargetLanguageCode(),
DeeplBackendUtility::detectCurrentPage($this->processingInstruction)
);

$translateContext->setGlossaryId($glossary['glossary_id']);
));
$glossaryId = $glossaryEvent->glossaryId;
if ($glossaryId !== '') {
$translateContext->setGlossaryId($glossaryId);
}
}

try {
Expand All @@ -93,10 +89,7 @@ public function translateContent(TranslateContext $translateContext): string
}

if ($response === null) {
// @todo Can be replaced with `$this->logger?->` when TYPO3 v11 and therefore PHP 7.4/8.0 support is dropped.
if ($this->logger !== null) {
$this->logger->warning('Translation not successful');
}
$this->logger?->warning('Translation not successful');

return '';
}
Expand Down
58 changes: 26 additions & 32 deletions Classes/Utility/DeeplBackendUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,25 @@
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use WebVision\Deepltranslate\Core\Configuration;
use WebVision\Deepltranslate\Core\Domain\Dto\CurrentPage;
use WebVision\Deepltranslate\Core\Exception\LanguageIsoCodeNotFoundException;
use WebVision\Deepltranslate\Core\Exception\LanguageRecordNotFoundException;
use WebVision\Deepltranslate\Core\Service\IconOverlayGenerator;
use WebVision\Deepltranslate\Core\Service\LanguageService;
use WebVision\Deepltranslate\Core\Service\ProcessingInstruction;

// @todo Make class final. Overriding a static utility class does not make much sense, but better to enforce it.
class DeeplBackendUtility
/**
* Utility helper methods for DeepL-translate
*
* Main entry point for detecting API key and current working page
*/
final class DeeplBackendUtility
{
private static string $apiKey = '';

private static bool $configurationLoaded = false;

/**
* @var array{uid: int, title: string}|array<empty>
*/
protected static array $currentPage;
protected static ?CurrentPage $currentPage = null;

/**
* @return string
Expand Down Expand Up @@ -127,16 +129,6 @@ public static function buildBackendRoute(string $route, array $parameters): stri
return (string)$uriBuilder->buildUriFromRoute($route, $parameters);
}

/**
* @deprecated This function will no longer be used and will be removed in a later version please use it \WebVision\Deepltranslate\Core\Service\IconOverlayGenerator
* @see IconOverlayGenerator::get()
*/
public static function getIcon(string $iconFlag): Icon
{
$iconOverlayGenerator = GeneralUtility::makeInstance(IconOverlayGenerator::class);
return $iconOverlayGenerator->get($iconFlag);
}

/**
* ToDo: Migrated function to own class object "WebVision\Deepltranslate\Core\Form\TranslationDropdownGenerator"
*/
Expand Down Expand Up @@ -233,20 +225,11 @@ public static function checkCanBeTranslated(int $pageId, int $languageId): bool
return true;
}

private static function getBackendUserAuthentication(): BackendUserAuthentication
{
return $GLOBALS['BE_USER'];
}

/**
* @return array{uid: int, title: string}|array<empty>
*/
public static function detectCurrentPage(ProcessingInstruction $processingInstruction): array
public static function detectCurrentPage(ProcessingInstruction $processingInstruction): ?CurrentPage
{
self::$currentPage = [];

$pageId = null;
if ($processingInstruction->getProcessingTable() === 'pages') {
self::$currentPage = self::getPageRecord((int)$processingInstruction->getProcessingId());
$pageId = (int)$processingInstruction->getProcessingId();
} elseif (
$processingInstruction->getProcessingTable() !== null
&& strlen($processingInstruction->getProcessingTable()) > 0
Expand All @@ -256,23 +239,34 @@ public static function detectCurrentPage(ProcessingInstruction $processingInstru
(string)$processingInstruction->getProcessingTable(),
(int)$processingInstruction->getProcessingId()
);
self::$currentPage = self::getPageRecord($pageId);
}
if ($pageId !== null && $pageId > 0) {
$pageRecord = self::getPageRecord($pageId);
if ($pageRecord !== null) {
self::$currentPage = new CurrentPage((int)$pageRecord['uid'], (string)$pageRecord['title']);
}
}

return self::$currentPage;
}

private static function getBackendUserAuthentication(): BackendUserAuthentication
{
return $GLOBALS['BE_USER'];
}

/**
* @return array{uid: int, title: string}|array<empty>
* @return array{uid: int, title: string}|null
*/
private static function getPageRecord(int $id): array
private static function getPageRecord(int $id): ?array
{
/** @var array{uid: int, title: string}|null $page */
$page = BackendUtility::getRecord(
'pages',
$id,
'uid, title'
);
return $page ?? [];
return $page;
}

private static function getPageIdFromRecord(string $table, int $id): int
Expand Down

0 comments on commit 55f7748

Please sign in to comment.