From 60ca47af2b1ce317b6cc7eef255600edc2d9668b Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Thu, 18 Sep 2025 12:11:24 +1000 Subject: [PATCH 01/21] docs: revise docs for PHP SDK --- src/LingoDotDevEngine.php | 146 +++++++++++++++++++++++++------------- test-all-methods.php | 11 +++ 2 files changed, 107 insertions(+), 50 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index ea26a91..679f58b 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -16,9 +16,11 @@ use Respect\Validation\Validator as v; /** - * LingoDotDevEngine class for interacting with the LingoDotDev API - * A powerful localization engine that supports various content types including - * plain text, objects, and chat sequences. + * LingoDotDevEngine wraps the Lingo.dev localization API for PHP consumers. + * + * Use a single engine instance to translate strings, arrays, and chat logs, or + * to detect the locale of free-form text. The engine handles request batching, + * progress reporting, and surfacing validation or transport errors. * * @category Localization * @package Lingodotdev\Sdk @@ -43,9 +45,17 @@ class LingoDotDevEngine private $_httpClient; /** - * Create a new LingoDotDevEngine instance - * - * @param array $config Configuration options for the Engine + * Build an engine instance with your API key and optional batch settings. + * + * Provide at least ['apiKey' => '...']. You may override: + * - 'apiUrl' with a valid base URL for the service (defaults to https://engine.lingo.dev). + * - 'batchSize' with an integer between 1 and 250 to control items sent per request. + * - 'idealBatchItemSize' with an integer between 1 and 2500 to cap words per request. + * Invalid values trigger \InvalidArgumentException. + * + * @param array $config HTTP client credentials and optional batching overrides. + * + * @throws \InvalidArgumentException When the API key is missing or a value fails validation. */ public function __construct(array $config = []) { @@ -280,16 +290,24 @@ private function _createId(): string } /** - * Localize a typical PHP array or object - * - * @param array $obj The object to be localized (strings will be extracted and translated) - * @param array $params Localization parameters: - * - sourceLocale: The source language code (e.g., 'en') - * - targetLocale: The target language code (e.g., 'es') - * - fast: Optional boolean to enable fast mode - * @param callable|null $progressCallback Optional callback function to report progress (0-100) - * - * @return array A new object with the same structure but localized string values + * Localize every string in a nested array while keeping the array structure. + * + * Require $params['targetLocale'] with the desired language code. Optionally + * pass: + * - 'sourceLocale' with the current language code (string or null). + * - 'fast' with a boolean forwarded to the API. + * - 'reference' with an array of supplemental data forwarded unchanged. + * The optional callback receives (int $progress, array $chunk, array $localizedChunk) + * for each batch the engine submits. + * + * @param array $obj Input data whose string entries should be localized. + * @param array $params Request parameters for locales and API options. + * @param callable|null $progressCallback Progress hook fired per batch. + * + * @return array Localized data mirroring the original structure. + * + * @throws \InvalidArgumentException When required params or reference data are invalid. + * @throws \RuntimeException When the API rejects or fails to process the request. */ public function localizeObject(array $obj, array $params, ?callable $progressCallback = null): array { @@ -305,16 +323,24 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal } /** - * Localize a single text string - * - * @param string $text The text string to be localized - * @param array $params Localization parameters: - * - sourceLocale: The source language code (e.g., 'en') - * - targetLocale: The target language code (e.g., 'es') - * - fast: Optional boolean to enable fast mode - * @param callable|null $progressCallback Optional callback function to report progress (0-100) - * - * @return string The localized text string + * Translate a single string and return the localized text. + * + * Set $params['targetLocale'] to the destination language code. You may + * also provide: + * - 'sourceLocale' with the existing language code (string or null). + * - 'fast' with a boolean forwarded to the API. + * - 'reference' with an array of supplemental data forwarded unchanged. + * The optional callback receives the completion percentage (0-100) for each + * processed batch. + * + * @param string $text Source text to localize. + * @param array $params Request parameters for locales and API options. + * @param callable|null $progressCallback Progress hook fired with an integer percentage. + * + * @return string Localized text (empty string if the API omits the field). + * + * @throws \InvalidArgumentException When required params are missing or invalid. + * @throws \RuntimeException When the API rejects or fails to process the request. */ public function localizeText(string $text, array $params, ?callable $progressCallback = null): string { @@ -332,15 +358,20 @@ public function localizeText(string $text, array $params, ?callable $progressCal } /** - * Localize a text string to multiple target locales - * - * @param string $text The text string to be localized - * @param array $params Localization parameters: - * - sourceLocale: The source language code (e.g., 'en') - * - targetLocales: An array of target language codes (e.g., ['es', 'fr']) - * - fast: Optional boolean to enable fast mode - * - * @return array An array of localized text strings + * Translate a string into several languages and return the results in order. + * + * Expect $params['sourceLocale'] with the language code of the input text + * and $params['targetLocales'] with an array of destination language codes. + * Optional 'fast' flags are forwarded to each {@see localizeText()} call. + * Any failure from an individual request surfaces immediately. + * + * @param string $text Source text to localize. + * @param array $params Request parameters describing the source and target languages. + * + * @return array List of localized strings matching the order of target locales. + * + * @throws \InvalidArgumentException When required params are missing or invalid. + * @throws \RuntimeException When an individual localization request fails. */ public function batchLocalizeText(string $text, array $params): array { @@ -367,16 +398,25 @@ public function batchLocalizeText(string $text, array $params): array } /** - * Localize a chat sequence while preserving speaker names - * - * @param array $chat Array of chat messages, each with 'name' and 'text' properties - * @param array $params Localization parameters: - * - sourceLocale: The source language code (e.g., 'en') - * - targetLocale: The target language code (e.g., 'es') - * - fast: Optional boolean to enable fast mode - * @param callable|null $progressCallback Optional callback function to report progress (0-100) - * - * @return array Array of localized chat messages with preserved structure + * Localize a chat transcript while keeping speaker names untouched. + * + * Each entry in $chat must provide 'name' and 'text'. Supply + * $params['targetLocale'] with the destination language code. Optionally + * pass: + * - 'sourceLocale' with the current language code (string or null). + * - 'fast' with a boolean forwarded to the API. + * - 'reference' with an array of supplemental data forwarded unchanged. + * The optional callback receives the completion percentage (0-100) for each + * processed batch. + * + * @param array $chat Ordered list of chat message arrays with 'name' and 'text'. + * @param array $params Request parameters for locales and API options. + * @param callable|null $progressCallback Progress hook fired with an integer percentage. + * + * @return array Localized chat messages with original names preserved. + * + * @throws \InvalidArgumentException When chat entries or params are invalid. + * @throws \RuntimeException When the API rejects or fails to process the request. */ public function localizeChat(array $chat, array $params, ?callable $progressCallback = null): array { @@ -408,11 +448,17 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall } /** - * Detect the language of a given text - * - * @param string $text The text to analyze - * - * @return string Locale code (e.g., 'en', 'es', 'fr') + * Ask the API to identify the locale of the provided text. + * + * Whitespace-only strings are rejected. On success the API's 'locale' + * field is returned directly. + * + * @param string $text Text whose locale should be recognised. + * + * @return string Locale code provided by the API. + * + * @throws \InvalidArgumentException When the input text is blank after trimming. + * @throws \RuntimeException When the API response is invalid or the request fails. */ public function recognizeLocale(string $text): string { diff --git a/test-all-methods.php b/test-all-methods.php index abe2c5f..e248748 100644 --- a/test-all-methods.php +++ b/test-all-methods.php @@ -24,6 +24,17 @@ "apiKey" => $apiKey, ]); +/** + * Execute a CLI test callback, reporting success or failure to stdout. + * + * Prints the section header, runs the callback, dumps the JSON-encoded result + * when successful, or surfaces exception details (including HTTP responses). + * + * @param string $name Human-readable test name displayed in logs. + * @param callable $callback Zero-argument function returning the test result. + * + * @return bool True on success, false on failure. + */ function runTest($name, $callback) { echo "\n=== Testing $name ===\n"; try { From 274424cd591d06452404289791817c1d01dc43e8 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:00:23 +1000 Subject: [PATCH 02/21] docs: updates --- src/LingoDotDevEngine.php | 192 +++++++++++++++----------------- test-all-methods.php | 19 ++-- tests/LingoDotDevEngineTest.php | 28 ++--- 3 files changed, 110 insertions(+), 129 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index 679f58b..aae7a2f 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -31,31 +31,29 @@ class LingoDotDevEngine { /** - * Configuration options for the Engine + * Configuration options for the Engine. * - * @var array + * @var array */ protected $config; /** - * HTTP client for API requests + * HTTP client for API requests. * * @var Client */ private $_httpClient; /** - * Build an engine instance with your API key and optional batch settings. + * Build an engine with your API key and optional batching limits. * - * Provide at least ['apiKey' => '...']. You may override: - * - 'apiUrl' with a valid base URL for the service (defaults to https://engine.lingo.dev). - * - 'batchSize' with an integer between 1 and 250 to control items sent per request. - * - 'idealBatchItemSize' with an integer between 1 and 2500 to cap words per request. - * Invalid values trigger \InvalidArgumentException. + * @param array $config Configuration options: + * - 'apiKey' (string, required): Your API token + * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) + * - 'batchSize' (int): Records per request, 1-250 (default: 25) + * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) * - * @param array $config HTTP client credentials and optional batching overrides. - * - * @throws \InvalidArgumentException When the API key is missing or a value fails validation. + * @throws \InvalidArgumentException When API key is missing or values fail validation */ public function __construct(array $config = []) { @@ -95,13 +93,14 @@ public function __construct(array $config = []) } /** - * Localize content using the Lingo.dev API - * - * @param array $payload The content to be localized - * @param array $params Localization parameters including source/target locales and fast mode option - * @param callable|null $progressCallback Optional callback function to report progress (0-100) - * - * @return array Localized content + * Localize content using the Lingo.dev API. + * + * @param array $payload Content to translate, structured as key-value pairs + * @param array $params Translation configuration options + * @param callable(int, mixed, mixed): void|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk + * + * @return array Translated content maintaining original structure + * * @internal */ protected function localizeRaw(array $payload, array $params, ?callable $progressCallback = null): array @@ -149,15 +148,18 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres } /** - * Localize a single chunk of content - * - * @param string|null $sourceLocale Source locale - * @param string $targetLocale Target locale - * @param array $payload Payload containing the chunk to be localized - * @param string $workflowId Workflow ID - * @param bool $fast Whether to use fast mode - * - * @return array Localized chunk + * Localize a single chunk of content. + * + * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection + * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') + * @param array $payload Content chunk with optional reference data for context + * @param string $workflowId Unique identifier for tracking related translation requests + * @param bool $fast Enable faster translation at potential quality tradeoff + * + * @return array Translated chunk maintaining original structure + * + * @throws \InvalidArgumentException When reference is not an array + * @throws \RuntimeException When API request fails */ private function _localizeChunk(?string $sourceLocale, string $targetLocale, array $payload, string $workflowId, bool $fast): array { @@ -214,11 +216,11 @@ private function _localizeChunk(?string $sourceLocale, string $targetLocale, arr } /** - * Extract payload chunks based on the ideal chunk size - * - * @param array $payload The payload to be chunked - * - * @return array An array of payload chunks + * Extract payload chunks based on the ideal chunk size. + * + * @param array $payload The payload to be chunked + * + * @return array> Array of payload chunks */ private function _extractPayloadChunks(array $payload): array { @@ -252,11 +254,11 @@ private function _extractPayloadChunks(array $payload): array } /** - * Count words in a record or array - * + * Count words in a record or array. + * * @param mixed $payload The payload to count words in - * - * @return int The total number of words + * + * @return int Total number of words */ private function _countWordsInRecord($payload): int { @@ -280,8 +282,8 @@ private function _countWordsInRecord($payload): int } /** - * Generate a unique ID - * + * Generate a unique ID. + * * @return string Unique ID */ private function _createId(): string @@ -290,24 +292,20 @@ private function _createId(): string } /** - * Localize every string in a nested array while keeping the array structure. - * - * Require $params['targetLocale'] with the desired language code. Optionally - * pass: - * - 'sourceLocale' with the current language code (string or null). - * - 'fast' with a boolean forwarded to the API. - * - 'reference' with an array of supplemental data forwarded unchanged. - * The optional callback receives (int $progress, array $chunk, array $localizedChunk) - * for each batch the engine submits. + * Localize every string in a nested array while keeping its shape intact. * - * @param array $obj Input data whose string entries should be localized. - * @param array $params Request parameters for locales and API options. - * @param callable|null $progressCallback Progress hook fired per batch. + * @param array $obj Nested data structure containing text to translate + * @param array $params Parameters: + * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection + * - 'fast' (bool): Trade translation quality for speed + * - 'reference' (array): Context or glossary terms to guide translation + * @param callable(int, mixed, mixed): void|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * - * @return array Localized data mirroring the original structure. + * @return array Translated data preserving original structure and non-text values * - * @throws \InvalidArgumentException When required params or reference data are invalid. - * @throws \RuntimeException When the API rejects or fails to process the request. + * @throws \InvalidArgumentException When required params or reference data are invalid + * @throws \RuntimeException When API rejects or fails to process the request */ public function localizeObject(array $obj, array $params, ?callable $progressCallback = null): array { @@ -323,24 +321,20 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal } /** - * Translate a single string and return the localized text. + * Localize a single string and return the translated text. * - * Set $params['targetLocale'] to the destination language code. You may - * also provide: - * - 'sourceLocale' with the existing language code (string or null). - * - 'fast' with a boolean forwarded to the API. - * - 'reference' with an array of supplemental data forwarded unchanged. - * The optional callback receives the completion percentage (0-100) for each - * processed batch. + * @param string $text Text content to translate + * @param array $params Parameters: + * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection + * - 'fast' (bool): Prioritize speed over translation quality + * - 'reference' (array): Context, terminology, or style guidelines for translation + * @param callable(int): void|null $progressCallback Called with completion percentage (0-100) during processing * - * @param string $text Source text to localize. - * @param array $params Request parameters for locales and API options. - * @param callable|null $progressCallback Progress hook fired with an integer percentage. + * @return string Translated text, or empty string if translation unavailable * - * @return string Localized text (empty string if the API omits the field). - * - * @throws \InvalidArgumentException When required params are missing or invalid. - * @throws \RuntimeException When the API rejects or fails to process the request. + * @throws \InvalidArgumentException When required params are missing or invalid + * @throws \RuntimeException When API rejects or fails to process the request */ public function localizeText(string $text, array $params, ?callable $progressCallback = null): string { @@ -358,20 +352,18 @@ public function localizeText(string $text, array $params, ?callable $progressCal } /** - * Translate a string into several languages and return the results in order. - * - * Expect $params['sourceLocale'] with the language code of the input text - * and $params['targetLocales'] with an array of destination language codes. - * Optional 'fast' flags are forwarded to each {@see localizeText()} call. - * Any failure from an individual request surfaces immediately. + * Localize a string into multiple languages and return texts in order. * - * @param string $text Source text to localize. - * @param array $params Request parameters describing the source and target languages. + * @param string $text Text content to translate into multiple languages + * @param array $params Parameters: + * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') + * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) + * - 'fast' (bool): Apply speed optimization to all translations * - * @return array List of localized strings matching the order of target locales. + * @return string[] Array of translated texts in same order as targetLocales parameter * - * @throws \InvalidArgumentException When required params are missing or invalid. - * @throws \RuntimeException When an individual localization request fails. + * @throws \InvalidArgumentException When required params are missing or invalid + * @throws \RuntimeException When an individual localization request fails */ public function batchLocalizeText(string $text, array $params): array { @@ -398,25 +390,20 @@ public function batchLocalizeText(string $text, array $params): array } /** - * Localize a chat transcript while keeping speaker names untouched. + * Localize a chat transcript while preserving speaker names. * - * Each entry in $chat must provide 'name' and 'text'. Supply - * $params['targetLocale'] with the destination language code. Optionally - * pass: - * - 'sourceLocale' with the current language code (string or null). - * - 'fast' with a boolean forwarded to the API. - * - 'reference' with an array of supplemental data forwarded unchanged. - * The optional callback receives the completion percentage (0-100) for each - * processed batch. + * @param array $chat Conversation history with speaker names and their messages + * @param array $params Parameters: + * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language of original messages, null for auto-detection + * - 'fast' (bool): Optimize for speed over translation quality + * - 'reference' (array): Conversation context or domain-specific terminology + * @param callable(int): void|null $progressCallback Called with completion percentage (0-100) during processing * - * @param array $chat Ordered list of chat message arrays with 'name' and 'text'. - * @param array $params Request parameters for locales and API options. - * @param callable|null $progressCallback Progress hook fired with an integer percentage. + * @return array Translated messages keeping original speaker names unchanged * - * @return array Localized chat messages with original names preserved. - * - * @throws \InvalidArgumentException When chat entries or params are invalid. - * @throws \RuntimeException When the API rejects or fails to process the request. + * @throws \InvalidArgumentException When chat entries or params are invalid + * @throws \RuntimeException When API rejects or fails to process the request */ public function localizeChat(array $chat, array $params, ?callable $progressCallback = null): array { @@ -448,17 +435,14 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall } /** - * Ask the API to identify the locale of the provided text. - * - * Whitespace-only strings are rejected. On success the API's 'locale' - * field is returned directly. + * Identify the locale of the provided text. * - * @param string $text Text whose locale should be recognised. + * @param string $text Sample text for language detection (longer text improves accuracy) * - * @return string Locale code provided by the API. + * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') * - * @throws \InvalidArgumentException When the input text is blank after trimming. - * @throws \RuntimeException When the API response is invalid or the request fails. + * @throws \InvalidArgumentException When input text is blank after trimming + * @throws \RuntimeException When API response is invalid or request fails */ public function recognizeLocale(string $text): string { diff --git a/test-all-methods.php b/test-all-methods.php index e248748..eca1710 100644 --- a/test-all-methods.php +++ b/test-all-methods.php @@ -1,10 +1,10 @@ */ @@ -27,13 +27,10 @@ /** * Execute a CLI test callback, reporting success or failure to stdout. * - * Prints the section header, runs the callback, dumps the JSON-encoded result - * when successful, or surfaces exception details (including HTTP responses). - * - * @param string $name Human-readable test name displayed in logs. - * @param callable $callback Zero-argument function returning the test result. + * @param string $name Human-readable test name displayed in logs + * @param callable(): mixed $callback Zero-argument function returning the test result * - * @return bool True on success, false on failure. + * @return bool True on success, false on failure */ function runTest($name, $callback) { echo "\n=== Testing $name ===\n"; diff --git a/tests/LingoDotDevEngineTest.php b/tests/LingoDotDevEngineTest.php index 59bd1ee..6aacc60 100644 --- a/tests/LingoDotDevEngineTest.php +++ b/tests/LingoDotDevEngineTest.php @@ -1,6 +1,6 @@ Date: Fri, 19 Sep 2025 10:02:02 +1000 Subject: [PATCH 03/21] chore: revert --- test-all-methods.php | 18 +++++------------- tests/LingoDotDevEngineTest.php | 28 ++++++++++++++-------------- 2 files changed, 19 insertions(+), 27 deletions(-) diff --git a/test-all-methods.php b/test-all-methods.php index eca1710..abe2c5f 100644 --- a/test-all-methods.php +++ b/test-all-methods.php @@ -1,10 +1,10 @@ */ @@ -24,14 +24,6 @@ "apiKey" => $apiKey, ]); -/** - * Execute a CLI test callback, reporting success or failure to stdout. - * - * @param string $name Human-readable test name displayed in logs - * @param callable(): mixed $callback Zero-argument function returning the test result - * - * @return bool True on success, false on failure - */ function runTest($name, $callback) { echo "\n=== Testing $name ===\n"; try { diff --git a/tests/LingoDotDevEngineTest.php b/tests/LingoDotDevEngineTest.php index 6aacc60..59bd1ee 100644 --- a/tests/LingoDotDevEngineTest.php +++ b/tests/LingoDotDevEngineTest.php @@ -1,6 +1,6 @@ Date: Fri, 19 Sep 2025 10:20:04 +1000 Subject: [PATCH 04/21] feat: github action --- .github/workflows/generate-docs.yml | 49 +++++++++++++++++++++++++++++ .gitignore | 1 + composer.json | 11 +++++-- src/LingoDotDevEngine.php | 8 ++--- 4 files changed, 63 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/generate-docs.yml diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml new file mode 100644 index 0000000..5ebbbc9 --- /dev/null +++ b/.github/workflows/generate-docs.yml @@ -0,0 +1,49 @@ +name: Generate Markdown Docs + +on: + push: + branches: + - '*' + workflow_dispatch: + +permissions: + contents: write + +jobs: + generate: + if: github.actor != 'github-actions[bot]' + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.1' + extensions: mbstring, intl + coverage: none + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-interaction --no-progress + + - name: Generate Markdown documentation + run: vendor/bin/phpdoc --directory=src --target=docs --template="vendor/saggre/phpdocumentor-markdown/themes/markdown" + + - name: Commit and push updates + run: | + STATUS=$(git status --short docs) + if [ -z "$STATUS" ]; then + echo "Documentation already up to date" + exit 0 + fi + + echo "Docs updated, committing changes" + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add docs + git commit -m "docs: update markdown API reference [skip ci]" + git push diff --git a/.gitignore b/.gitignore index e102943..c93f120 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .env /demo/vendor/ /demo/composer.lock +.phpdoc/cache \ No newline at end of file diff --git a/composer.json b/composer.json index 2399fef..fdaf1a1 100644 --- a/composer.json +++ b/composer.json @@ -12,10 +12,12 @@ "require": { "php": "^8.1", "guzzlehttp/guzzle": "^7.0", - "respect/validation": "^2.0" + "respect/validation": "^2.0", + "phpdocumentor/shim": "^3.8" }, "require-dev": { - "phpunit/phpunit": "^9.0" + "phpunit/phpunit": "^9.0", + "saggre/phpdocumentor-markdown": "^1.0" }, "autoload": { "psr-4": { @@ -26,5 +28,10 @@ "psr-4": { "LingoDotDev\\Sdk\\Tests\\": "tests/" } + }, + "config": { + "allow-plugins": { + "phpdocumentor/shim": true + } } } diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index aae7a2f..a1e55c7 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -97,7 +97,7 @@ public function __construct(array $config = []) * * @param array $payload Content to translate, structured as key-value pairs * @param array $params Translation configuration options - * @param callable(int, mixed, mixed): void|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk + * @param null|callable(int, mixed, mixed): void $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk * * @return array Translated content maintaining original structure * @@ -300,7 +300,7 @@ private function _createId(): string * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array): Context or glossary terms to guide translation - * @param callable(int, mixed, mixed): void|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) + * @param null|callable(int, mixed, mixed): void $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * * @return array Translated data preserving original structure and non-text values * @@ -329,7 +329,7 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Prioritize speed over translation quality * - 'reference' (array): Context, terminology, or style guidelines for translation - * @param callable(int): void|null $progressCallback Called with completion percentage (0-100) during processing + * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * * @return string Translated text, or empty string if translation unavailable * @@ -398,7 +398,7 @@ public function batchLocalizeText(string $text, array $params): array * - 'sourceLocale' (string|null): Language of original messages, null for auto-detection * - 'fast' (bool): Optimize for speed over translation quality * - 'reference' (array): Conversation context or domain-specific terminology - * @param callable(int): void|null $progressCallback Called with completion percentage (0-100) during processing + * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * * @return array Translated messages keeping original speaker names unchanged * From 4ab9e07edae052769502fd9176041f659884cb35 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 00:20:26 +0000 Subject: [PATCH 05/21] docs: update markdown API reference [skip ci] --- docs/Home.md | 12 + .../LingoDotDev/Sdk/LingoDotDevEngine.md | 305 ++++++++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 docs/Home.md create mode 100644 docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..8fa6bd8 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,12 @@ + +This is an automatically generated documentation for **Documentation**. + +## Namespaces + +### \LingoDotDev\Sdk + +#### Classes + +| Class | Description | +|--------------------------------------------------------------------|---------------------------------------------------------------------------| +| [`LingoDotDevEngine`](./classes/LingoDotDev/Sdk/LingoDotDevEngine) | LingoDotDevEngine wraps the Lingo.dev localization API for PHP consumers. | diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md new file mode 100644 index 0000000..fb2bc78 --- /dev/null +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -0,0 +1,305 @@ + +LingoDotDevEngine wraps the Lingo.dev localization API for PHP consumers. + +Use a single engine instance to translate strings, arrays, and chat logs, or +to detect the locale of free-form text. The engine handles request batching, +progress reporting, and surfacing validation or transport errors. + +*** + +* Full name: `\LingoDotDev\Sdk\LingoDotDevEngine` + +**See Also:** + +* https://lingo.dev + +## Properties + +### config + +Configuration options for the Engine. + +```php +protected array $config +``` + +*** + +### _httpClient + +HTTP client for API requests. + +```php +private \GuzzleHttp\Client $_httpClient +``` + +*** + +## Methods + +### __construct + +Build an engine with your API key and optional batching limits. + +```php +public __construct(array $config = []): mixed +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$config` | **array** | Configuration options: +- 'apiKey' (string, required): Your API token +- 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) +- 'batchSize' (int): Records per request, 1-250 (default: 25) +- 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) | + +**Throws:** + +When API key is missing or values fail validation +- [`InvalidArgumentException`](../../InvalidArgumentException) + +*** + +### _localizeChunk + +Localize a single chunk of content. + +```php +private _localizeChunk(string|null $sourceLocale, string $targetLocale, array $payload, string $workflowId, bool $fast): array +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------------|-------------------------|--------------------------------------------------------------------------------| +| `$sourceLocale` | **string\|null** | Language code of the original text (e.g., 'en', 'es'), null for auto-detection | +| `$targetLocale` | **string** | Language code to translate into (e.g., 'fr', 'de') | +| `$payload` | **array** | Content chunk with optional reference data for context | +| `$workflowId` | **string** | Unique identifier for tracking related translation requests | +| `$fast` | **bool** | Enable faster translation at potential quality tradeoff | + +**Return Value:** + +Translated chunk maintaining original structure + +**Throws:** + +When reference is not an array +- [`InvalidArgumentException`](../../InvalidArgumentException) +When API request fails +- [`RuntimeException`](../../RuntimeException) + +*** + +### _extractPayloadChunks + +Extract payload chunks based on the ideal chunk size. + +```php +private _extractPayloadChunks(array $payload): array> +``` + +**Parameters:** + +| Parameter | Type | Description | +|------------|-------------------------|---------------------------| +| `$payload` | **array** | The payload to be chunked | + +**Return Value:** + +Array of payload chunks + +*** + +### _countWordsInRecord + +Count words in a record or array. + +```php +private _countWordsInRecord(mixed $payload): int +``` + +**Parameters:** + +| Parameter | Type | Description | +|------------|-----------|-------------------------------| +| `$payload` | **mixed** | The payload to count words in | + +**Return Value:** + +Total number of words + +*** + +### _createId + +Generate a unique ID. + +```php +private _createId(): string +``` + +**Return Value:** + +Unique ID + +*** + +### localizeObject + +Localize every string in a nested array while keeping its shape intact. + +```php +public localizeObject(array $obj, array $params, null|callable $progressCallback = null): array +``` + +**Parameters:** + +| Parameter | Type | Description | +|---------------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$obj` | **array** | Nested data structure containing text to translate | +| `$params` | **array** | Parameters: +- 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') +- 'sourceLocale' (string\|null): Language code of original text, null for auto-detection +- 'fast' (bool): Trade translation quality for speed +- 'reference' (array): Context or glossary terms to guide translation | +| `$progressCallback` | **null\|callable** | Invoked per batch with (percentage complete, current batch, translated batch) | + +**Return Value:** + +Translated data preserving original structure and non-text values + +**Throws:** + +When required params or reference data are invalid +- [`InvalidArgumentException`](../../InvalidArgumentException) +When API rejects or fails to process the request +- [`RuntimeException`](../../RuntimeException) + +*** + +### localizeText + +Localize a single string and return the translated text. + +```php +public localizeText(string $text, array $params, null|callable $progressCallback = null): string +``` + +**Parameters:** + +| Parameter | Type | Description | +|---------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate | +| `$params` | **array** | Parameters: +- 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') +- 'sourceLocale' (string\|null): Language code of original text, null for auto-detection +- 'fast' (bool): Prioritize speed over translation quality +- 'reference' (array): Context, terminology, or style guidelines for translation | +| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | + +**Return Value:** + +Translated text, or empty string if translation unavailable + +**Throws:** + +When required params are missing or invalid +- [`InvalidArgumentException`](../../InvalidArgumentException) +When API rejects or fails to process the request +- [`RuntimeException`](../../RuntimeException) + +*** + +### batchLocalizeText + +Localize a string into multiple languages and return texts in order. + +```php +public batchLocalizeText(string $text, array $params): string[] +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate into multiple languages | +| `$params` | **array** | Parameters: +- 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') +- 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) +- 'fast' (bool): Apply speed optimization to all translations | + +**Return Value:** + +Array of translated texts in same order as targetLocales parameter + +**Throws:** + +When required params are missing or invalid +- [`InvalidArgumentException`](../../InvalidArgumentException) +When an individual localization request fails +- [`RuntimeException`](../../RuntimeException) + +*** + +### localizeChat + +Localize a chat transcript while preserving speaker names. + +```php +public localizeChat(array $chat, array $params, null|callable $progressCallback = null): array +``` + +**Parameters:** + +| Parameter | Type | Description | +|---------------------|--------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$chat` | **array** | Conversation history with speaker names and their messages | +| `$params` | **array** | Parameters: +- 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') +- 'sourceLocale' (string\|null): Language of original messages, null for auto-detection +- 'fast' (bool): Optimize for speed over translation quality +- 'reference' (array): Conversation context or domain-specific terminology | +| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | + +**Return Value:** + +Translated messages keeping original speaker names unchanged + +**Throws:** + +When chat entries or params are invalid +- [`InvalidArgumentException`](../../InvalidArgumentException) +When API rejects or fails to process the request +- [`RuntimeException`](../../RuntimeException) + +*** + +### recognizeLocale + +Identify the locale of the provided text. + +```php +public recognizeLocale(string $text): string +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|------------|--------------------------------------------------------------------| +| `$text` | **string** | Sample text for language detection (longer text improves accuracy) | + +**Return Value:** + +ISO language code detected by the API (e.g., 'en', 'es', 'zh') + +**Throws:** + +When input text is blank after trimming +- [`InvalidArgumentException`](../../InvalidArgumentException) +When API response is invalid or request fails +- [`RuntimeException`](../../RuntimeException) + +*** From af05155ae43fd9bf25ef3cb168aa59af210cf812 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:23:57 +1000 Subject: [PATCH 06/21] feat: update --- .github/workflows/generate-docs.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index 5ebbbc9..25402cf 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -31,7 +31,13 @@ jobs: run: composer install --prefer-dist --no-interaction --no-progress - name: Generate Markdown documentation - run: vendor/bin/phpdoc --directory=src --target=docs --template="vendor/saggre/phpdocumentor-markdown/themes/markdown" + run: | + vendor/bin/phpdoc \ + --directory=src \ + --target=docs \ + --template="vendor/saggre/phpdocumentor-markdown/themes/markdown" \ + --title="PHP SDK for Lingo.dev" \ + --visibility=public - name: Commit and push updates run: | From 6effbec95f21a80ad67e97b17f0095317cee3267 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 00:24:26 +0000 Subject: [PATCH 07/21] docs: update markdown API reference [skip ci] --- docs/Home.md | 2 +- .../LingoDotDev/Sdk/LingoDotDevEngine.md | 107 ------------------ 2 files changed, 1 insertion(+), 108 deletions(-) diff --git a/docs/Home.md b/docs/Home.md index 8fa6bd8..0fddc01 100644 --- a/docs/Home.md +++ b/docs/Home.md @@ -1,5 +1,5 @@ -This is an automatically generated documentation for **Documentation**. +This is an automatically generated documentation for **PHP SDK for Lingo.dev**. ## Namespaces diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index fb2bc78..612eb24 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -13,28 +13,6 @@ progress reporting, and surfacing validation or transport errors. * https://lingo.dev -## Properties - -### config - -Configuration options for the Engine. - -```php -protected array $config -``` - -*** - -### _httpClient - -HTTP client for API requests. - -```php -private \GuzzleHttp\Client $_httpClient -``` - -*** - ## Methods ### __construct @@ -62,91 +40,6 @@ When API key is missing or values fail validation *** -### _localizeChunk - -Localize a single chunk of content. - -```php -private _localizeChunk(string|null $sourceLocale, string $targetLocale, array $payload, string $workflowId, bool $fast): array -``` - -**Parameters:** - -| Parameter | Type | Description | -|-----------------|-------------------------|--------------------------------------------------------------------------------| -| `$sourceLocale` | **string\|null** | Language code of the original text (e.g., 'en', 'es'), null for auto-detection | -| `$targetLocale` | **string** | Language code to translate into (e.g., 'fr', 'de') | -| `$payload` | **array** | Content chunk with optional reference data for context | -| `$workflowId` | **string** | Unique identifier for tracking related translation requests | -| `$fast` | **bool** | Enable faster translation at potential quality tradeoff | - -**Return Value:** - -Translated chunk maintaining original structure - -**Throws:** - -When reference is not an array -- [`InvalidArgumentException`](../../InvalidArgumentException) -When API request fails -- [`RuntimeException`](../../RuntimeException) - -*** - -### _extractPayloadChunks - -Extract payload chunks based on the ideal chunk size. - -```php -private _extractPayloadChunks(array $payload): array> -``` - -**Parameters:** - -| Parameter | Type | Description | -|------------|-------------------------|---------------------------| -| `$payload` | **array** | The payload to be chunked | - -**Return Value:** - -Array of payload chunks - -*** - -### _countWordsInRecord - -Count words in a record or array. - -```php -private _countWordsInRecord(mixed $payload): int -``` - -**Parameters:** - -| Parameter | Type | Description | -|------------|-----------|-------------------------------| -| `$payload` | **mixed** | The payload to count words in | - -**Return Value:** - -Total number of words - -*** - -### _createId - -Generate a unique ID. - -```php -private _createId(): string -``` - -**Return Value:** - -Unique ID - -*** - ### localizeObject Localize every string in a nested array while keeping its shape intact. From 8f7deccd53acf2b7e57b292a8d305923bde0a592 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:28:19 +1000 Subject: [PATCH 08/21] docs: add examples --- src/LingoDotDevEngine.php | 276 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 276 insertions(+) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index a1e55c7..5b1d8fa 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -22,6 +22,51 @@ * to detect the locale of free-form text. The engine handles request batching, * progress reporting, and surfacing validation or transport errors. * + * @example Basic setup + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * ``` + * + * @example Laravel integration + * ```php + * engine = new LingoDotDevEngine([ + * 'apiKey' => config('services.lingodotdev.api_key'), + * ]); + * } + * + * public function translateMessage(Request $request) + * { + * $translated = $this->engine->localizeText($request->message, [ + * 'sourceLocale' => $request->source_locale, + * 'targetLocale' => $request->target_locale, + * ]); + * + * return response()->json(['translated' => $translated]); + * } + * } + * ``` + * * @category Localization * @package Lingodotdev\Sdk * @author Lingo.dev Team @@ -53,6 +98,28 @@ class LingoDotDevEngine * - 'batchSize' (int): Records per request, 1-250 (default: 25) * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) * + * @example Configuration + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * 'batchSize' => 100, + * 'idealBatchItemSize' => 1000, + * ]); + * + * $result = $engine->localizeText('Configuration test', [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'es', + * ]); + * echo $result; + * // Output: Prueba de configuración + * ``` + * * @throws \InvalidArgumentException When API key is missing or values fail validation */ public function __construct(array $config = []) @@ -304,6 +371,35 @@ private function _createId(): string * * @return array Translated data preserving original structure and non-text values * + * @example Object translation + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $content = [ + * 'greeting' => 'Hello', + * 'farewell' => 'Goodbye', + * 'messages' => [ + * 'welcome' => 'Welcome to our service', + * 'thanks' => 'Thank you for your business' + * ] + * ]; + * + * $translated = $engine->localizeObject($content, [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'fr', + * ]); + * print_r($translated); + * // Output: Array with French translations maintaining structure + * ``` + * * @throws \InvalidArgumentException When required params or reference data are invalid * @throws \RuntimeException When API rejects or fails to process the request */ @@ -333,6 +429,117 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * * @return string Translated text, or empty string if translation unavailable * + * @example Text translation + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $result = $engine->localizeText('Hello, world!', [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'es', + * ]); + * echo $result; + * // Output: ¡Hola, mundo! + * ``` + * + * @example Progress tracking + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $largeText = 'This is a very long text that needs translation...'; + * + * $result = $engine->localizeText($largeText, [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'es', + * ], function ($progress) { + * echo "Translation progress: $progress%\n"; + * }); + * // Output: + * // Translation progress: 25% + * // Translation progress: 50% + * // Translation progress: 75% + * // Translation progress: 100% + * ``` + * + * @example Translation parameters + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $result = $engine->localizeText('Hello world', [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'es', + * 'fast' => true, + * ]); + * echo $result; + * // Output: Hola mundo + * ``` + * + * @example Automatic language detection + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $result = $engine->localizeText('Bonjour le monde', [ + * 'sourceLocale' => null, + * 'targetLocale' => 'en', + * ]); + * echo $result; + * // Output: Hello world + * ``` + * + * @example Error handling + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * try { + * $result = $engine->localizeText('Hello', [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'es', + * ]); + * echo $result; + * } catch (Exception $e) { + * error_log('Translation failed: ' . $e->getMessage()); + * } + * ``` + * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When API rejects or fails to process the request */ @@ -362,6 +569,26 @@ public function localizeText(string $text, array $params, ?callable $progressCal * * @return string[] Array of translated texts in same order as targetLocales parameter * + * @example Batch translation to multiple languages + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $results = $engine->batchLocalizeText('Hello, world!', [ + * 'sourceLocale' => 'en', + * 'targetLocales' => ['es', 'fr', 'de'], + * ]); + * print_r($results); + * // Output: ["¡Hola, mundo!", "Bonjour le monde!", "Hallo, Welt!"] + * ``` + * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When an individual localization request fails */ @@ -402,6 +629,38 @@ public function batchLocalizeText(string $text, array $params): array * * @return array Translated messages keeping original speaker names unchanged * + * @example Chat translation + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $conversation = [ + * ['name' => 'Alice', 'text' => 'Hello, how are you?'], + * ['name' => 'Bob', 'text' => 'I am fine, thank you!'], + * ['name' => 'Alice', 'text' => 'What are you doing today?'] + * ]; + * + * $translated = $engine->localizeChat($conversation, [ + * 'sourceLocale' => 'en', + * 'targetLocale' => 'de', + * ]); + * + * foreach ($translated as $message) { + * echo $message['name'] . ': ' . $message['text'] . "\n"; + * } + * // Output: + * // Alice: Hallo, wie geht es dir? + * // Bob: Mir geht es gut, danke! + * // Alice: Was machst du heute? + * ``` + * * @throws \InvalidArgumentException When chat entries or params are invalid * @throws \RuntimeException When API rejects or fails to process the request */ @@ -441,6 +700,23 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall * * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') * + * @example Language detection + * ```php + * $_ENV['LINGODOTDEV_API_KEY'], + * ]); + * + * $locale = $engine->recognizeLocale('Bonjour le monde'); + * echo $locale; + * // Output: fr + * ``` + * * @throws \InvalidArgumentException When input text is blank after trimming * @throws \RuntimeException When API response is invalid or request fails */ From 026281450ed4e640a04378765c67a79d11fe672d Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:43:05 +1000 Subject: [PATCH 09/21] docs: changes --- src/LingoDotDevEngine.php | 78 +++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 35 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index 5b1d8fa..5f84744 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -93,10 +93,10 @@ class LingoDotDevEngine * Build an engine with your API key and optional batching limits. * * @param array $config Configuration options: - * - 'apiKey' (string, required): Your API token - * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) - * - 'batchSize' (int): Records per request, 1-250 (default: 25) - * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) + * - 'apiKey' (string, required): Your API token + * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) + * - 'batchSize' (int): Records per request, 1-250 (default: 25) + * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) * * @example Configuration * ```php @@ -163,7 +163,11 @@ public function __construct(array $config = []) * Localize content using the Lingo.dev API. * * @param array $payload Content to translate, structured as key-value pairs - * @param array $params Translation configuration options + * @param array $params Translation configuration options: + * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection + * - 'fast' (bool): Trade translation quality for speed + * - 'reference' (array|null): Context or glossary terms to guide translation * @param null|callable(int, mixed, mixed): void $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk * * @return array Translated content maintaining original structure @@ -217,11 +221,13 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres /** * Localize a single chunk of content. * - * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection - * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') - * @param array $payload Content chunk with optional reference data for context - * @param string $workflowId Unique identifier for tracking related translation requests - * @param bool $fast Enable faster translation at potential quality tradeoff + * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection + * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') + * @param array $payload Content chunk with optional reference data for context: + * - 'data' (array): Chunk data submitted for translation + * - 'reference' (array|null): Additional context for the translation request + * @param string $workflowId Unique identifier for tracking related translation requests + * @param bool $fast Enable faster translation at potential quality tradeoff * * @return array Translated chunk maintaining original structure * @@ -361,12 +367,12 @@ private function _createId(): string /** * Localize every string in a nested array while keeping its shape intact. * - * @param array $obj Nested data structure containing text to translate - * @param array $params Parameters: - * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection - * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array): Context or glossary terms to guide translation + * @param array $obj Nested data structure containing text to translate + * @param array $params Translation options controlling locale, speed, and contextual reference data: + * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection + * - 'fast' (bool): Trade translation quality for speed + * - 'reference' (array|null): Context or glossary terms to guide translation * @param null|callable(int, mixed, mixed): void $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * * @return array Translated data preserving original structure and non-text values @@ -419,12 +425,12 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal /** * Localize a single string and return the translated text. * - * @param string $text Text content to translate - * @param array $params Parameters: - * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection - * - 'fast' (bool): Prioritize speed over translation quality - * - 'reference' (array): Context, terminology, or style guidelines for translation + * @param string $text Text content to translate + * @param array $params Translation options such as locale hints, speed preference, and contextual references: + * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection + * - 'fast' (bool): Trade translation quality for speed + * - 'reference' (array|null): Context, terminology, or style guidelines * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * * @return string Translated text, or empty string if translation unavailable @@ -561,11 +567,11 @@ public function localizeText(string $text, array $params, ?callable $progressCal /** * Localize a string into multiple languages and return texts in order. * - * @param string $text Text content to translate into multiple languages - * @param array $params Parameters: - * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') - * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) - * - 'fast' (bool): Apply speed optimization to all translations + * @param string $text Text content to translate into multiple languages + * @param array $params Batch translation options shared by all target locales: + * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') + * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) + * - 'fast' (bool): Apply speed optimization to all translations * * @return string[] Array of translated texts in same order as targetLocales parameter * @@ -619,15 +625,17 @@ public function batchLocalizeText(string $text, array $params): array /** * Localize a chat transcript while preserving speaker names. * - * @param array $chat Conversation history with speaker names and their messages - * @param array $params Parameters: - * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language of original messages, null for auto-detection - * - 'fast' (bool): Optimize for speed over translation quality - * - 'reference' (array): Conversation context or domain-specific terminology - * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing + * @param array> $chat Conversation history with speaker names and their messages. Each entry must include: + * - 'name' (string): Speaker label to preserve + * - 'text' (string): Message content to translate + * @param array $params Chat translation options defining locale behavior and context: + * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') + * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection + * - 'fast' (bool): Optimize for speed over translation quality + * - 'reference' (array|null): Conversation context or domain-specific terminology + * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * - * @return array Translated messages keeping original speaker names unchanged + * @return array> Translated messages keeping original speaker names unchanged * * @example Chat translation * ```php From f36191bbcd8151b187d33567c0f77852892f697e Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:45:30 +1000 Subject: [PATCH 10/21] docs: consistency --- src/LingoDotDevEngine.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index 5f84744..736fc24 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -167,7 +167,7 @@ public function __construct(array $config = []) * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context or glossary terms to guide translation + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param null|callable(int, mixed, mixed): void $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk * * @return array Translated content maintaining original structure @@ -225,7 +225,7 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') * @param array $payload Content chunk with optional reference data for context: * - 'data' (array): Chunk data submitted for translation - * - 'reference' (array|null): Additional context for the translation request + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param string $workflowId Unique identifier for tracking related translation requests * @param bool $fast Enable faster translation at potential quality tradeoff * @@ -372,7 +372,7 @@ private function _createId(): string * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context or glossary terms to guide translation + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param null|callable(int, mixed, mixed): void $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * * @return array Translated data preserving original structure and non-text values @@ -430,7 +430,7 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context, terminology, or style guidelines + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * * @return string Translated text, or empty string if translation unavailable @@ -571,7 +571,7 @@ public function localizeText(string $text, array $params, ?callable $progressCal * @param array $params Batch translation options shared by all target locales: * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) - * - 'fast' (bool): Apply speed optimization to all translations + * - 'fast' (bool): Trade translation quality for speed * * @return string[] Array of translated texts in same order as targetLocales parameter * @@ -631,8 +631,8 @@ public function batchLocalizeText(string $text, array $params): array * @param array $params Chat translation options defining locale behavior and context: * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection - * - 'fast' (bool): Optimize for speed over translation quality - * - 'reference' (array|null): Conversation context or domain-specific terminology + * - 'fast' (bool): Trade translation quality for speed + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing * * @return array> Translated messages keeping original speaker names unchanged From f5b131b30b11b1d00e71e3807454948cd7b66e1e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 00:45:51 +0000 Subject: [PATCH 11/21] docs: update markdown API reference [skip ci] --- .../LingoDotDev/Sdk/LingoDotDevEngine.md | 56 ++++++++++--------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index 612eb24..9a3be42 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -50,15 +50,15 @@ public localizeObject(array $obj, array $params, nul **Parameters:** -| Parameter | Type | Description | -|---------------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$obj` | **array** | Nested data structure containing text to translate | -| `$params` | **array** | Parameters: +| Parameter | Type | Description | +|---------------------|-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$obj` | **array** | Nested data structure containing text to translate | +| `$params` | **array** | Translation options controlling locale, speed, and contextual reference data: - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection - 'fast' (bool): Trade translation quality for speed -- 'reference' (array): Context or glossary terms to guide translation | -| `$progressCallback` | **null\|callable** | Invoked per batch with (percentage complete, current batch, translated batch) | +- 'reference' (array\|null): Context data or glossary terms to guide translation | +| `$progressCallback` | **null\|callable** | Invoked per batch with (percentage complete, current batch, translated batch) | **Return Value:** @@ -83,15 +83,15 @@ public localizeText(string $text, array $params, null|callable $pr **Parameters:** -| Parameter | Type | Description | -|---------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate | -| `$params` | **array** | Parameters: +| Parameter | Type | Description | +|---------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate | +| `$params` | **array** | Translation options such as locale hints, speed preference, and contextual references: - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection -- 'fast' (bool): Prioritize speed over translation quality -- 'reference' (array): Context, terminology, or style guidelines for translation | -| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | +- 'fast' (bool): Trade translation quality for speed +- 'reference' (array\|null): Context data or glossary terms to guide translation | +| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | **Return Value:** @@ -116,13 +116,13 @@ public batchLocalizeText(string $text, array $params): string[] **Parameters:** -| Parameter | Type | Description | -|-----------|-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate into multiple languages | -| `$params` | **array** | Parameters: +| Parameter | Type | Description | +|-----------|-------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate into multiple languages | +| `$params` | **array** | Batch translation options shared by all target locales: - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) -- 'fast' (bool): Apply speed optimization to all translations | +- 'fast' (bool): Trade translation quality for speed | **Return Value:** @@ -142,20 +142,22 @@ When an individual localization request fails Localize a chat transcript while preserving speaker names. ```php -public localizeChat(array $chat, array $params, null|callable $progressCallback = null): array +public localizeChat(array> $chat, array $params, null|callable $progressCallback = null): array> ``` **Parameters:** -| Parameter | Type | Description | -|---------------------|--------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$chat` | **array** | Conversation history with speaker names and their messages | -| `$params` | **array** | Parameters: +| Parameter | Type | Description | +|---------------------|-------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$chat` | **array>** | Conversation history with speaker names and their messages. Each entry must include: +- 'name' (string): Speaker label to preserve +- 'text' (string): Message content to translate | +| `$params` | **array** | Chat translation options defining locale behavior and context: - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') -- 'sourceLocale' (string\|null): Language of original messages, null for auto-detection -- 'fast' (bool): Optimize for speed over translation quality -- 'reference' (array): Conversation context or domain-specific terminology | -| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | +- 'sourceLocale' (string\|null): Language code of original messages, null for auto-detection +- 'fast' (bool): Trade translation quality for speed +- 'reference' (array\|null): Context data or glossary terms to guide translation | +| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | **Return Value:** From 4798346fadfc78f7aac1413bae95ea54d1f970ea Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 10:58:42 +1000 Subject: [PATCH 12/21] docs: update --- src/LingoDotDevEngine.php | 335 ++++++++++---------------------------- 1 file changed, 89 insertions(+), 246 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index 736fc24..b2b810a 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -22,56 +22,51 @@ * to detect the locale of free-form text. The engine handles request batching, * progress reporting, and surfacing validation or transport errors. * - * @example Basic setup - * ```php + * Example (basic setup): + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * @endcode * - * @example Laravel integration - * ```php + * Example (Laravel integration): + * @code * engine = new LingoDotDevEngine([ - * 'apiKey' => config('services.lingodotdev.api_key'), - * ]); - * } - * - * public function translateMessage(Request $request) - * { - * $translated = $this->engine->localizeText($request->message, [ - * 'sourceLocale' => $request->source_locale, - * 'targetLocale' => $request->target_locale, - * ]); - * - * return response()->json(['translated' => $translated]); - * } - * } - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => config('services.lingodotdev.api_key')]); + * $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']); + * @endcode * * @category Localization * @package Lingodotdev\Sdk * @author Lingo.dev Team * @license MIT https://opensource.org/licenses/MIT * @link https://lingo.dev + * + * @phpstan-type EngineConfig array{ + * apiKey: string, + * apiUrl?: string, + * batchSize?: positive-int, + * idealBatchItemSize?: positive-int + * } + * @phpstan-type LocalizeParams array{ + * targetLocale: string, + * sourceLocale?: string|null, + * fast?: bool, + * reference?: array|null + * } + * @phpstan-type BatchLocalizeParams array{ + * sourceLocale: string, + * targetLocales: array, + * fast?: bool + * } + * @phpstan-type ChatMessage array{ + * name: string, + * text: string + * } + * @phpstan-type ChatTranscript array + * @phpstan-type ChunkPayload array{ + * data: array, + * reference?: array|null + * } */ class LingoDotDevEngine { @@ -97,28 +92,17 @@ class LingoDotDevEngine * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) * - 'batchSize' (int): Records per request, 1-250 (default: 25) * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) + * @phpstan-param EngineConfig $config * - * @example Configuration - * ```php + * Example: + * @code * $_ENV['LINGODOTDEV_API_KEY'], * 'batchSize' => 100, * 'idealBatchItemSize' => 1000, * ]); - * - * $result = $engine->localizeText('Configuration test', [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'es', - * ]); - * echo $result; - * // Output: Prueba de configuración - * ``` + * @endcode * * @throws \InvalidArgumentException When API key is missing or values fail validation */ @@ -162,13 +146,14 @@ public function __construct(array $config = []) /** * Localize content using the Lingo.dev API. * - * @param array $payload Content to translate, structured as key-value pairs - * @param array $params Translation configuration options: + * @param array $payload Content to translate, structured as key-value pairs + * @param array $params Translation configuration options: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param null|callable(int, mixed, mixed): void $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk + * @phpstan-param LocalizeParams $params + * @param (callable(int, array, array): void)|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk * * @return array Translated content maintaining original structure * @@ -223,9 +208,8 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres * * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') - * @param array $payload Content chunk with optional reference data for context: - * - 'data' (array): Chunk data submitted for translation - * - 'reference' (array|null): Context data or glossary terms to guide translation + * @param array $payload Content chunk with optional reference data for context + * @phpstan-param ChunkPayload $payload * @param string $workflowId Unique identifier for tracking related translation requests * @param bool $fast Enable faster translation at potential quality tradeoff * @@ -373,38 +357,18 @@ private function _createId(): string * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param null|callable(int, mixed, mixed): void $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) + * @phpstan-param LocalizeParams $params + * @param (callable(int, array, array): void)|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * * @return array Translated data preserving original structure and non-text values * * @example Object translation - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $content = [ - * 'greeting' => 'Hello', - * 'farewell' => 'Goodbye', - * 'messages' => [ - * 'welcome' => 'Welcome to our service', - * 'thanks' => 'Thank you for your business' - * ] - * ]; - * - * $translated = $engine->localizeObject($content, [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'fr', - * ]); - * print_r($translated); - * // Output: Array with French translations maintaining structure - * ``` + * $content = ['greeting' => 'Hello']; + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); + * @endcode * * @throws \InvalidArgumentException When required params or reference data are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -431,120 +395,37 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing + * @phpstan-param LocalizeParams $params + * @param (callable(int): void)|null $progressCallback Called with completion percentage (0-100) during processing * * @return string Translated text, or empty string if translation unavailable * * @example Text translation - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $result = $engine->localizeText('Hello, world!', [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'es', - * ]); - * echo $result; - * // Output: ¡Hola, mundo! - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * echo $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); + * @endcode * * @example Progress tracking - * ```php - * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $largeText = 'This is a very long text that needs translation...'; - * - * $result = $engine->localizeText($largeText, [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'es', - * ], function ($progress) { - * echo "Translation progress: $progress%\n"; - * }); - * // Output: - * // Translation progress: 25% - * // Translation progress: 50% - * // Translation progress: 75% - * // Translation progress: 100% - * ``` - * - * @example Translation parameters - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $result = $engine->localizeText('Hello world', [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'es', - * 'fast' => true, - * ]); - * echo $result; - * // Output: Hola mundo - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->localizeText( + * 'This is a very long text that needs translation...', + * ['sourceLocale' => 'en', 'targetLocale' => 'es'], + * function (int $progress): void { + * echo 'Translation progress: ' . $progress . "%\n"; + * } + * ); + * @endcode * * @example Automatic language detection - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $result = $engine->localizeText('Bonjour le monde', [ - * 'sourceLocale' => null, - * 'targetLocale' => 'en', - * ]); - * echo $result; - * // Output: Hello world - * ``` - * - * @example Error handling - * ```php - * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * try { - * $result = $engine->localizeText('Hello', [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'es', - * ]); - * echo $result; - * } catch (Exception $e) { - * error_log('Translation failed: ' . $e->getMessage()); - * } - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * echo $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); + * @endcode * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -572,28 +453,19 @@ public function localizeText(string $text, array $params, ?callable $progressCal * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) * - 'fast' (bool): Trade translation quality for speed + * @phpstan-param BatchLocalizeParams $params * * @return string[] Array of translated texts in same order as targetLocales parameter * * @example Batch translation to multiple languages - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $results = $engine->batchLocalizeText('Hello, world!', [ * 'sourceLocale' => 'en', * 'targetLocales' => ['es', 'fr', 'de'], * ]); - * print_r($results); - * // Output: ["¡Hola, mundo!", "Bonjour le monde!", "Hallo, Welt!"] - * ``` + * @endcode * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When an individual localization request fails @@ -628,46 +500,27 @@ public function batchLocalizeText(string $text, array $params): array * @param array> $chat Conversation history with speaker names and their messages. Each entry must include: * - 'name' (string): Speaker label to preserve * - 'text' (string): Message content to translate + * @phpstan-param ChatTranscript $chat * @param array $params Chat translation options defining locale behavior and context: * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param null|callable(int): void $progressCallback Called with completion percentage (0-100) during processing + * @phpstan-param LocalizeParams $params + * @param (callable(int): void)|null $progressCallback Called with completion percentage (0-100) during processing * * @return array> Translated messages keeping original speaker names unchanged * * @example Chat translation - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $conversation = [ * ['name' => 'Alice', 'text' => 'Hello, how are you?'], - * ['name' => 'Bob', 'text' => 'I am fine, thank you!'], - * ['name' => 'Alice', 'text' => 'What are you doing today?'] + * ['name' => 'Bob', 'text' => 'I am fine, thank you!'] * ]; - * - * $translated = $engine->localizeChat($conversation, [ - * 'sourceLocale' => 'en', - * 'targetLocale' => 'de', - * ]); - * - * foreach ($translated as $message) { - * echo $message['name'] . ': ' . $message['text'] . "\n"; - * } - * // Output: - * // Alice: Hallo, wie geht es dir? - * // Bob: Mir geht es gut, danke! - * // Alice: Was machst du heute? - * ``` + * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); + * @endcode * * @throws \InvalidArgumentException When chat entries or params are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -709,21 +562,11 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') * * @example Language detection - * ```php + * @code * $_ENV['LINGODOTDEV_API_KEY'], - * ]); - * - * $locale = $engine->recognizeLocale('Bonjour le monde'); - * echo $locale; - * // Output: fr - * ``` + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * echo $engine->recognizeLocale('Bonjour le monde'); + * @endcode * * @throws \InvalidArgumentException When input text is blank after trimming * @throws \RuntimeException When API response is invalid or request fails From 953cd422b881465b660cc1c4334fdc869ff632b7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 00:58:59 +0000 Subject: [PATCH 13/21] docs: update markdown API reference [skip ci] --- docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index 9a3be42..eb23103 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -5,6 +5,8 @@ Use a single engine instance to translate strings, arrays, and chat logs, or to detect the locale of free-form text. The engine handles request batching, progress reporting, and surfacing validation or transport errors. +Example (basic setup): + *** * Full name: `\LingoDotDev\Sdk\LingoDotDevEngine` @@ -45,7 +47,7 @@ When API key is missing or values fail validation Localize every string in a nested array while keeping its shape intact. ```php -public localizeObject(array $obj, array $params, null|callable $progressCallback = null): array +public localizeObject(array $obj, array $params, callable|null $progressCallback = null): array ``` **Parameters:** @@ -58,7 +60,7 @@ public localizeObject(array $obj, array $params, nul - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **null\|callable** | Invoked per batch with (percentage complete, current batch, translated batch) | +| `$progressCallback` | **callable\|null** | Invoked per batch with (percentage complete, current batch, translated batch) | **Return Value:** @@ -78,7 +80,7 @@ When API rejects or fails to process the request Localize a single string and return the translated text. ```php -public localizeText(string $text, array $params, null|callable $progressCallback = null): string +public localizeText(string $text, array $params, callable|null $progressCallback = null): string ``` **Parameters:** @@ -91,7 +93,7 @@ public localizeText(string $text, array $params, null|callable $pr - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | +| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | **Return Value:** @@ -142,7 +144,7 @@ When an individual localization request fails Localize a chat transcript while preserving speaker names. ```php -public localizeChat(array> $chat, array $params, null|callable $progressCallback = null): array> +public localizeChat(array> $chat, array $params, callable|null $progressCallback = null): array> ``` **Parameters:** @@ -157,7 +159,7 @@ public localizeChat(array> $chat, array $ - 'sourceLocale' (string\|null): Language code of original messages, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **null\|callable** | Called with completion percentage (0-100) during processing | +| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | **Return Value:** From 1b5fa78f6f8ae04e286b8f2b543f10c9ad895945 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 11:05:12 +1000 Subject: [PATCH 14/21] docs: update --- src/LingoDotDevEngine.php | 99 +++++++++++++-------------------------- 1 file changed, 32 insertions(+), 67 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index b2b810a..d312e66 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -23,50 +23,23 @@ * progress reporting, and surfacing validation or transport errors. * * Example (basic setup): - * @code + *

  *  $_ENV['LINGODOTDEV_API_KEY']]);
- * @endcode
+ * 
* * Example (Laravel integration): - * @code + *

  *  config('services.lingodotdev.api_key')]);
  * $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']);
