Skip to content

Commit

Permalink
Merge pull request #4 from vildanbina/detached
Browse files Browse the repository at this point in the history
Refactor TranslationsManager
  • Loading branch information
vildanbina authored Dec 28, 2024
2 parents 8083526 + 6cd18a3 commit 37a4f6d
Show file tree
Hide file tree
Showing 9 changed files with 204 additions and 135 deletions.
33 changes: 31 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,35 @@ php artisan translate:default fr --driver=deepl --overwrite
- `--driver` (Optional) – Translation driver; defaults to config value.
- `--overwrite` (Optional) – Whether to overwrite existing translations.

### 3. Using In-Memory Texts (If Applicable)

In addition to scanning and translating language files, you can programmatically set texts directly in memory. This is useful for scenarios where you want to translate specific texts without relying on language files.

**Example:**

~~~php
use VildanBina\LaravelAutoTranslation\TranslationWorkflowService;
use VildanBina\LaravelAutoTranslation\Services\TranslationEngineService;

// Assume $translationEngineService is an instance of TranslationEngineService
$translationWorkflowService = new TranslationWorkflowService($translationEngineService);

// Define texts to translate
$texts = [
'welcome.message' => 'Welcome to our application!',
'user.greeting' => 'Hello, :name!',
];

// Set texts in memory
$translationWorkflowService->setInMemoryTexts($texts);

// Perform translation
$translatedTexts = $translationWorkflowService->translate('en', 'fr', 'deepl');

// Output translated texts
print_r($translatedTexts);
~~~

## Custom Drivers

To add a custom driver, follow these steps:
Expand All @@ -141,6 +170,7 @@ To add a custom driver, follow these steps:
}
}
~~~

