PHPackages                             eugene-erg/google-informal-icu-i18n-translate - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. eugene-erg/google-informal-icu-i18n-translate

ActiveLibrary[API Development](/categories/api)

eugene-erg/google-informal-icu-i18n-translate
=============================================

Text translation using multiple neural network APIs

1.0.2(1mo ago)151MITPHP

Since Apr 14Pushed 1mo agoCompare

[ Source](https://github.com/EugeneErg/google-informal-icu-i18n-translator)[ Packagist](https://packagist.org/packages/eugene-erg/google-informal-icu-i18n-translate)[ RSS](/packages/eugene-erg-google-informal-icu-i18n-translate/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (3)Dependencies (10)Versions (4)Used By (1)

google-informal-icu-i18n-translator
===================================

[](#google-informal-icu-i18n-translator)

A PHP library for translating [ICU message format](https://unicode-org.github.io/icu/userguide/format_parse/messages/) strings using the Google Translate unofficial API. Designed to integrate with the [`eugene-erg/icu-i18n-translator`](https://github.com/EugeneErg/icu-i18n-translator) ecosystem and any PSR-18 HTTP client.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
- [Usage](#usage)
    - [Basic Translation](#basic-translation)
    - [Translation with Language Detection](#translation-with-language-detection)
    - [Check Language Support](#check-language-support)
    - [Using the Low-Level Client Directly](#using-the-low-level-client-directly)
    - [Requesting Specific Data Types](#requesting-specific-data-types)
- [Architecture](#architecture)
- [Configuration](#configuration)
- [Exception Handling](#exception-handling)
- [Response Structure](#response-structure)
- [Comparison with Alternatives](#comparison-with-alternatives)
- [Development](#development)
- [License](#license)

---

Requirements
------------

[](#requirements)

RequirementVersionPHP`^8.2`ext-intl`*`psr/http-client`^1.0`psr/http-message`^2.0`psr/http-factory`^1.1`psr/simple-cache`^3.0`eugene-erg/icu-i18n-translator`^1.0`You also need a PSR-18 compatible HTTP client installed (e.g. Guzzle, Symfony HttpClient, or any other). The library does not ship one by default to remain transport-agnostic.

---

Installation
------------

[](#installation)

```
composer require eugene-erg/google-informal-icu-i18n-translate
```

Then install a PSR-18 HTTP client. Any of the following will work:

```
# Guzzle
composer require guzzlehttp/guzzle guzzlehttp/psr7

# Symfony HttpClient
composer require symfony/http-client nyholm/psr7

# Buzz (lightweight)
composer require kriswallsmith/buzz nyholm/psr7
```

---

Quick Start
-----------

[](#quick-start)

```
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Client;
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\PsrClient;
use EugeneErg\GoogleInformalIcuI18nTranslator\GoogleInformalTranslator;
use EugeneErg\ICUMessageFormatParser\Parser;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Psr16Cache;

// 1. Wire up your PSR-18 HTTP client (example with Guzzle)
$httpClient      = new \GuzzleHttp\Client();
$requestFactory  = new \GuzzleHttp\Psr7\HttpFactory();
$streamFactory   = new \GuzzleHttp\Psr7\HttpFactory();

// 2. Build the transport adapter
$psrClient = new PsrClient($httpClient, $requestFactory, $streamFactory);

// 3. Build the low-level Google client
$client = new Client($psrClient, 'https://translate.googleapis.com');

// 4. Build the translator (requires a PSR-16 cache)
$cache      = new Psr16Cache(new ArrayAdapter());
$translator = new GoogleInformalTranslator($client, new Parser(), $cache);

// 5. Translate
$result = $translator->translate(['Hello, world!'], 'en_EN', 'ru_RU');
// $result = ['Привет, мир!']
```

---

Core Concepts
-------------

[](#core-concepts)

### ICU Message Format

[](#icu-message-format)

[ICU messages](https://unicode-org.github.io/icu/userguide/format_parse/messages/) allow you to express pluralization, gender, and variable substitution in a locale-aware way:

```
You have {count, plural, one {# message} other {# messages}}.

```

This library translates ICU patterns while preserving the structure — variables and formatting directives are never sent through Google Translate. Only the human-readable text fragments are translated.

### Pattern = `array`

[](#pattern--arraystringvariable)

Rather than a plain string, the translator works with a **pattern** — an array of strings and `Variable` objects. This keeps ICU variables intact during translation:

```
use EugeneErg\IcuI18nTranslator\DataTransferObjects\Variable;

$pattern = ['Hello, ', new Variable(0), '! You have ', new Variable(1), ' messages.'];

$translated = $translator->translate($pattern, 'en_EN', 'ru_RU');
// ['Привет, ', Variable(0), '! У вас ', Variable(1), ' сообщений.']
```

Variable placeholders are encoded as `{{_0_}}`, `{{_1_}}` etc. when sent to Google and restored in the result.

---

Usage
-----

[](#usage)

### Basic Translation

[](#basic-translation)

```
$translated = $translator->translate(
    pattern: ['Good morning!'],
    fromLocale: 'en_EN',
    toLocale: 'de_DE',
);
// ['Guten Morgen!']
```

Locale format is `language_REGION` — the library extracts the region part as the language code sent to Google. Passing just `'en'` or `'ru'` (no underscore) is also supported and will be lowercased.

```
// Both forms are valid
$translator->translate(['Hello'], 'en', 'ru');
$translator->translate(['Hello'], 'en_EN', 'ru_RU');
```

### Translation with Language Detection

[](#translation-with-language-detection)

When the source language is unknown, use `translateWithDetect()`. Google will detect it automatically and return it alongside the translation:

```
use EugeneErg\IcuI18nTranslator\ValueObjects\Translated;

$result = $translator->translateWithDetect(
    pattern: ['Bonjour le monde'],
    toLocale: 'en_EN',
);

echo $result->locale;  // 'fr'
echo $result->pattern[0]; // 'Hello world'
```

### Check Language Support

[](#check-language-support)

Before translating you can verify that the target (and optionally source) language is supported by Google Translate. The result is cached for 24 hours via your PSR-16 cache.

```
// Is Russian a supported target?
$translator->canTranslate('ru_RU');          // true

// Can we translate from English to Russian?
$translator->canTranslate('ru_RU', 'en_EN'); // true

// Unsupported target
$translator->canTranslate('xx_XX');          // false
```

### Using the Low-Level Client Directly

[](#using-the-low-level-client-directly)

If you need more control over the Google Translate response — alternative translations, dictionary entries, romanization, etc. — use `Client` directly:

```
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Client;
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\ValueObjects\GoogleTranslateType;

$response = $client->single(
    text: 'Hello',
    targetLanguage: 'ru',
    types: [
        GoogleTranslateType::Translation,
        GoogleTranslateType::Dictionary,
        GoogleTranslateType::AlternativeTranslations,
    ],
    sourceLanguage: 'en',
);

echo $response->translates[0]->translatedText; // 'Привет'
echo $response->detectedSourceLanguage;        // 'en'
var_dump($response->dictionary);               // raw dictionary data
```

### Requesting Specific Data Types

[](#requesting-specific-data-types)

`GoogleTranslateType` is an enum controlling what data Google returns:

CaseValueDescription`Translation``t`Main translation result`AlternativeTranslations``at`Alternative phrasings`Romanization``rm`Romanized (transliterated) form`Dictionary``bd`Dictionary entries with examples`QualityCheck``qc`Quality check information`Examples``ex`Usage examples`Synonyms``ss`Synonyms`RelatedWords``rw`Related words`Morphology``md`Morphological infoYou can request multiple types at once. Types not requested will have `null` in the corresponding response fields.

### List Supported Languages

[](#list-supported-languages)

```
$response = $client->getSupportedLanguages();

foreach ($response->languages as $code => $language) {
    echo sprintf(
        "%s: %s (source: %s, target: %s)\n",
        $code,
        $language->name,
        $language->source ? 'yes' : 'no',
        $language->target ? 'yes' : 'no',
    );
}
```

---

Architecture
------------

[](#architecture)

```
GoogleInformalTranslator          — TranslatorInterface implementation
│  uses Parser (ICU parser)
│  uses CacheInterface (PSR-16)
└─ Client                         — Google Translate API wrapper
   │  uses ClientInterface
   └─ PsrClient                   — ClientInterface over PSR-18
      │  uses Psr\Http\Client\ClientInterface  (PSR-18)
      │  uses RequestFactoryInterface          (PSR-17)
      └─ uses StreamFactoryInterface           (PSR-17)

```

**`GoogleInformalTranslator`** implements `TranslatorInterface` from `eugene-erg/icu-i18n-translator`. It converts ICU pattern arrays to plain text (escaping ICU syntax via `Parser::quote()`), translates via `Client`, then parses variable placeholders back out of the response.

**`Client`** wraps the unofficial Google Translate endpoint (`translate.googleapis.com`). It maps the raw array response into typed value objects (`GoogleTranslateResponse`, `Translate`, `Confidence`, `QualityCheck`, `Model`) and maps HTTP/PSR errors into its own exception hierarchy.

**`PsrClient`** is a thin adapter that converts the library's simplified `sendRequest(method, uri, body, headers)` interface into proper PSR-7 `RequestInterface` calls, allowing any PSR-18 client to be used as transport.

---

Configuration
-------------

[](#configuration)

### Custom API URL

[](#custom-api-url)

By default the library targets `https://translate.googleapis.com`. You can override it — useful for testing, proxying, or regional endpoints:

```
$client = new Client($psrClient, 'https://your-proxy.example.com');
```

### Cache TTL

[](#cache-ttl)

Supported languages are cached for 24 hours (`P1D`). The cache key is `GoogleInformalTranslator:getSupportedLanguages`. To change the TTL, extend `GoogleInformalTranslator` and override `getSupportedLanguages()`, or wrap it with your own caching layer.

### Custom HTTP Adapter

[](#custom-http-adapter)

Implement `ClientInterface` to use any transport, add authentication, logging, or retry logic:

```
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;

final class LoggingClient implements ClientInterface
{
    public function __construct(
        private ClientInterface $inner,
        private LoggerInterface $logger,
    ) {}

    public function sendRequest(
        string $method,
        string $uri,
        string|null $body = null,
        array $headers = [],
    ): ResponseInterface {
        $this->logger->debug("[$method] $uri");
        return $this->inner->sendRequest($method, $uri, $body, $headers);
    }
}
```

---

Exception Hierarchy
-------------------

[](#exception-hierarchy)

```
\RuntimeException
└─ Exception
   ├─ ClientException          — 4xx response or generic PSR-18 error
   │  ├─ NetworkException      — 5xx response or PSR-18 NetworkExceptionInterface
   │  └─ TimeoutException      — PSR-18 RequestExceptionInterface (timeout/abort)
   └─ ResponseJsonException    — response body is not valid JSON (on 2xx)

```

All exceptions live under `EugeneErg\GoogleInformalIcuI18nTranslator\Client\Exceptions`.

```
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Exceptions\ClientException;
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Exceptions\NetworkException;
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Exceptions\TimeoutException;
use EugeneErg\GoogleInformalIcuI18nTranslator\Client\Exceptions\ResponseJsonException;

try {
    $response = $client->single('Hello', 'ru');
} catch (TimeoutException $e) {
    // request timed out or was aborted
} catch (NetworkException $e) {
    // server error (5xx) or network-level failure
} catch (ClientException $e) {
    // client error (4xx) or unexpected HTTP problem
} catch (ResponseJsonException $e) {
    // got a 2xx but body wasn't JSON
}
```

---

Response Structure
------------------

[](#response-structure)

### `GoogleTranslateResponse`

[](#googletranslateresponse)

PropertyTypeDescription`translates``Translate\[\]null``dictionary``mixed\[\]null``detectedSourceLanguage``stringnull``alternativeTranslations``mixed\[\]null``confidenceValue``floatnull``qualityCheck``QualityChecknull``confidence``Confidencenull``additional``mixed[]`Undocumented fields from the API### `Translate`

[](#translate)

PropertyTypeDescription`translatedText``stringnull``originalText``stringnull``transliteration``stringnull``models``Model\[\]null``additional``mixed[]`Undocumented fields---

Comparison with Alternatives
----------------------------

[](#comparison-with-alternatives)

FeatureThis library`stichoza/google-translate-php``google/cloud-translate`**API**Unofficial (free)Unofficial (free)Official (paid)**ICU message format**✅ Native support❌❌**Variable preservation**✅❌❌**PSR-18 transport**✅ Bring your own❌ Uses curl directly✅**PSR-16 cache**✅❌❌**Language detection**✅✅✅**Typed response objects**✅❌ plain string✅**Alternative translations**✅❌✅**Dictionary / examples**✅❌✅**Quality check data**✅❌❌**Auth required**❌❌✅ API key / OAuth**Rate limits**Google informalGoogle informalQuota-based billing**PHP version**`^8.2``^8.0``^8.0`**Static analysis**PHPStan level 9——**Test coverage**100%partial—> **Note:** The unofficial Google Translate API has no SLA and may change without notice. It is suitable for development, tooling, and low-traffic use cases. For production workloads at scale, consider the official Cloud Translation API.

---

Development
-----------

[](#development)

### Setup

[](#setup)

```
git clone https://github.com/EugeneErg/google-informal-icu-i18n-translator
cd google-informal-icu-i18n-translator
composer install
```

### Running Tests

[](#running-tests)

```
./vendor/bin/phpunit
```

With coverage (requires Xdebug or PCOV):

```
XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-filter src --coverage-text
```

### Static Analysis

[](#static-analysis)

```
./vendor/bin/phpstan analyse
```

Level 9 (maximum). Covers both `src/` and `tests/`.

### Code Style

[](#code-style)

```
# Check
./vendor/bin/php-cs-fixer fix --dry-run --diff

# Fix
./vendor/bin/php-cs-fixer fix
```

### Project Structure

[](#project-structure)

```
src/
├── GoogleInformalTranslator.php       # Main TranslatorInterface implementation
└── Client/
    ├── Client.php                     # Google Translate API wrapper
    ├── ClientInterface.php            # HTTP transport abstraction
    ├── PsrClient.php                  # PSR-18 adapter
    ├── Exceptions/
    │   ├── Exception.php
    │   ├── ClientException.php
    │   ├── NetworkException.php
    │   ├── TimeoutException.php
    │   └── ResponseJsonException.php
    └── ValueObjects/
        ├── GoogleTranslateResponse.php
        ├── GoogleTranslateType.php
        ├── Translate.php
        ├── Confidence.php
        ├── QualityCheck.php
        ├── Model.php
        ├── Language.php
        └── SupportedLanguagesResponse.php

tests/
├── GoogleInformalTranslatorTest.php
└── Client/
    ├── ClientTest.php
    ├── PsrClientTest.php
    └── Stubs/
        └── FakeRequest.php

```

---

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance90

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~28 days

Total

3

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/899442d4ad0c107f9972542ef053239fcbff4f3c718ab77c9219e6daa02d852d?d=identicon)[EugeneErg](/maintainers/EugeneErg)

---

Top Contributors

[![EugeneErg](https://avatars.githubusercontent.com/u/19587107?v=4)](https://github.com/EugeneErg "EugeneErg (11 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/eugene-erg-google-informal-icu-i18n-translate/health.svg)

```
[![Health](https://phpackages.com/badges/eugene-erg-google-informal-icu-i18n-translate/health.svg)](https://phpackages.com/packages/eugene-erg-google-informal-icu-i18n-translate)
```

###  Alternatives

[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k16](/packages/tempest-framework)[cakephp/cakephp

The CakePHP framework

8.8k19.5M1.8k](/packages/cakephp-cakephp)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

36789.4k2](/packages/telnyx-telnyx-php)[mollie/mollie-api-php

Mollie API client library for PHP. Mollie is a European Payment Service provider and offers international payment methods such as Mastercard, VISA, American Express and PayPal, and local payment methods such as iDEAL, Bancontact, SOFORT Banking, SEPA direct debit, Belfius Direct Net, KBC Payment Button and various gift cards such as Podiumcadeaukaart and fashioncheque.

60316.0M89](/packages/mollie-mollie-api-php)[n1ebieski/ksef-php-client

PHP API client that allows you to interact with the API Krajowego Systemu e-Faktur

9067.8k](/packages/n1ebieski-ksef-php-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