- * @endcode
+ * 
* * @category Localization * @package Lingodotdev\Sdk * @author Lingo.dev Team * @license MIT https://opensource.org/licenses/MIT * @link https://lingo.dev - * - * @phpstan-type EngineConfig array{ - * apiKey: string, - * apiUrl?: string, - * batchSize?: positive-int, - * idealBatchItemSize?: positive-int - * } - * @phpstan-type LocalizeParams array{ - * targetLocale: string, - * sourceLocale?: string|null, - * fast?: bool, - * reference?: array|null - * } - * @phpstan-type BatchLocalizeParams array{ - * sourceLocale: string, - * targetLocales: array, - * fast?: bool - * } - * @phpstan-type ChatMessage array{ - * name: string, - * text: string - * } - * @phpstan-type ChatTranscript array - * @phpstan-type ChunkPayload array{ - * data: array, - * reference?: array|null - * } */ class LingoDotDevEngine { @@ -87,22 +60,21 @@ class LingoDotDevEngine /** * Build an engine with your API key and optional batching limits. * - * @param array $config Configuration options: + * @param array{apiKey:string,apiUrl?:string,batchSize?:int,idealBatchItemSize?:int} $config Configuration options: * - 'apiKey' (string, required): Your API token * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) * - 'batchSize' (int): Records per request, 1-250 (default: 25) * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) - * @phpstan-param EngineConfig $config * * Example: - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY'],
      *     'batchSize' => 100,
      *     'idealBatchItemSize' => 1000,
      * ]);
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When API key is missing or values fail validation */ @@ -147,13 +119,12 @@ public function __construct(array $config = []) * Localize content using the Lingo.dev API. * * @param array $payload Content to translate, structured as key-value pairs - * @param array $params Translation configuration options: + * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation configuration options: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @phpstan-param LocalizeParams $params - * @param (callable(int, array, array): void)|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk + * @param callable|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk * * @return array Translated content maintaining original structure * @@ -208,8 +179,7 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres * * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') - * @param array $payload Content chunk with optional reference data for context - * @phpstan-param ChunkPayload $payload + * @param array{data:array,reference?:array|null} $payload Content chunk with optional reference data for context * @param string $workflowId Unique identifier for tracking related translation requests * @param bool $fast Enable faster translation at potential quality tradeoff * @@ -352,23 +322,22 @@ private function _createId(): string * Localize every string in a nested array while keeping its shape intact. * * @param array $obj Nested data structure containing text to translate - * @param array $params Translation options controlling locale, speed, and contextual reference data: + * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation options controlling locale, speed, and contextual reference data: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @phpstan-param LocalizeParams $params - * @param (callable(int, array, array): void)|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) + * @param callable|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) * * @return array Translated data preserving original structure and non-text values * * @example Object translation - * @code + *

      *  'Hello'];
      * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]);
      * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']);
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When required params or reference data are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -390,25 +359,24 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * Localize a single string and return the translated text. * * @param string $text Text content to translate - * @param array $params Translation options such as locale hints, speed preference, and contextual references: + * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation options such as locale hints, speed preference, and contextual references: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @phpstan-param LocalizeParams $params - * @param (callable(int): void)|null $progressCallback Called with completion percentage (0-100) during processing + * @param callable|null $progressCallback Called with completion percentage (0-100) during processing * * @return string Translated text, or empty string if translation unavailable * * @example Text translation - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * echo $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']);
-     * @endcode
+     * 
* * @example Progress tracking - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * $engine->localizeText(
@@ -418,14 +386,14 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal
      *         echo 'Translation progress: ' . $progress . "%\n";
      *     }
      * );