2. **Register the driver in `auto-translations.php`**:
~~~php
'drivers' => [
Expand All @@ -162,7 +192,7 @@ To add a custom driver, follow these steps:
- **ChatGPT**: Flexible and context-aware translations.
- **Google Translate**: Fast and reliable.
- **DeepL**: Known for accurate translations, especially for European languages.
- **[New] Custom Driver**: Extendable for your own APIs or offline services.
- **Custom Driver**: Extendable for your own APIs or offline services.

## Contributing

Expand All @@ -180,4 +210,3 @@ Please e-mail vildanbina@gmail.com to report any security vulnerabilities instea
## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"automation"
],
"license": "MIT",
"version": "1.1.0",
"version": "1.2.0",
"authors": [
{
"name": "Vildan Bina",
Expand Down
4 changes: 2 additions & 2 deletions src/Commands/ScanTextCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

use Exception;
use Illuminate\Console\Command;
use VildanBina\LaravelAutoTranslation\TranslationsManager;
use VildanBina\LaravelAutoTranslation\TranslationWorkflowService;

class ScanTextCommand extends Command
{
protected $signature = 'translate:scan
{--lang= : Source language code (defaults to config value)}';
protected $description = 'Scan language files in lang_path and prepare strings for translation';

public function handle(TranslationsManager $manager): void
public function handle(TranslationWorkflowService $manager): void
{
try {
$sourceLang = $this->option('lang') ?: config('auto-translations.source_language');
Expand Down
4 changes: 2 additions & 2 deletions src/Commands/TranslateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use Exception;
use Illuminate\Console\Command;
use VildanBina\LaravelAutoTranslation\TranslationsManager;
use VildanBina\LaravelAutoTranslation\TranslationWorkflowService;

class TranslateCommand extends Command
{
Expand All @@ -15,7 +15,7 @@ class TranslateCommand extends Command
{--overwrite : Overwrite existing translations}';
protected $description = 'Translate language strings to another language using a specified driver.';

public function handle(TranslationsManager $manager): void
public function handle(TranslationWorkflowService $manager): void
{
$targetLang = $this->argument('target_lang');
$sourceLang = $this->option('source_lang') ?: config('auto-translations.source_language');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use VildanBina\LaravelAutoTranslation\Drivers\DeepLDriver;
use VildanBina\LaravelAutoTranslation\Drivers\GoogleTranslateDriver;

class TranslationService
class TranslationEngineService
{
private $drivers = [];

Expand Down
157 changes: 157 additions & 0 deletions src/TranslationWorkflowService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

namespace VildanBina\LaravelAutoTranslation;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use VildanBina\LaravelAutoTranslation\Services\TranslationEngineService;

class TranslationWorkflowService
{
protected array $inMemoryTexts;

protected TranslationEngineService $service;

public function __construct(TranslationEngineService $service)
{
$this->service = $service;
}

public function setInMemoryTexts(array $texts): static
{
$this->inMemoryTexts = $texts;

return $this;
}

public function scanLanguageFiles(string $lang): void
{
$texts = $this->loadLanguageFiles($lang);
$this->storeTextsForTranslation($texts);
}

/**
* Translates the loaded texts from source language to target language.
*
* @param string $sourceLang The source language code.
* @param string $targetLang The target language code.
* @param string $driver The translation driver to use.
* @param bool $overwrite Whether to overwrite existing translations.
* @return array Returns translated texts.
*
* @throws Exception If translation files are missing or invalid.
*/
public function translate(string $sourceLang, string $targetLang, string $driver, bool $overwrite = false): array
{
$texts = $this->loadTexts();
$translated = $this->service->translate($texts, $sourceLang, $targetLang, $driver);

if (isset($this->inMemoryTexts)) {
return $translated;
}

$this->saveTranslated($translated, $targetLang, $overwrite);

return $translated;
}

/**
* Stores the gathered texts to a JSON file for translation.
*
* @param array $texts The array of texts to store.
*/
private function storeTextsForTranslation(array $texts): void
{
$langPath = config('auto-translations.lang_path');
$filePath = "{$langPath}/texts_to_translate.json";
ksort($texts);
File::put($filePath, json_encode($texts, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

/**
* Loads texts either from in-memory storage or from the translation file.
*
* @return array The array of texts to be translated.
*
* @throws Exception If the translation file does not exist or has invalid format.
*/
private function loadTexts(): array
{
if (isset($this->inMemoryTexts)) {
return $this->inMemoryTexts;
}

$file = config('auto-translations.lang_path').'/texts_to_translate.json';
if (! File::exists($file)) {
throw new Exception("No texts found. Run 'translate:scan' first.");
}

$contents = json_decode(File::get($file), true);
if (! is_array($contents)) {
throw new Exception("Invalid format in 'texts_to_translate.json'.");
}

return $contents;
}

/**
* Loads all language strings from JSON and PHP language files.
*
* @param string $lang The language code to load.
* @return array The array of loaded language strings.
*/
private function loadLanguageFiles(string $lang): array
{
$dir = config('auto-translations.lang_path');
$texts = [];

$jsonFile = "{$dir}/{$lang}.json";
if (File::exists($jsonFile)) {
$jsonData = json_decode(File::get($jsonFile), true);
if (is_array($jsonData)) {
$texts = array_merge($texts, $jsonData);
}
}

$langDir = "{$dir}/{$lang}";
if (File::isDirectory($langDir)) {
foreach (File::allFiles($langDir) as $file) {
if ($file->getExtension() === 'php') {
$subKey = str_replace(['/', '.php'], ['.', ''], $file->getRelativePathname());
$array = include $file->getPathname();
if (is_array($array)) {
$flattened = Arr::dot([$subKey => $array]);
$texts = array_merge($texts, $flattened);

}
}
}
}

return $texts;
}

/**
* Saves the translated texts to the target language file.
*
* @param array $translated The array of translated texts.
* @param string $lang The target language code.
* @param bool $overwrite Whether to overwrite existing translations.
*/
private function saveTranslated(array $translated, string $lang, bool $overwrite): void
{
$file = config('auto-translations.lang_path')."/{$lang}.json";
$existing = [];

if (File::exists($file)) {
$existing = json_decode(File::get($file), true) ?: [];
}

if (! $overwrite) {
$translated = array_merge($existing, $translated);
}

File::put($file, json_encode($translated, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}
117 changes: 0 additions & 117 deletions src/TranslationsManager.php

This file was deleted.

Loading

0 comments on commit 37a4f6d

Please sign in to comment.