Skip to content

Commit

Permalink
Dispatch MissingTranslationCategoryEvent once per category (#74)
Browse files Browse the repository at this point in the history
* Dispatch `MissingTranslationCategoryEvent` once per category

* fix
  • Loading branch information
vjik committed Oct 17, 2022
1 parent aa4bd14 commit 6093538
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

## 1.1.2 under development

- Enh #74: Dispatch `MissingTranslationCategoryEvent` once per category (@vjik)
- Enh #73: Set `en_US` as default locale for translator (@vjik)
- Enh #72: Use `SimpleMessageFormatter` to format messages when missing translation category (@vjik)

Expand Down
20 changes: 17 additions & 3 deletions src/Translator.php
Expand Up @@ -27,6 +27,11 @@ final class Translator implements TranslatorInterface

private ?SimpleMessageFormatter $simpleMessageFormatter = null;

/**
* @psalm-var array<string,true>
*/
private array $dispatchedMissingTranslationCategoryEvents = [];

/**
* @param string $locale Default locale to use if locale is not specified explicitly.
* @param string|null $fallbackLocale Locale to use if message for the locale specified was not found. Null for none.
Expand Down Expand Up @@ -79,9 +84,7 @@ public function translate(
$category = $category ?? $this->defaultCategory;

if (empty($this->categorySources[$category])) {
if ($this->eventDispatcher !== null) {
$this->eventDispatcher->dispatch(new MissingTranslationCategoryEvent($category));
}
$this->dispatchMissingTranslationCategoryEvent($category);
return $this->getSimpleMessageFormatter()->format($id, $parameters);
}

Expand Down Expand Up @@ -146,6 +149,17 @@ private function translateUsingCategorySources(
return $categorySource->format($id, $parameters, $locale);
}

private function dispatchMissingTranslationCategoryEvent(string $category): void
{
if (
$this->eventDispatcher !== null
&& !isset($this->dispatchedMissingTranslationCategoryEvents[$category])
) {
$this->dispatchedMissingTranslationCategoryEvents[$category] = true;
$this->eventDispatcher->dispatch(new MissingTranslationCategoryEvent($category));
}
}

private function getSimpleMessageFormatter(): SimpleMessageFormatter
{
if ($this->simpleMessageFormatter === null) {
Expand Down
1 change: 1 addition & 0 deletions tests/TranslatorTest.php
Expand Up @@ -138,6 +138,7 @@ public function testWithoutDefaultCategoryMissingEvent(): void
$locale = 'en';
$translator = new Translator($locale, null, $eventDispatcher);
$this->assertEquals('Without translation', $translator->translate('Without translation'));
$this->assertEquals('Without translation 2', $translator->translate('Without translation 2'));
}

public function testMultiCategories(): void
Expand Down

0 comments on commit 6093538

Please sign in to comment.