-     * @endcode
+     * 
* * @example Automatic language detection - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * echo $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']);
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -449,23 +417,22 @@ public function localizeText(string $text, array $params, ?callable $progressCal * Localize a string into multiple languages and return texts in order. * * @param string $text Text content to translate into multiple languages - * @param array $params Batch translation options shared by all target locales: + * @param array{sourceLocale:string,targetLocales:array,fast?:bool} $params Batch translation options shared by all target locales: * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) * - 'fast' (bool): Trade translation quality for speed - * @phpstan-param BatchLocalizeParams $params * * @return string[] Array of translated texts in same order as targetLocales parameter * * @example Batch translation to multiple languages - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * $results = $engine->batchLocalizeText('Hello, world!', [
      *     'sourceLocale' => 'en',
      *     'targetLocales' => ['es', 'fr', 'de'],
      * ]);
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When an individual localization request fails @@ -497,22 +464,20 @@ public function batchLocalizeText(string $text, array $params): array /** * Localize a chat transcript while preserving speaker names. * - * @param array> $chat Conversation history with speaker names and their messages. Each entry must include: + * @param array $chat Conversation history with speaker names and their messages. Each entry must include: * - 'name' (string): Speaker label to preserve * - 'text' (string): Message content to translate - * @phpstan-param ChatTranscript $chat - * @param array $params Chat translation options defining locale behavior and context: + * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Chat translation options defining locale behavior and context: * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation - * @phpstan-param LocalizeParams $params - * @param (callable(int): void)|null $progressCallback Called with completion percentage (0-100) during processing + * @param callable|null $progressCallback Called with completion percentage (0-100) during processing * * @return array> Translated messages keeping original speaker names unchanged * * @example Chat translation - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * $conversation = [
@@ -520,7 +485,7 @@ public function batchLocalizeText(string $text, array $params): array
      *     ['name' => 'Bob', 'text' => 'I am fine, thank you!']
      * ];
      * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']);
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When chat entries or params are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -562,11 +527,11 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') * * @example Language detection - * @code + *

      *  $_ENV['LINGODOTDEV_API_KEY']]);
      * echo $engine->recognizeLocale('Bonjour le monde');
-     * @endcode
+     * 
* * @throws \InvalidArgumentException When input text is blank after trimming * @throws \RuntimeException When API response is invalid or request fails From b3f4001d456ee054dfad2374662bb8113783a16f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 01:05:31 +0000 Subject: [PATCH 15/21] docs: update markdown API reference [skip ci] --- .../LingoDotDev/Sdk/LingoDotDevEngine.md | 83 ++++++++++++------- 1 file changed, 52 insertions(+), 31 deletions(-) diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index eb23103..37c059b 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -6,6 +6,17 @@ to detect the locale of free-form text. The engine handles request batching, progress reporting, and surfacing validation or transport errors. Example (basic setup): +

+ $_ENV['LINGODOTDEV_API_KEY']]);
+
+ +Example (Laravel integration): +

+ config('services.lingodotdev.api_key')]);
+$engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']);
+
*** @@ -22,18 +33,28 @@ Example (basic setup): Build an engine with your API key and optional batching limits. ```php -public __construct(array $config = []): mixed +public __construct(array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config = []): mixed ``` **Parameters:** -| Parameter | Type | Description | -|-----------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$config` | **array** | Configuration options: -- 'apiKey' (string, required): Your API token -- 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) -- 'batchSize' (int): Records per request, 1-250 (default: 25) -- 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) | +| Parameter | Type | Description | +|-----------|---------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$config` | **array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int}** | Configuration options: + - 'apiKey' (string, required): Your API token + - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) + - 'batchSize' (int): Records per request, 1-250 (default: 25) + - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) + +Example: +

+ $_ENV['LINGODOTDEV_API_KEY'],
+    'batchSize' => 100,
+    'idealBatchItemSize' => 1000,
+]);
+
| **Throws:** @@ -47,20 +68,20 @@ When API key is missing or values fail validation Localize every string in a nested array while keeping its shape intact. ```php -public localizeObject(array $obj, array $params, callable|null $progressCallback = null): array +public localizeObject(array $obj, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array ``` **Parameters:** -| Parameter | Type | Description | -|---------------------|-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$obj` | **array** | Nested data structure containing text to translate | -| `$params` | **array** | Translation options controlling locale, speed, and contextual reference data: +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$obj` | **array** | Nested data structure containing text to translate | +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options controlling locale, speed, and contextual reference data: - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Invoked per batch with (percentage complete, current batch, translated batch) | +| `$progressCallback` | **callable\|null** | Invoked per batch with (percentage complete, current batch, translated batch) | **Return Value:** @@ -80,20 +101,20 @@ When API rejects or fails to process the request Localize a single string and return the translated text. ```php -public localizeText(string $text, array $params, callable|null $progressCallback = null): string +public localizeText(string $text, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): string ``` **Parameters:** -| Parameter | Type | Description | -|---------------------|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate | -| `$params` | **array** | Translation options such as locale hints, speed preference, and contextual references: +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate | +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options such as locale hints, speed preference, and contextual references: - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - 'sourceLocale' (string\|null): Language code of original text, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | +| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | **Return Value:** @@ -113,15 +134,15 @@ When API rejects or fails to process the request Localize a string into multiple languages and return texts in order. ```php -public batchLocalizeText(string $text, array $params): string[] +public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales: array, fast?: bool} $params): string[] ``` **Parameters:** -| Parameter | Type | Description | -|-----------|-------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate into multiple languages | -| `$params` | **array** | Batch translation options shared by all target locales: +| Parameter | Type | Description | +|-----------|--------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate into multiple languages | +| `$params` | **array{sourceLocale: string, targetLocales: array, fast?: bool}** | Batch translation options shared by all target locales: - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) - 'fast' (bool): Trade translation quality for speed | @@ -144,22 +165,22 @@ When an individual localization request fails Localize a chat transcript while preserving speaker names. ```php -public localizeChat(array> $chat, array $params, callable|null $progressCallback = null): array> +public localizeChat(array $chat, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array> ``` **Parameters:** -| Parameter | Type | Description | -|---------------------|-------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$chat` | **array>** | Conversation history with speaker names and their messages. Each entry must include: +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$chat` | **array** | Conversation history with speaker names and their messages. Each entry must include: - 'name' (string): Speaker label to preserve - 'text' (string): Message content to translate | -| `$params` | **array** | Chat translation options defining locale behavior and context: +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Chat translation options defining locale behavior and context: - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') - 'sourceLocale' (string\|null): Language code of original messages, null for auto-detection - 'fast' (bool): Trade translation quality for speed - 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | +| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | **Return Value:** From 58d09ff692205ebf0c315e05e293467031ce17e1 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 11:29:56 +1000 Subject: [PATCH 16/21] docs: update --- src/LingoDotDevEngine.php | 138 +++++++++++++++----------------------- 1 file changed, 53 insertions(+), 85 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index d312e66..26e4b3e 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -23,17 +23,11 @@ * progress reporting, and surfacing validation or transport errors. * * Example (basic setup): - *

- *  $_ENV['LINGODOTDEV_API_KEY']]);
- * 
+ * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * * Example (Laravel integration): - *

- *  config('services.lingodotdev.api_key')]);
- * $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']);
- * 
+ * $engine = new LingoDotDevEngine(['apiKey' => config('services.lingodotdev.api_key')]); + * $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']); * * @category Localization * @package Lingodotdev\Sdk @@ -46,7 +40,7 @@ class LingoDotDevEngine /** * Configuration options for the Engine. * - * @var array + * @var array{apiKey: string, apiUrl: string, batchSize: int, idealBatchItemSize: int} */ protected $config; @@ -60,21 +54,18 @@ class LingoDotDevEngine /** * Build an engine with your API key and optional batching limits. * - * @param array{apiKey:string,apiUrl?:string,batchSize?:int,idealBatchItemSize?:int} $config Configuration options: + * @param array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config Configuration options: * - 'apiKey' (string, required): Your API token * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) * - 'batchSize' (int): Records per request, 1-250 (default: 25) * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) * * Example: - *

-     *  $_ENV['LINGODOTDEV_API_KEY'],
-     *     'batchSize' => 100,
-     *     'idealBatchItemSize' => 1000,
-     * ]);
-     * 
+ * $engine = new LingoDotDevEngine([ + * 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], + * 'batchSize' => 100, + * 'idealBatchItemSize' => 1000, + * ]); * * @throws \InvalidArgumentException When API key is missing or values fail validation */ @@ -119,7 +110,7 @@ public function __construct(array $config = []) * Localize content using the Lingo.dev API. * * @param array $payload Content to translate, structured as key-value pairs - * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation configuration options: + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation configuration options: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed @@ -179,7 +170,9 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres * * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') - * @param array{data:array,reference?:array|null} $payload Content chunk with optional reference data for context + * @param array{data: array, reference?: array|null} $payload Content chunk with optional reference data for context. Expected keys: + * - 'data' (array): Chunk data submitted for translation + * - 'reference' (array|null): Context data or glossary terms to guide translation * @param string $workflowId Unique identifier for tracking related translation requests * @param bool $fast Enable faster translation at potential quality tradeoff * @@ -322,7 +315,7 @@ private function _createId(): string * Localize every string in a nested array while keeping its shape intact. * * @param array $obj Nested data structure containing text to translate - * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation options controlling locale, speed, and contextual reference data: + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options controlling locale, speed, and contextual reference data: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed @@ -331,13 +324,10 @@ private function _createId(): string * * @return array Translated data preserving original structure and non-text values * - * @example Object translation - *

-     *  'Hello'];
-     * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]);
-     * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']);
-     * 
+ * Example: + * $content = ['greeting' => 'Hello']; + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); * * @throws \InvalidArgumentException When required params or reference data are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -359,7 +349,7 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * Localize a single string and return the translated text. * * @param string $text Text content to translate - * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Translation options such as locale hints, speed preference, and contextual references: + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options such as locale hints, speed preference, and contextual references: * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection * - 'fast' (bool): Trade translation quality for speed @@ -368,32 +358,19 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * * @return string Translated text, or empty string if translation unavailable * - * @example Text translation - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * echo $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']);
-     * 
- * - * @example Progress tracking - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * $engine->localizeText(
-     *     'This is a very long text that needs translation...',
-     *     ['sourceLocale' => 'en', 'targetLocale' => 'es'],
-     *     function (int $progress): void {
-     *         echo 'Translation progress: ' . $progress . "%\n";
-     *     }
-     * );
-     * 
- * - * @example Automatic language detection - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * echo $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']);
-     * 
+ * Examples: + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); + * + * $engine->localizeText( + * 'This is a very long text that needs translation...', + * ['sourceLocale' => 'en', 'targetLocale' => 'es'], + * function (int $progress): void { + * echo 'Translation progress: ' . $progress . "%\n"; + * } + * ); + * + * $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -417,22 +394,19 @@ public function localizeText(string $text, array $params, ?callable $progressCal * Localize a string into multiple languages and return texts in order. * * @param string $text Text content to translate into multiple languages - * @param array{sourceLocale:string,targetLocales:array,fast?:bool} $params Batch translation options shared by all target locales: + * @param array{sourceLocale: string, targetLocales: string[], fast?: bool} $params Batch translation options shared by all target locales: * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) * - 'fast' (bool): Trade translation quality for speed * * @return string[] Array of translated texts in same order as targetLocales parameter * - * @example Batch translation to multiple languages - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * $results = $engine->batchLocalizeText('Hello, world!', [
-     *     'sourceLocale' => 'en',
-     *     'targetLocales' => ['es', 'fr', 'de'],
-     * ]);
-     * 
+ * Example: + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->batchLocalizeText('Hello, world!', [ + * 'sourceLocale' => 'en', + * 'targetLocales' => ['es', 'fr', 'de'], + * ]); * * @throws \InvalidArgumentException When required params are missing or invalid * @throws \RuntimeException When an individual localization request fails @@ -464,28 +438,25 @@ public function batchLocalizeText(string $text, array $params): array /** * Localize a chat transcript while preserving speaker names. * - * @param array $chat Conversation history with speaker names and their messages. Each entry must include: + * @param array $chat Conversation history with speaker names and their messages. Each entry must include: * - 'name' (string): Speaker label to preserve * - 'text' (string): Message content to translate - * @param array{targetLocale:string,sourceLocale?:string|null,fast?:bool,reference?:array|null} $params Chat translation options defining locale behavior and context: + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Chat translation options defining locale behavior and context: * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection * - 'fast' (bool): Trade translation quality for speed * - 'reference' (array|null): Context data or glossary terms to guide translation * @param callable|null $progressCallback Called with completion percentage (0-100) during processing * - * @return array> Translated messages keeping original speaker names unchanged + * @return array Translated messages keeping original speaker names unchanged * - * @example Chat translation - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * $conversation = [
-     *     ['name' => 'Alice', 'text' => 'Hello, how are you?'],
-     *     ['name' => 'Bob', 'text' => 'I am fine, thank you!']
-     * ];
-     * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']);
-     * 
+ * Example: + * $conversation = [ + * ['name' => 'Alice', 'text' => 'Hello, how are you?'], + * ['name' => 'Bob', 'text' => 'I am fine, thank you!'], + * ]; + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); * * @throws \InvalidArgumentException When chat entries or params are invalid * @throws \RuntimeException When API rejects or fails to process the request @@ -526,12 +497,9 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall * * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') * - * @example Language detection - *

-     *  $_ENV['LINGODOTDEV_API_KEY']]);
-     * echo $engine->recognizeLocale('Bonjour le monde');
-     * 
+ * Example: + * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $engine->recognizeLocale('Bonjour le monde'); * * @throws \InvalidArgumentException When input text is blank after trimming * @throws \RuntimeException When API response is invalid or request fails From 8d7f3bacee364cf94d8ae455900dc52792193b95 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 01:30:20 +0000 Subject: [PATCH 17/21] docs: update markdown API reference [skip ci] --- .../LingoDotDev/Sdk/LingoDotDevEngine.md | 79 +++++++++++++------ 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index 37c059b..788ae7e 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -6,17 +6,11 @@ to detect the locale of free-form text. The engine handles request batching, progress reporting, and surfacing validation or transport errors. Example (basic setup): -

- $_ENV['LINGODOTDEV_API_KEY']]);
-
+ $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); Example (Laravel integration): -

- config('services.lingodotdev.api_key')]);
-$engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']);
-
+ $engine = new LingoDotDevEngine(['apiKey' => config('services.lingodotdev.api_key')]); + $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']); *** @@ -38,8 +32,8 @@ public __construct(array{apiKey: string, apiUrl?: string, batchSize?: int, ideal **Parameters:** -| Parameter | Type | Description | -|-----------|---------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Parameter | Type | Description | +|-----------|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `$config` | **array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int}** | Configuration options: - 'apiKey' (string, required): Your API token - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) @@ -47,14 +41,11 @@ public __construct(array{apiKey: string, apiUrl?: string, batchSize?: int, ideal - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) Example: -

- $_ENV['LINGODOTDEV_API_KEY'],
-    'batchSize' => 100,
-    'idealBatchItemSize' => 1000,
-]);
-
| + $engine = new LingoDotDevEngine([ + 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], + 'batchSize' => 100, + 'idealBatchItemSize' => 1000, + ]); | **Throws:** @@ -87,6 +78,11 @@ public localizeObject(array $obj, array{targetLocale: string, sour Translated data preserving original structure and non-text values +Example: + $content = ['greeting' => 'Hello']; + $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); + **Throws:** When required params or reference data are invalid @@ -120,6 +116,20 @@ public localizeText(string $text, array{targetLocale: string, sourceLocale?: str Translated text, or empty string if translation unavailable +Examples: + $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); + + $engine->localizeText( + 'This is a very long text that needs translation...', + ['sourceLocale' => 'en', 'targetLocale' => 'es'], + function (int $progress): void { + echo 'Translation progress: ' . $progress . "%%\n"; + } + ); + + $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); + **Throws:** When required params are missing or invalid @@ -134,15 +144,15 @@ When API rejects or fails to process the request Localize a string into multiple languages and return texts in order. ```php -public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales: array, fast?: bool} $params): string[] +public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales: string[], fast?: bool} $params): string[] ``` **Parameters:** -| Parameter | Type | Description | -|-----------|--------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate into multiple languages | -| `$params` | **array{sourceLocale: string, targetLocales: array, fast?: bool}** | Batch translation options shared by all target locales: +| Parameter | Type | Description | +|-----------|-----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `$text` | **string** | Text content to translate into multiple languages | +| `$params` | **array{sourceLocale: string, targetLocales: string[], fast?: bool}** | Batch translation options shared by all target locales: - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) - 'fast' (bool): Trade translation quality for speed | @@ -151,6 +161,13 @@ public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales Array of translated texts in same order as targetLocales parameter +Example: + $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $engine->batchLocalizeText('Hello, world!', [ + 'sourceLocale' => 'en', + 'targetLocales' => ['es', 'fr', 'de'], + ]); + **Throws:** When required params are missing or invalid @@ -165,7 +182,7 @@ When an individual localization request fails Localize a chat transcript while preserving speaker names. ```php -public localizeChat(array $chat, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array> +public localizeChat(array $chat, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array ``` **Parameters:** @@ -186,6 +203,14 @@ public localizeChat(array $chat, array{ta Translated messages keeping original speaker names unchanged +Example: + $conversation = [ + ['name' => 'Alice', 'text' => 'Hello, how are you?'], + ['name' => 'Bob', 'text' => 'I am fine, thank you!'], + ]; + $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); + **Throws:** When chat entries or params are invalid @@ -213,6 +238,10 @@ public recognizeLocale(string $text): string ISO language code detected by the API (e.g., 'en', 'es', 'zh') +Example: + $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $engine->recognizeLocale('Bonjour le monde'); + **Throws:** When input text is blank after trimming From 6282355de0d32f670b5f055bb63a330956bb888f Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 11:35:13 +1000 Subject: [PATCH 18/21] docs: update --- src/LingoDotDevEngine.php | 131 +++++++++++++++----------------------- 1 file changed, 52 insertions(+), 79 deletions(-) diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index 26e4b3e..b203158 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -54,12 +54,6 @@ class LingoDotDevEngine /** * Build an engine with your API key and optional batching limits. * - * @param array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config Configuration options: - * - 'apiKey' (string, required): Your API token - * - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) - * - 'batchSize' (int): Records per request, 1-250 (default: 25) - * - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) - * * Example: * $engine = new LingoDotDevEngine([ * 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], @@ -67,7 +61,9 @@ class LingoDotDevEngine * 'idealBatchItemSize' => 1000, * ]); * - * @throws \InvalidArgumentException When API key is missing or values fail validation + * @param array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config Configuration options + * + * @throws \InvalidArgumentException API key missing or values invalid */ public function __construct(array $config = []) { @@ -109,15 +105,11 @@ public function __construct(array $config = []) /** * Localize content using the Lingo.dev API. * - * @param array $payload Content to translate, structured as key-value pairs - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation configuration options: - * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection - * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param callable|null $progressCallback Callback invoked with completion percentage (0-100), current chunk, and processed chunk + * @param array $payload Content to translate + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation configuration + * @param callable|null $progressCallback Progress callback (0-100%, chunk, result) * - * @return array Translated content maintaining original structure + * @return array Translated content * * @internal */ @@ -168,18 +160,16 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres /** * Localize a single chunk of content. * - * @param string|null $sourceLocale Language code of the original text (e.g., 'en', 'es'), null for auto-detection - * @param string $targetLocale Language code to translate into (e.g., 'fr', 'de') - * @param array{data: array, reference?: array|null} $payload Content chunk with optional reference data for context. Expected keys: - * - 'data' (array): Chunk data submitted for translation - * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param string $workflowId Unique identifier for tracking related translation requests - * @param bool $fast Enable faster translation at potential quality tradeoff + * @param string|null $sourceLocale Source language code or null for auto-detect + * @param string $targetLocale Target language code + * @param array{data: array, reference?: array|null} $payload Content chunk with optional reference + * @param string $workflowId Workflow tracking ID + * @param bool $fast Fast mode flag * - * @return array Translated chunk maintaining original structure + * @return array Translated chunk * - * @throws \InvalidArgumentException When reference is not an array - * @throws \RuntimeException When API request fails + * @throws \InvalidArgumentException Invalid reference format + * @throws \RuntimeException API request failure */ private function _localizeChunk(?string $sourceLocale, string $targetLocale, array $payload, string $workflowId, bool $fast): array { @@ -314,23 +304,19 @@ private function _createId(): string /** * Localize every string in a nested array while keeping its shape intact. * - * @param array $obj Nested data structure containing text to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options controlling locale, speed, and contextual reference data: - * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection - * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param callable|null $progressCallback Invoked per batch with (percentage complete, current batch, translated batch) - * - * @return array Translated data preserving original structure and non-text values - * * Example: * $content = ['greeting' => 'Hello']; * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); * - * @throws \InvalidArgumentException When required params or reference data are invalid - * @throws \RuntimeException When API rejects or fails to process the request + * @param array $obj Nested data structure to translate + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param callable|null $progressCallback Progress callback (%, batch, result) + * + * @return array Translated data preserving structure + * + * @throws \InvalidArgumentException Invalid parameters or reference + * @throws \RuntimeException API request failure */ public function localizeObject(array $obj, array $params, ?callable $progressCallback = null): array { @@ -348,16 +334,6 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal /** * Localize a single string and return the translated text. * - * @param string $text Text content to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options such as locale hints, speed preference, and contextual references: - * - 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original text, null for auto-detection - * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param callable|null $progressCallback Called with completion percentage (0-100) during processing - * - * @return string Translated text, or empty string if translation unavailable - * * Examples: * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); @@ -372,8 +348,14 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * * $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); * - * @throws \InvalidArgumentException When required params are missing or invalid - * @throws \RuntimeException When API rejects or fails to process the request + * @param string $text Text to translate + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param callable|null $progressCallback Progress callback (0-100%) + * + * @return string Translated text or empty string + * + * @throws \InvalidArgumentException Missing or invalid parameters + * @throws \RuntimeException API request failure */ public function localizeText(string $text, array $params, ?callable $progressCallback = null): string { @@ -393,14 +375,6 @@ public function localizeText(string $text, array $params, ?callable $progressCal /** * Localize a string into multiple languages and return texts in order. * - * @param string $text Text content to translate into multiple languages - * @param array{sourceLocale: string, targetLocales: string[], fast?: bool} $params Batch translation options shared by all target locales: - * - 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') - * - 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) - * - 'fast' (bool): Trade translation quality for speed - * - * @return string[] Array of translated texts in same order as targetLocales parameter - * * Example: * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $engine->batchLocalizeText('Hello, world!', [ @@ -408,8 +382,13 @@ public function localizeText(string $text, array $params, ?callable $progressCal * 'targetLocales' => ['es', 'fr', 'de'], * ]); * - * @throws \InvalidArgumentException When required params are missing or invalid - * @throws \RuntimeException When an individual localization request fails + * @param string $text Text to translate + * @param array{sourceLocale: string, targetLocales: string[], fast?: bool} $params Batch translation options + * + * @return string[] Translated texts in targetLocales order + * + * @throws \InvalidArgumentException Missing or invalid parameters + * @throws \RuntimeException Individual request failure */ public function batchLocalizeText(string $text, array $params): array { @@ -438,18 +417,6 @@ public function batchLocalizeText(string $text, array $params): array /** * Localize a chat transcript while preserving speaker names. * - * @param array $chat Conversation history with speaker names and their messages. Each entry must include: - * - 'name' (string): Speaker label to preserve - * - 'text' (string): Message content to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Chat translation options defining locale behavior and context: - * - 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') - * - 'sourceLocale' (string|null): Language code of original messages, null for auto-detection - * - 'fast' (bool): Trade translation quality for speed - * - 'reference' (array|null): Context data or glossary terms to guide translation - * @param callable|null $progressCallback Called with completion percentage (0-100) during processing - * - * @return array Translated messages keeping original speaker names unchanged - * * Example: * $conversation = [ * ['name' => 'Alice', 'text' => 'Hello, how are you?'], @@ -458,8 +425,14 @@ public function batchLocalizeText(string $text, array $params): array * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); * - * @throws \InvalidArgumentException When chat entries or params are invalid - * @throws \RuntimeException When API rejects or fails to process the request + * @param array $chat Conversation with names and messages + * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param callable|null $progressCallback Progress callback (0-100%) + * + * @return array Translated chat preserving names + * + * @throws \InvalidArgumentException Invalid chat entries or parameters + * @throws \RuntimeException API request failure */ public function localizeChat(array $chat, array $params, ?callable $progressCallback = null): array { @@ -493,16 +466,16 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall /** * Identify the locale of the provided text. * - * @param string $text Sample text for language detection (longer text improves accuracy) - * - * @return string ISO language code detected by the API (e.g., 'en', 'es', 'zh') - * * Example: * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); * $engine->recognizeLocale('Bonjour le monde'); * - * @throws \InvalidArgumentException When input text is blank after trimming - * @throws \RuntimeException When API response is invalid or request fails + * @param string $text Sample text for language detection + * + * @return string ISO language code (e.g., 'en', 'es', 'zh') + * + * @throws \InvalidArgumentException Empty text provided + * @throws \RuntimeException Invalid API response or request failure */ public function recognizeLocale(string $text): string { From 4b7b899d602d75d1b67589018030b399c3d44248 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 01:35:35 +0000 Subject: [PATCH 19/21] docs: update markdown API reference [skip ci] --- .../LingoDotDev/Sdk/LingoDotDevEngine.md | 191 ++++++++---------- 1 file changed, 85 insertions(+), 106 deletions(-) diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index 788ae7e..62fbd1b 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -30,26 +30,22 @@ Build an engine with your API key and optional batching limits. public __construct(array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config = []): mixed ``` -**Parameters:** +Example: +$engine = new LingoDotDevEngine([ + 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], + 'batchSize' => 100, + 'idealBatchItemSize' => 1000, +]); -| Parameter | Type | Description | -|-----------|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$config` | **array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int}** | Configuration options: - - 'apiKey' (string, required): Your API token - - 'apiUrl' (string): API base URL (default: https://engine.lingo.dev) - - 'batchSize' (int): Records per request, 1-250 (default: 25) - - 'idealBatchItemSize' (int): Max words per request, 1-2500 (default: 250) +**Parameters:** -Example: - $engine = new LingoDotDevEngine([ - 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], - 'batchSize' => 100, - 'idealBatchItemSize' => 1000, - ]); | +| Parameter | Type | Description | +|-----------|---------------------------------------------------------------------------------------|-----------------------| +| `$config` | **array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int}** | Configuration options | **Throws:** -When API key is missing or values fail validation +API key missing or values invalid - [`InvalidArgumentException`](../../InvalidArgumentException) *** @@ -62,32 +58,28 @@ Localize every string in a nested array while keeping its shape intact. public localizeObject(array $obj, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array ``` +Example: +$content = ['greeting' => 'Hello']; +$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); + **Parameters:** -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$obj` | **array** | Nested data structure containing text to translate | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options controlling locale, speed, and contextual reference data: -- 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') -- 'sourceLocale' (string\|null): Language code of original text, null for auto-detection -- 'fast' (bool): Trade translation quality for speed -- 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Invoked per batch with (percentage complete, current batch, translated batch) | +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|--------------------------------------| +| `$obj` | **array** | Nested data structure to translate | +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (%, batch, result) | **Return Value:** -Translated data preserving original structure and non-text values - -Example: - $content = ['greeting' => 'Hello']; - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); +Translated data preserving structure **Throws:** -When required params or reference data are invalid +Invalid parameters or reference - [`InvalidArgumentException`](../../InvalidArgumentException) -When API rejects or fails to process the request +API request failure - [`RuntimeException`](../../RuntimeException) *** @@ -100,41 +92,37 @@ Localize a single string and return the translated text. public localizeText(string $text, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): string ``` -**Parameters:** +Examples: +$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options such as locale hints, speed preference, and contextual references: -- 'targetLocale' (string, required): Language code to translate into (e.g., 'es', 'fr') -- 'sourceLocale' (string\|null): Language code of original text, null for auto-detection -- 'fast' (bool): Trade translation quality for speed -- 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | +$engine->localizeText( + 'This is a very long text that needs translation...', + ['sourceLocale' => 'en', 'targetLocale' => 'es'], + function (int $progress): void { + echo 'Translation progress: ' . $progress . "%%\n"; + } +); -**Return Value:** +$engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); -Translated text, or empty string if translation unavailable +**Parameters:** -Examples: - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|----------------------------| +| `$text` | **string** | Text to translate | +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | - $engine->localizeText( - 'This is a very long text that needs translation...', - ['sourceLocale' => 'en', 'targetLocale' => 'es'], - function (int $progress): void { - echo 'Translation progress: ' . $progress . "%%\n"; - } - ); +**Return Value:** - $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); +Translated text or empty string **Throws:** -When required params are missing or invalid +Missing or invalid parameters - [`InvalidArgumentException`](../../InvalidArgumentException) -When API rejects or fails to process the request +API request failure - [`RuntimeException`](../../RuntimeException) *** @@ -147,32 +135,29 @@ Localize a string into multiple languages and return texts in order. public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales: string[], fast?: bool} $params): string[] ``` +Example: +$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$engine->batchLocalizeText('Hello, world!', [ + 'sourceLocale' => 'en', + 'targetLocales' => ['es', 'fr', 'de'], +]); + **Parameters:** -| Parameter | Type | Description | -|-----------|-----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$text` | **string** | Text content to translate into multiple languages | -| `$params` | **array{sourceLocale: string, targetLocales: string[], fast?: bool}** | Batch translation options shared by all target locales: -- 'sourceLocale' (string, required): Language code of the original text (e.g., 'en') -- 'targetLocales' (string[], required): Array of language codes to translate into (e.g., ['es', 'fr', 'de']) -- 'fast' (bool): Trade translation quality for speed | +| Parameter | Type | Description | +|-----------|-----------------------------------------------------------------------|---------------------------| +| `$text` | **string** | Text to translate | +| `$params` | **array{sourceLocale: string, targetLocales: string[], fast?: bool}** | Batch translation options | **Return Value:** -Array of translated texts in same order as targetLocales parameter - -Example: - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - $engine->batchLocalizeText('Hello, world!', [ - 'sourceLocale' => 'en', - 'targetLocales' => ['es', 'fr', 'de'], - ]); +Translated texts in targetLocales order **Throws:** -When required params are missing or invalid +Missing or invalid parameters - [`InvalidArgumentException`](../../InvalidArgumentException) -When an individual localization request fails +Individual request failure - [`RuntimeException`](../../RuntimeException) *** @@ -185,37 +170,31 @@ Localize a chat transcript while preserving speaker names. public localizeChat(array $chat, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array ``` +Example: +$conversation = [ + ['name' => 'Alice', 'text' => 'Hello, how are you?'], + ['name' => 'Bob', 'text' => 'I am fine, thank you!'], +]; +$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); + **Parameters:** -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `$chat` | **array** | Conversation history with speaker names and their messages. Each entry must include: -- 'name' (string): Speaker label to preserve -- 'text' (string): Message content to translate | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Chat translation options defining locale behavior and context: -- 'targetLocale' (string, required): Language code to translate messages into (e.g., 'es', 'fr') -- 'sourceLocale' (string\|null): Language code of original messages, null for auto-detection -- 'fast' (bool): Trade translation quality for speed -- 'reference' (array\|null): Context data or glossary terms to guide translation | -| `$progressCallback` | **callable\|null** | Called with completion percentage (0-100) during processing | +| Parameter | Type | Description | +|---------------------|------------------------------------------------------------------------------------------------------------------|--------------------------------------| +| `$chat` | **array** | Conversation with names and messages | +| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | **Return Value:** -Translated messages keeping original speaker names unchanged - -Example: - $conversation = [ - ['name' => 'Alice', 'text' => 'Hello, how are you?'], - ['name' => 'Bob', 'text' => 'I am fine, thank you!'], - ]; - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); +Translated chat preserving names **Throws:** -When chat entries or params are invalid +Invalid chat entries or parameters - [`InvalidArgumentException`](../../InvalidArgumentException) -When API rejects or fails to process the request +API request failure - [`RuntimeException`](../../RuntimeException) *** @@ -228,25 +207,25 @@ Identify the locale of the provided text. public recognizeLocale(string $text): string ``` +Example: +$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$engine->recognizeLocale('Bonjour le monde'); + **Parameters:** -| Parameter | Type | Description | -|-----------|------------|--------------------------------------------------------------------| -| `$text` | **string** | Sample text for language detection (longer text improves accuracy) | +| Parameter | Type | Description | +|-----------|------------|------------------------------------| +| `$text` | **string** | Sample text for language detection | **Return Value:** -ISO language code detected by the API (e.g., 'en', 'es', 'zh') - -Example: - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - $engine->recognizeLocale('Bonjour le monde'); +ISO language code (e.g., 'en', 'es', 'zh') **Throws:** -When input text is blank after trimming +Empty text provided - [`InvalidArgumentException`](../../InvalidArgumentException) -When API response is invalid or request fails +Invalid API response or request failure - [`RuntimeException`](../../RuntimeException) *** From ec50c130790093d8edfa7e2b0443434b80a41122 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 19 Sep 2025 11:44:01 +1000 Subject: [PATCH 20/21] feat: refactor api --- src/BatchTranslationOptions.php | 89 +++++++++++++++ src/EngineConfig.php | 89 +++++++++++++++ src/LingoDotDevEngine.php | 196 +++++++++++++++----------------- src/TranslationOptions.php | 94 +++++++++++++++ 4 files changed, 361 insertions(+), 107 deletions(-) create mode 100644 src/BatchTranslationOptions.php create mode 100644 src/EngineConfig.php create mode 100644 src/TranslationOptions.php diff --git a/src/BatchTranslationOptions.php b/src/BatchTranslationOptions.php new file mode 100644 index 0000000..1823d23 --- /dev/null +++ b/src/BatchTranslationOptions.php @@ -0,0 +1,89 @@ + + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ + +namespace LingoDotDev\Sdk; + +/** + * Options for batch text translation to multiple languages. + * + * @category Localization + * @package Lingodotdev\Sdk + * @author Lingo.dev Team + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ +class BatchTranslationOptions +{ + /** + * Source language code (e.g., 'en') + * Required field. + */ + public string $sourceLocale; + + /** + * Array of target language codes (e.g., ['es', 'fr', 'de']) + * Required field. + * + * @var string[] + */ + public array $targetLocales; + + /** + * Enable fast mode - trades translation quality for speed + * Default: false (quality mode) + */ + public bool $fast = false; + + + /** + * Create a fluent builder for batch translation options. + * + * @param string $sourceLocale Source language code + */ + public static function create(string $sourceLocale): self + { + $instance = new self(); + $instance->sourceLocale = $sourceLocale; + $instance->targetLocales = []; + return $instance; + } + + /** + * Set target locales. + * + * @param string[] $locales Target language codes + */ + public function to(array $locales): self + { + $this->targetLocales = $locales; + return $this; + } + + /** + * Add a single target locale. + * + * @param string $locale Target language code + */ + public function addTarget(string $locale): self + { + $this->targetLocales[] = $locale; + return $this; + } + + /** + * Enable fast translation mode. + */ + public function withFastMode(): self + { + $this->fast = true; + return $this; + } +} \ No newline at end of file diff --git a/src/EngineConfig.php b/src/EngineConfig.php new file mode 100644 index 0000000..e1b599a --- /dev/null +++ b/src/EngineConfig.php @@ -0,0 +1,89 @@ + + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ + +namespace LingoDotDev\Sdk; + +/** + * Configuration for LingoDotDevEngine initialization. + * + * @category Localization + * @package Lingodotdev\Sdk + * @author Lingo.dev Team + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ +class EngineConfig +{ + /** + * Your Lingo.dev API token + */ + public string $apiKey; + + /** + * API base URL (default: https://engine.lingo.dev) + */ + public string $apiUrl = 'https://engine.lingo.dev'; + + /** + * Maximum records per request (1-250, default: 25) + */ + public int $batchSize = 25; + + /** + * Maximum words per request (1-2500, default: 250) + */ + public int $idealBatchItemSize = 250; + + /** + * Create configuration with API key. + * + * @param string $apiKey Your Lingo.dev API token + */ + public static function create(string $apiKey): self + { + $instance = new self(); + $instance->apiKey = $apiKey; + return $instance; + } + + /** + * Set custom API URL. + * + * @param string $url API endpoint URL + */ + public function withApiUrl(string $url): self + { + $this->apiUrl = $url; + return $this; + } + + /** + * Set batch size limit. + * + * @param int $size Records per request (1-250) + */ + public function withBatchSize(int $size): self + { + $this->batchSize = $size; + return $this; + } + + /** + * Set ideal batch item size. + * + * @param int $size Max words per request (1-2500) + */ + public function withIdealBatchItemSize(int $size): self + { + $this->idealBatchItemSize = $size; + return $this; + } +} \ No newline at end of file diff --git a/src/LingoDotDevEngine.php b/src/LingoDotDevEngine.php index b203158..5d4458b 100644 --- a/src/LingoDotDevEngine.php +++ b/src/LingoDotDevEngine.php @@ -23,11 +23,16 @@ * progress reporting, and surfacing validation or transport errors. * * Example (basic setup): - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); * * Example (Laravel integration): - * $engine = new LingoDotDevEngine(['apiKey' => config('services.lingodotdev.api_key')]); - * $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']); + * $config = EngineConfig::create(config('services.lingodotdev.api_key')) + * ->withBatchSize(100); + * $engine = new LingoDotDevEngine($config); + * + * $options = TranslationOptions::create('es')->from('en'); + * $engine->localizeText($request->message, $options); * * @category Localization * @package Lingodotdev\Sdk @@ -40,9 +45,9 @@ class LingoDotDevEngine /** * Configuration options for the Engine. * - * @var array{apiKey: string, apiUrl: string, batchSize: int, idealBatchItemSize: int} + * @var EngineConfig */ - protected $config; + protected EngineConfig $config; /** * HTTP client for API requests. @@ -52,51 +57,44 @@ class LingoDotDevEngine private $_httpClient; /** - * Build an engine with your API key and optional batching limits. + * Build an engine with your configuration. * * Example: - * $engine = new LingoDotDevEngine([ - * 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], - * 'batchSize' => 100, - * 'idealBatchItemSize' => 1000, - * ]); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']) + * ->withBatchSize(100) + * ->withIdealBatchItemSize(1000); + * $engine = new LingoDotDevEngine($config); * - * @param array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config Configuration options + * @param EngineConfig $config Engine configuration * - * @throws \InvalidArgumentException API key missing or values invalid + * @throws \InvalidArgumentException Invalid configuration values */ - public function __construct(array $config = []) + public function __construct(EngineConfig $config) { - $this->config = array_merge( - [ - 'apiUrl' => 'https://engine.lingo.dev', - 'batchSize' => 25, - 'idealBatchItemSize' => 250 - ], $config - ); + $this->config = $config; - if (!isset($this->config['apiKey'])) { + if (empty($this->config->apiKey)) { throw new \InvalidArgumentException('API key is required'); } - if (!filter_var($this->config['apiUrl'], FILTER_VALIDATE_URL)) { + if (!filter_var($this->config->apiUrl, FILTER_VALIDATE_URL)) { throw new \InvalidArgumentException('API URL must be a valid URL'); } - if (!is_int($this->config['batchSize']) || $this->config['batchSize'] <= 0 || $this->config['batchSize'] > 250) { - throw new \InvalidArgumentException('Batch size must be an integer between 1 and 250'); + if ($this->config->batchSize <= 0 || $this->config->batchSize > 250) { + throw new \InvalidArgumentException('Batch size must be between 1 and 250'); } - if (!is_int($this->config['idealBatchItemSize']) || $this->config['idealBatchItemSize'] <= 0 || $this->config['idealBatchItemSize'] > 2500) { - throw new \InvalidArgumentException('Ideal batch item size must be an integer between 1 and 2500'); + if ($this->config->idealBatchItemSize <= 0 || $this->config->idealBatchItemSize > 2500) { + throw new \InvalidArgumentException('Ideal batch item size must be between 1 and 2500'); } $this->_httpClient = new Client( [ - 'base_uri' => $this->config['apiUrl'], + 'base_uri' => $this->config->apiUrl, 'headers' => [ 'Content-Type' => 'application/json; charset=utf-8', - 'Authorization' => 'Bearer ' . $this->config['apiKey'] + 'Authorization' => 'Bearer ' . $this->config->apiKey ] ] ); @@ -106,27 +104,15 @@ public function __construct(array $config = []) * Localize content using the Lingo.dev API. * * @param array $payload Content to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation configuration + * @param TranslationOptions $options Translation configuration * @param callable|null $progressCallback Progress callback (0-100%, chunk, result) * * @return array Translated content * * @internal */ - protected function localizeRaw(array $payload, array $params, ?callable $progressCallback = null): array + protected function localizeRaw(array $payload, TranslationOptions $options, ?callable $progressCallback = null): array { - if (!isset($params['targetLocale'])) { - throw new \InvalidArgumentException('Target locale is required'); - } - - if (isset($params['sourceLocale']) && !is_string($params['sourceLocale']) && $params['sourceLocale'] !== null) { - throw new \InvalidArgumentException('Source locale must be a string or null'); - } - - if (!is_string($params['targetLocale'])) { - throw new \InvalidArgumentException('Target locale must be a string'); - } - $chunkedPayload = $this->_extractPayloadChunks($payload); $processedPayloadChunks = []; @@ -137,14 +123,14 @@ protected function localizeRaw(array $payload, array $params, ?callable $progres $percentageCompleted = round((($i + 1) / count($chunkedPayload)) * 100); $processedPayloadChunk = $this->_localizeChunk( - $params['sourceLocale'] ?? null, - $params['targetLocale'], + $options->sourceLocale, + $options->targetLocale, [ - 'data' => $chunk, - 'reference' => $params['reference'] ?? null + 'data' => $chunk, + 'reference' => $options->reference ], $workflowId, - $params['fast'] ?? false + $options->fast ); if ($progressCallback) { @@ -249,9 +235,9 @@ private function _extractPayloadChunks(array $payload): array $currentChunkItemCount++; $currentChunkSize = $this->_countWordsInRecord($currentChunk); - - if ($currentChunkSize > $this->config['idealBatchItemSize'] - || $currentChunkItemCount >= $this->config['batchSize'] + + if ($currentChunkSize > $this->config->idealBatchItemSize + || $currentChunkItemCount >= $this->config->batchSize || $i === count($keys) - 1 ) { $result[] = $currentChunk; @@ -305,26 +291,22 @@ private function _createId(): string * Localize every string in a nested array while keeping its shape intact. * * Example: - * $content = ['greeting' => 'Hello']; - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - * $engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); + * $options = TranslationOptions::create('fr')->from('en'); + * $engine->localizeObject(['greeting' => 'Hello'], $options); * * @param array $obj Nested data structure to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param TranslationOptions $options Translation options * @param callable|null $progressCallback Progress callback (%, batch, result) * * @return array Translated data preserving structure * - * @throws \InvalidArgumentException Invalid parameters or reference * @throws \RuntimeException API request failure */ - public function localizeObject(array $obj, array $params, ?callable $progressCallback = null): array + public function localizeObject(array $obj, TranslationOptions $options, ?callable $progressCallback = null): array { - if (!isset($params['targetLocale'])) { - throw new \InvalidArgumentException('Target locale is required'); - } - - return $this->localizeRaw($obj, $params, function($progress, $chunk, $processedChunk) use ($progressCallback) { + return $this->localizeRaw($obj, $options, function($progress, $chunk, $processedChunk) use ($progressCallback) { if ($progressCallback) { $progressCallback($progress, $chunk, $processedChunk); } @@ -335,40 +317,42 @@ public function localizeObject(array $obj, array $params, ?callable $progressCal * Localize a single string and return the translated text. * * Examples: - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - * $engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); + * + * // Simple translation + * $options = TranslationOptions::create('es')->from('en'); + * $engine->localizeText('Hello, world!', $options); * + * // With progress callback * $engine->localizeText( - * 'This is a very long text that needs translation...', - * ['sourceLocale' => 'en', 'targetLocale' => 'es'], + * 'This is a very long text...', + * $options, * function (int $progress): void { - * echo 'Translation progress: ' . $progress . "%\n"; + * echo "Progress: {$progress}%\n"; * } * ); * - * $engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); + * // Auto-detect source language + * $options = TranslationOptions::create('en'); + * $engine->localizeText('Bonjour le monde', $options); * * @param string $text Text to translate - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param TranslationOptions $options Translation options * @param callable|null $progressCallback Progress callback (0-100%) * * @return string Translated text or empty string * - * @throws \InvalidArgumentException Missing or invalid parameters * @throws \RuntimeException API request failure */ - public function localizeText(string $text, array $params, ?callable $progressCallback = null): string + public function localizeText(string $text, TranslationOptions $options, ?callable $progressCallback = null): string { - if (!isset($params['targetLocale'])) { - throw new \InvalidArgumentException('Target locale is required'); - } - - $response = $this->localizeRaw(['text' => $text], $params, function($progress, $chunk, $processedChunk) use ($progressCallback) { + $response = $this->localizeRaw(['text' => $text], $options, function($progress, $chunk, $processedChunk) use ($progressCallback) { if ($progressCallback) { $progressCallback($progress); } }); - + return $response['text'] ?? ''; } @@ -376,39 +360,33 @@ public function localizeText(string $text, array $params, ?callable $progressCal * Localize a string into multiple languages and return texts in order. * * Example: - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - * $engine->batchLocalizeText('Hello, world!', [ - * 'sourceLocale' => 'en', - * 'targetLocales' => ['es', 'fr', 'de'], - * ]); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); + * + * $options = BatchTranslationOptions::create('en') + * ->to(['es', 'fr', 'de']) + * ->withFastMode(); + * $engine->batchLocalizeText('Hello, world!', $options); * * @param string $text Text to translate - * @param array{sourceLocale: string, targetLocales: string[], fast?: bool} $params Batch translation options + * @param BatchTranslationOptions $options Batch translation options * * @return string[] Translated texts in targetLocales order * - * @throws \InvalidArgumentException Missing or invalid parameters * @throws \RuntimeException Individual request failure */ - public function batchLocalizeText(string $text, array $params): array + public function batchLocalizeText(string $text, BatchTranslationOptions $options): array { - if (!isset($params['sourceLocale'])) { - throw new \InvalidArgumentException('Source locale is required'); - } + $responses = []; + foreach ($options->targetLocales as $targetLocale) { + $translationOptions = TranslationOptions::create($targetLocale) + ->from($options->sourceLocale); - if (!isset($params['targetLocales']) || !is_array($params['targetLocales'])) { - throw new \InvalidArgumentException('Target locales must be an array'); - } + if ($options->fast) { + $translationOptions->withFastMode(); + } - $responses = []; - foreach ($params['targetLocales'] as $targetLocale) { - $responses[] = $this->localizeText( - $text, [ - 'sourceLocale' => $params['sourceLocale'], - 'targetLocale' => $targetLocale, - 'fast' => $params['fast'] ?? false - ] - ); + $responses[] = $this->localizeText($text, $translationOptions); } return $responses; @@ -422,19 +400,22 @@ public function batchLocalizeText(string $text, array $params): array * ['name' => 'Alice', 'text' => 'Hello, how are you?'], * ['name' => 'Bob', 'text' => 'I am fine, thank you!'], * ]; - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); - * $engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); + * + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); + * $options = TranslationOptions::create('de')->from('en'); + * $engine->localizeChat($conversation, $options); * * @param array $chat Conversation with names and messages - * @param array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params Translation options + * @param TranslationOptions $options Translation options * @param callable|null $progressCallback Progress callback (0-100%) * * @return array Translated chat preserving names * - * @throws \InvalidArgumentException Invalid chat entries or parameters + * @throws \InvalidArgumentException Invalid chat entries * @throws \RuntimeException API request failure */ - public function localizeChat(array $chat, array $params, ?callable $progressCallback = null): array + public function localizeChat(array $chat, TranslationOptions $options, ?callable $progressCallback = null): array { foreach ($chat as $message) { if (!isset($message['name']) || !isset($message['text'])) { @@ -442,7 +423,7 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall } } - $localized = $this->localizeRaw(['chat' => $chat], $params, function($progress, $chunk, $processedChunk) use ($progressCallback) { + $localized = $this->localizeRaw(['chat' => $chat], $options, function($progress, $chunk, $processedChunk) use ($progressCallback) { if ($progressCallback) { $progressCallback($progress); } @@ -467,7 +448,8 @@ public function localizeChat(array $chat, array $params, ?callable $progressCall * Identify the locale of the provided text. * * Example: - * $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + * $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + * $engine = new LingoDotDevEngine($config); * $engine->recognizeLocale('Bonjour le monde'); * * @param string $text Sample text for language detection diff --git a/src/TranslationOptions.php b/src/TranslationOptions.php new file mode 100644 index 0000000..d4d6b3f --- /dev/null +++ b/src/TranslationOptions.php @@ -0,0 +1,94 @@ + + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ + +namespace LingoDotDev\Sdk; + +/** + * Options for text and object translation. + * + * @category Localization + * @package Lingodotdev\Sdk + * @author Lingo.dev Team + * @license MIT https://opensource.org/licenses/MIT + * @link https://lingo.dev + */ +class TranslationOptions +{ + /** + * Target language code (e.g., 'es', 'fr') + * Required field. + */ + public string $targetLocale; + + /** + * Source language code or null for auto-detection + * Example: 'en', 'es', or null + */ + public ?string $sourceLocale = null; + + /** + * Enable fast mode - trades translation quality for speed + * Default: false (quality mode) + */ + public bool $fast = false; + + /** + * Context data or glossary terms to guide translation + * Can include domain-specific terminology or reference translations + * + * @var array|null + */ + public ?array $reference = null; + + + /** + * Create a fluent builder for translation options. + * + * @param string $targetLocale Target language code + */ + public static function create(string $targetLocale): self + { + $instance = new self(); + $instance->targetLocale = $targetLocale; + return $instance; + } + + /** + * Set source locale. + * + * @param string|null $locale Source language code or null for auto-detection + */ + public function from(?string $locale): self + { + $this->sourceLocale = $locale; + return $this; + } + + /** + * Enable fast translation mode. + */ + public function withFastMode(): self + { + $this->fast = true; + return $this; + } + + /** + * Add reference data for context. + * + * @param array $reference Context or glossary data + */ + public function withReference(array $reference): self + { + $this->reference = $reference; + return $this; + } +} \ No newline at end of file From f834ef42a1ebd76bd2de53214c0c119b57985393 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 19 Sep 2025 01:44:23 +0000 Subject: [PATCH 21/21] docs: update markdown API reference [skip ci] --- docs/Home.md | 9 +- .../Sdk/BatchTranslationOptions.md | 106 ++++++++++++++ docs/classes/LingoDotDev/Sdk/EngineConfig.md | 119 ++++++++++++++++ .../LingoDotDev/Sdk/LingoDotDevEngine.md | 134 ++++++++++-------- .../LingoDotDev/Sdk/TranslationOptions.md | 117 +++++++++++++++ 5 files changed, 421 insertions(+), 64 deletions(-) create mode 100644 docs/classes/LingoDotDev/Sdk/BatchTranslationOptions.md create mode 100644 docs/classes/LingoDotDev/Sdk/EngineConfig.md create mode 100644 docs/classes/LingoDotDev/Sdk/TranslationOptions.md diff --git a/docs/Home.md b/docs/Home.md index 0fddc01..7d3a39e 100644 --- a/docs/Home.md +++ b/docs/Home.md @@ -7,6 +7,9 @@ This is an automatically generated documentation for **PHP SDK for Lingo.dev**. #### Classes -| Class | Description | -|--------------------------------------------------------------------|---------------------------------------------------------------------------| -| [`LingoDotDevEngine`](./classes/LingoDotDev/Sdk/LingoDotDevEngine) | LingoDotDevEngine wraps the Lingo.dev localization API for PHP consumers. | +| Class | Description | +|--------------------------------------------------------------------------------|---------------------------------------------------------------------------| +| [`BatchTranslationOptions`](./classes/LingoDotDev/Sdk/BatchTranslationOptions) | Options for batch text translation to multiple languages. | +| [`EngineConfig`](./classes/LingoDotDev/Sdk/EngineConfig) | Configuration for LingoDotDevEngine initialization. | +| [`LingoDotDevEngine`](./classes/LingoDotDev/Sdk/LingoDotDevEngine) | LingoDotDevEngine wraps the Lingo.dev localization API for PHP consumers. | +| [`TranslationOptions`](./classes/LingoDotDev/Sdk/TranslationOptions) | Options for text and object translation. | diff --git a/docs/classes/LingoDotDev/Sdk/BatchTranslationOptions.md b/docs/classes/LingoDotDev/Sdk/BatchTranslationOptions.md new file mode 100644 index 0000000..9f13249 --- /dev/null +++ b/docs/classes/LingoDotDev/Sdk/BatchTranslationOptions.md @@ -0,0 +1,106 @@ + +Options for batch text translation to multiple languages. + +*** + +* Full name: `\LingoDotDev\Sdk\BatchTranslationOptions` + +**See Also:** + +* https://lingo.dev + +## Properties + +### sourceLocale + +Source language code (e.g., 'en') +Required field. + +```php +public string $sourceLocale +``` + +*** + +### targetLocales + +Array of target language codes (e.g., ['es', 'fr', 'de']) +Required field. + +```php +public string[] $targetLocales +``` + +*** + +### fast + +Enable fast mode - trades translation quality for speed +Default: false (quality mode) + +```php +public bool $fast +``` + +*** + +## Methods + +### create + +Create a fluent builder for batch translation options. + +```php +public static create(string $sourceLocale): self +``` + +* This method is **static**. +**Parameters:** + +| Parameter | Type | Description | +|-----------------|------------|----------------------| +| `$sourceLocale` | **string** | Source language code | + +*** + +### to + +Set target locales. + +```php +public to(string[] $locales): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|------------|--------------|-----------------------| +| `$locales` | **string[]** | Target language codes | + +*** + +### addTarget + +Add a single target locale. + +```php +public addTarget(string $locale): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|------------|----------------------| +| `$locale` | **string** | Target language code | + +*** + +### withFastMode + +Enable fast translation mode. + +```php +public withFastMode(): self +``` + +*** diff --git a/docs/classes/LingoDotDev/Sdk/EngineConfig.md b/docs/classes/LingoDotDev/Sdk/EngineConfig.md new file mode 100644 index 0000000..883f1fb --- /dev/null +++ b/docs/classes/LingoDotDev/Sdk/EngineConfig.md @@ -0,0 +1,119 @@ + +Configuration for LingoDotDevEngine initialization. + +*** + +* Full name: `\LingoDotDev\Sdk\EngineConfig` + +**See Also:** + +* https://lingo.dev + +## Properties + +### apiKey + +Your Lingo.dev API token + +```php +public string $apiKey +``` + +*** + +### apiUrl + +API base URL (default: https://engine.lingo.dev) + +```php +public string $apiUrl +``` + +*** + +### batchSize + +Maximum records per request (1-250, default: 25) + +```php +public int $batchSize +``` + +*** + +### idealBatchItemSize + +Maximum words per request (1-2500, default: 250) + +```php +public int $idealBatchItemSize +``` + +*** + +## Methods + +### create + +Create configuration with API key. + +```php +public static create(string $apiKey): self +``` + +* This method is **static**. +**Parameters:** + +| Parameter | Type | Description | +|-----------|------------|--------------------------| +| `$apiKey` | **string** | Your Lingo.dev API token | + +*** + +### withApiUrl + +Set custom API URL. + +```php +public withApiUrl(string $url): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|------------|------------------| +| `$url` | **string** | API endpoint URL | + +*** + +### withBatchSize + +Set batch size limit. + +```php +public withBatchSize(int $size): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|---------|-----------------------------| +| `$size` | **int** | Records per request (1-250) | + +*** + +### withIdealBatchItemSize + +Set ideal batch item size. + +```php +public withIdealBatchItemSize(int $size): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|---------|--------------------------------| +| `$size` | **int** | Max words per request (1-2500) | + +*** diff --git a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md index 62fbd1b..6780d95 100644 --- a/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md +++ b/docs/classes/LingoDotDev/Sdk/LingoDotDevEngine.md @@ -6,11 +6,16 @@ to detect the locale of free-form text. The engine handles request batching, progress reporting, and surfacing validation or transport errors. Example (basic setup): - $engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); + $config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); + $engine = new LingoDotDevEngine($config); Example (Laravel integration): - $engine = new LingoDotDevEngine(['apiKey' => config('services.lingodotdev.api_key')]); - $engine->localizeText($request->message, ['sourceLocale' => 'en', 'targetLocale' => 'es']); + $config = EngineConfig::create(config('services.lingodotdev.api_key')) + ->withBatchSize(100); + $engine = new LingoDotDevEngine($config); + + $options = TranslationOptions::create('es')->from('en'); + $engine->localizeText($request->message, $options); *** @@ -24,28 +29,27 @@ Example (Laravel integration): ### __construct -Build an engine with your API key and optional batching limits. +Build an engine with your configuration. ```php -public __construct(array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int} $config = []): mixed +public __construct(\LingoDotDev\Sdk\EngineConfig $config): mixed ``` Example: -$engine = new LingoDotDevEngine([ - 'apiKey' => $_ENV['LINGODOTDEV_API_KEY'], - 'batchSize' => 100, - 'idealBatchItemSize' => 1000, -]); +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']) + ->withBatchSize(100) + ->withIdealBatchItemSize(1000); +$engine = new LingoDotDevEngine($config); **Parameters:** -| Parameter | Type | Description | -|-----------|---------------------------------------------------------------------------------------|-----------------------| -| `$config` | **array{apiKey: string, apiUrl?: string, batchSize?: int, idealBatchItemSize?: int}** | Configuration options | +| Parameter | Type | Description | +|-----------|-----------------------------------|----------------------| +| `$config` | **\LingoDotDev\Sdk\EngineConfig** | Engine configuration | **Throws:** -API key missing or values invalid +Invalid configuration values - [`InvalidArgumentException`](../../InvalidArgumentException) *** @@ -55,21 +59,22 @@ API key missing or values invalid Localize every string in a nested array while keeping its shape intact. ```php -public localizeObject(array $obj, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array +public localizeObject(array $obj, \LingoDotDev\Sdk\TranslationOptions $options, callable|null $progressCallback = null): array ``` Example: -$content = ['greeting' => 'Hello']; -$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); -$engine->localizeObject($content, ['sourceLocale' => 'en', 'targetLocale' => 'fr']); +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); +$engine = new LingoDotDevEngine($config); +$options = TranslationOptions::create('fr')->from('en'); +$engine->localizeObject(['greeting' => 'Hello'], $options); **Parameters:** -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|--------------------------------------| -| `$obj` | **array** | Nested data structure to translate | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | -| `$progressCallback` | **callable\|null** | Progress callback (%, batch, result) | +| Parameter | Type | Description | +|---------------------|-----------------------------------------|--------------------------------------| +| `$obj` | **array** | Nested data structure to translate | +| `$options` | **\LingoDotDev\Sdk\TranslationOptions** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (%, batch, result) | **Return Value:** @@ -77,8 +82,6 @@ Translated data preserving structure **Throws:** -Invalid parameters or reference -- [`InvalidArgumentException`](../../InvalidArgumentException) API request failure - [`RuntimeException`](../../RuntimeException) @@ -89,30 +92,37 @@ API request failure Localize a single string and return the translated text. ```php -public localizeText(string $text, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): string +public localizeText(string $text, \LingoDotDev\Sdk\TranslationOptions $options, callable|null $progressCallback = null): string ``` Examples: -$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); -$engine->localizeText('Hello, world!', ['sourceLocale' => 'en', 'targetLocale' => 'es']); +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); +$engine = new LingoDotDevEngine($config); +// Simple translation +$options = TranslationOptions::create('es')->from('en'); +$engine->localizeText('Hello, world!', $options); + +// With progress callback $engine->localizeText( - 'This is a very long text that needs translation...', - ['sourceLocale' => 'en', 'targetLocale' => 'es'], + 'This is a very long text...', + $options, function (int $progress): void { - echo 'Translation progress: ' . $progress . "%%\n"; + echo "Progress: {$progress}%%\n"; } ); -$engine->localizeText('Bonjour le monde', ['sourceLocale' => null, 'targetLocale' => 'en']); +// Auto-detect source language +$options = TranslationOptions::create('en'); +$engine->localizeText('Bonjour le monde', $options); **Parameters:** -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|----------------------------| -| `$text` | **string** | Text to translate | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | -| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | +| Parameter | Type | Description | +|---------------------|-----------------------------------------|----------------------------| +| `$text` | **string** | Text to translate | +| `$options` | **\LingoDotDev\Sdk\TranslationOptions** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | **Return Value:** @@ -120,8 +130,6 @@ Translated text or empty string **Throws:** -Missing or invalid parameters -- [`InvalidArgumentException`](../../InvalidArgumentException) API request failure - [`RuntimeException`](../../RuntimeException) @@ -132,22 +140,24 @@ API request failure Localize a string into multiple languages and return texts in order. ```php -public batchLocalizeText(string $text, array{sourceLocale: string, targetLocales: string[], fast?: bool} $params): string[] +public batchLocalizeText(string $text, \LingoDotDev\Sdk\BatchTranslationOptions $options): string[] ``` Example: -$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); -$engine->batchLocalizeText('Hello, world!', [ - 'sourceLocale' => 'en', - 'targetLocales' => ['es', 'fr', 'de'], -]); +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); +$engine = new LingoDotDevEngine($config); + +$options = BatchTranslationOptions::create('en') + ->to(['es', 'fr', 'de']) + ->withFastMode(); +$engine->batchLocalizeText('Hello, world!', $options); **Parameters:** -| Parameter | Type | Description | -|-----------|-----------------------------------------------------------------------|---------------------------| -| `$text` | **string** | Text to translate | -| `$params` | **array{sourceLocale: string, targetLocales: string[], fast?: bool}** | Batch translation options | +| Parameter | Type | Description | +|------------|----------------------------------------------|---------------------------| +| `$text` | **string** | Text to translate | +| `$options` | **\LingoDotDev\Sdk\BatchTranslationOptions** | Batch translation options | **Return Value:** @@ -155,8 +165,6 @@ Translated texts in targetLocales order **Throws:** -Missing or invalid parameters -- [`InvalidArgumentException`](../../InvalidArgumentException) Individual request failure - [`RuntimeException`](../../RuntimeException) @@ -167,7 +175,7 @@ Individual request failure Localize a chat transcript while preserving speaker names. ```php -public localizeChat(array $chat, array{targetLocale: string, sourceLocale?: string|null, fast?: bool, reference?: array|null} $params, callable|null $progressCallback = null): array +public localizeChat(array $chat, \LingoDotDev\Sdk\TranslationOptions $options, callable|null $progressCallback = null): array ``` Example: @@ -175,16 +183,19 @@ $conversation = [ ['name' => 'Alice', 'text' => 'Hello, how are you?'], ['name' => 'Bob', 'text' => 'I am fine, thank you!'], ]; -$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); -$engine->localizeChat($conversation, ['sourceLocale' => 'en', 'targetLocale' => 'de']); + +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); +$engine = new LingoDotDevEngine($config); +$options = TranslationOptions::create('de')->from('en'); +$engine->localizeChat($conversation, $options); **Parameters:** -| Parameter | Type | Description | -|---------------------|------------------------------------------------------------------------------------------------------------------|--------------------------------------| -| `$chat` | **array** | Conversation with names and messages | -| `$params` | **array{targetLocale: string, sourceLocale?: string\|null, fast?: bool, reference?: array\|null}** | Translation options | -| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | +| Parameter | Type | Description | +|---------------------|--------------------------------------------------|--------------------------------------| +| `$chat` | **array** | Conversation with names and messages | +| `$options` | **\LingoDotDev\Sdk\TranslationOptions** | Translation options | +| `$progressCallback` | **callable\|null** | Progress callback (0-100%) | **Return Value:** @@ -192,7 +203,7 @@ Translated chat preserving names **Throws:** -Invalid chat entries or parameters +Invalid chat entries - [`InvalidArgumentException`](../../InvalidArgumentException) API request failure - [`RuntimeException`](../../RuntimeException) @@ -208,7 +219,8 @@ public recognizeLocale(string $text): string ``` Example: -$engine = new LingoDotDevEngine(['apiKey' => $_ENV['LINGODOTDEV_API_KEY']]); +$config = EngineConfig::create($_ENV['LINGODOTDEV_API_KEY']); +$engine = new LingoDotDevEngine($config); $engine->recognizeLocale('Bonjour le monde'); **Parameters:** diff --git a/docs/classes/LingoDotDev/Sdk/TranslationOptions.md b/docs/classes/LingoDotDev/Sdk/TranslationOptions.md new file mode 100644 index 0000000..af57853 --- /dev/null +++ b/docs/classes/LingoDotDev/Sdk/TranslationOptions.md @@ -0,0 +1,117 @@ + +Options for text and object translation. + +*** + +* Full name: `\LingoDotDev\Sdk\TranslationOptions` + +**See Also:** + +* https://lingo.dev + +## Properties + +### targetLocale + +Target language code (e.g., 'es', 'fr') +Required field. + +```php +public string $targetLocale +``` + +*** + +### sourceLocale + +Source language code or null for auto-detection +Example: 'en', 'es', or null + +```php +public ?string $sourceLocale +``` + +*** + +### fast + +Enable fast mode - trades translation quality for speed +Default: false (quality mode) + +```php +public bool $fast +``` + +*** + +### reference + +Context data or glossary terms to guide translation +Can include domain-specific terminology or reference translations + +```php +public array|null $reference +``` + +*** + +## Methods + +### create + +Create a fluent builder for translation options. + +```php +public static create(string $targetLocale): self +``` + +* This method is **static**. +**Parameters:** + +| Parameter | Type | Description | +|-----------------|------------|----------------------| +| `$targetLocale` | **string** | Target language code | + +*** + +### from + +Set source locale. + +```php +public from(string|null $locale): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|-----------|------------------|-------------------------------------------------| +| `$locale` | **string\|null** | Source language code or null for auto-detection | + +*** + +### withFastMode + +Enable fast translation mode. + +```php +public withFastMode(): self +``` + +*** + +### withReference + +Add reference data for context. + +```php +public withReference(array $reference): self +``` + +**Parameters:** + +| Parameter | Type | Description | +|--------------|-------------------------|--------------------------| +| `$reference` | **array** | Context or glossary data | + +***