PHPackages                             marketforce-info/azure-translator - 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. [Localization &amp; i18n](/categories/localization)
4. /
5. marketforce-info/azure-translator

ActiveLibrary[Localization &amp; i18n](/categories/localization)

marketforce-info/azure-translator
=================================

Azure Translator taking ICU message format into account

1.0.0(2y ago)01MITPHPPHP ^8.1|^8.2

Since Oct 15Pushed 2y agoCompare

[ Source](https://github.com/marketforce-info/azure-translator)[ Packagist](https://packagist.org/packages/marketforce-info/azure-translator)[ Docs](https://github.com/marketforce-info/azure-translator)[ RSS](/packages/marketforce-info-azure-translator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (0)

MarketforceInfo/AzureTranslator
===============================

[](#marketforceinfoazuretranslator)

[![Code Checks](https://camo.githubusercontent.com/abe0caa17c012f67ccf4bbb1b73032285e15bd8a5aafaffbb695107e3b7f8869/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d61726b6574666f7263652d696e666f2f617a7572652d7472616e736c61746f722f636f64652d636865636b732e796d6c3f6272616e63683d6d61696e266c6f676f3d676974687562)](https://github.com/marketforce-info/azure-translator/actions/workflows/code-checks.yml)[![Latest Stable Version](https://camo.githubusercontent.com/c3958f91dd34e2f70dbe886c5ee6982e18b81682e41906fb3d8ab3341f67bec7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f6d61726b6574666f7263652d696e666f2f617a7572652d7472616e736c61746f723f6c6f676f3d7061636b6167697374)](https://github.com/marketforce-info/azure-translator/releases)[![Total Downloads](https://camo.githubusercontent.com/ae9a7203e3ebed8c941d3e6b1cb0ebfc8f86339efbc85696c2a9c69314056ea1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d61726b6574666f7263652d696e666f2f617a7572652d7472616e736c61746f723f6c6f676f3d7061636b6167697374)](https://packagist.org/packages/marketforce-info/azure-translator)[![Licence](https://camo.githubusercontent.com/1b4655f6bc8106e1321bbd9119fc7e2572df35be6717bb221e733c043c7b73fc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d61726b6574666f7263652d696e666f2f617a7572652d7472616e736c61746f722e737667)](https://camo.githubusercontent.com/1b4655f6bc8106e1321bbd9119fc7e2572df35be6717bb221e733c043c7b73fc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d61726b6574666f7263652d696e666f2f617a7572652d7472616e736c61746f722e737667)

Sends batches of messages to be translated to the Azure translate service. Has the option of handling variables as a formatted message.

---

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

[](#installation)

```
$ composer require marketforce-info/azure-translator
```

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

[](#requirements)

- Access to Azure authentication details. Supports subscription key and authorization token mechanisms.
- Depends on a concrete implementation of psr/http-client

Usage
-----

[](#usage)

```
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory as GuzzleFactory;
use MarketforceInfo\AzureTranslator\Translator;

$factory = new GuzzleFactory();
$client = new Translator\Client(
    new GuzzleClient(),
    new Translator\RequestFactory($factory, $factory, [Translator\Language::french])
);

$translator = new Translator($client);
$translator->onTranslate(static function (Translator\Translation $translation) {
        // do something with the message
    })
    ->begin(static function (Translator\Delegate $translator) use ($messages) {
        foreach ($messages as $message) {
            $translator->translate($message);
        }
    });
```

More in depth example of using the `Builder` class.

```
use \MarketforceInfo\AzureTranslator\Builder;
use \MarketforceInfo\AzureTranslator\MessageFormatter\BasicFormatter;
use \MarketforceInfo\AzureTranslator\Translator;

$factory = new GuzzleFactory();
$translator = (new Builder())
    ->withBaseUrl(Translator\RequestFactory::BASE_URL_US)
    ->withHttp(new GuzzleClient(), $factory, $factory)
    ->withLanguages([Translator\Language::arabic], Translator\Language::french)
    ->withBearerToken('')
    ->withMessageFormatter(new BasicFormatter('[', ']'))
    ->withTraceIdCallback(fn () => 'xxxx-XXXX-xxxx-XXXX-xxxx')
    ->when(
        $_ENV['delete_profanity'] === true,
        fn (Builder $builder) => $builder->withProfanityDeleted(),
        fn (Builder $builder) => $builder->withProfanityMarked(static fn (string $word) => '*censored*')
    )
    ->create();
```

### Translated Message

[](#translated-message)

The `onTranslate` callback method receives a DTO translation of an individual translated message for a language. It contains four properties:

`$message` is a string of the translated message.

`$language` is a `Language` enum of the language the message has been translated into.

`$traceId` is a trace ID used to track requests (see below for more information).

`$state` is user specified data specific to the original untranslated message.

The state is something that can be optionally set at the point of request (`translate`).

```
foreach ($messages as $messageId => $message) {
    $translator->translate($message, ['id' => $messageId]);
}
```

Then in the `onTranslate` callback.

```
static function (Translation $translation) use ($db) {
    $db->replace(
        table: 'translations',
        where: [
            'id' => $translation->state['id'],
            'language' => $translation->language->value
        ],
        data: ['message' => $translation->message]
    );
};
```

### Translate Request

[](#translate-request)

Batching of the requested messages is handled automatically. The ability to pass messages to be translated is done via the `Delegate` class. The `begin` method can not be called until the `onTranslate` behaviour has been defined.

```
$translator->begin(static function (Delegate $translator) use ($untranslatedMessages) {
    foreach ($untranslatedMessages as $message) {
        $translator->translate($message);
    }
});
```

Features
--------

[](#features)

### HTTP Client

[](#http-client)

This library relies on three PSR interface implementations to be provided. `ClientInterface` for the HTTP client, `RequestFactoryInterface` to create a request and `StreamFactoryInterface` to create the request body. For example, in the case of the Guzzle implementation, the request and stream factory are the same implementation.

```
$builder->withHttp($client, $requestFactory, $streamFactory);
```

#### Providers

[](#providers)

- [HTTP Client](https://packagist.org/providers/psr/http-client-implementation)
- [HTTP Message](https://packagist.org/providers/psr/http-message-implementation)
- [HTTP Factory](https://packagist.org/providers/psr/http-factory-implementation)

### Authentication

[](#authentication)

There are two methods of specifying an authentication token.

```
$builder->withSubscriptionKey('');
// or
$builder->withBearerToken('');
```

Anything more complicated should be handled through plugins/middleware in the HTTP Client.

### Message Format

[](#message-format)

By default, there is no message formatting. The following outlines alternatives to allow for different translation behaviours.

#### Basic

[](#basic)

Allows for basic syntax substitution in messages. For example

```
Welcome {name} to the monthly newsletter from {company}

```

The formatter will substitute the variables, so they won't be translated and then replace them in the final translated message.

```
use \MarketforceInfo\AzureTranslator\MessageFormatter\BasicFormatter;
$builder->withMessageFormatter(new BasicFormatter());
```

Basic formatter defaults to `{}` style syntax but this can be changed in the constructor.

#### ICU Message Format

[](#icu-message-format)

Requires an additional component which parses the ICU message format so that a representation can be sent to the translation service.

#### Installation

[](#installation-1)

```
$ composer require marketforce-info/message-format-parser
```

##### Usage

[](#usage-1)

```
use \MarketforceInfo\AzureTranslator\MessageFormatter\IcuFormatter;
$builder->withMessageFormatter(new IcuFormatter());
```

##### Caveat

[](#caveat)

The process of creating a representation to send to the translation service produces a verbose output which could have a detrimental effect on the character count and subsequently the billing by the Azure service. Additionally, the ICU parsing attempts to achieve the best translation outcome by composing variations of the messages when the format of a ICU message uses `select`, `selectordinal` or `plural`.

#### Custom Message Format

[](#custom-message-format)

It's possible to create a custom message format class. The `withMessageFormatter` method accepts any implementation of the `MessageFormatter` interface.

### Tracing Requests

[](#tracing-requests)

Each individual request to the Azure service includes a Client Trace ID. By default, this is handled automatically. This can be overridden with the following method.

#### User defined function

[](#user-defined-function)

```
$builder->withTraceIdCallback(fn () => 'xxxx-XXXX-xxxx-XXXX-xxxx');
// or
$builder->withTraceIdCallback([$this, 'traceFunction']);
// or
$builder->withTraceIdCallback(fn (\Closure $generatorFn) => $generatorFn());
```

#### Generator function

[](#generator-function)

As shown, the call back is passed a parameter which allows the use of the internal generator function. This is useful in scenarios where a trace ID is recorded for every request made.

### Handling Profanity

[](#handling-profanity)

Azure has three options for handling profanity. None, deleted or marked with asterisks or tags. The component allows this to be specified. By default, no profanity handling will be enabled. It allows for a callback to customise the way profane phrases are displayed.

#### Methods available

[](#methods-available)

```
$builder->withoutProfanityHandling(); // default
$builder->withProfanityDeleted();
$builder->withProfanityMarked(); // words replaced with *
$builder->withProfanityMarked(static function (string $phrase) {
    return '' . str_pad('', mb_strlen($phrase), 'x') . '';
});
```

### Getting Metric Data

[](#getting-metric-data)

On each request to the translate service, information about the number of characters processed is returned in the process. This can be retrieved on completion.

```
$translator->getMeteredUsage();
```

This returns an array of each request made and the data returned.

```
{
    "1234-1234-1234-1234": [
        "182"
    ]
}
```

Contributions
-------------

[](#contributions)

Contributions gratefully accepted in the form issues or PRs.

Security
--------

[](#security)

If you discover any security related issues, please email [appsupport\_uk@marketforce.com](mailto:appsupport_uk@marketforce.com) instead of using the issue tracker.

License
-------

[](#license)

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

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

941d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e246e62fd17e68a8bc383497325d43baf33c9396bc6513c3443ec38897263e17?d=identicon)[lrichardsmf](/maintainers/lrichardsmf)

---

Top Contributors

[![lrichardsmf](https://avatars.githubusercontent.com/u/115080961?v=4)](https://github.com/lrichardsmf "lrichardsmf (24 commits)")

---

Tags

icuazuretranslatormessageformat

###  Code Quality

TestsPHPUnit

Code StyleECS

### Embed Badge

![Health badge](/badges/marketforce-info-azure-translator/health.svg)

```
[![Health](https://phpackages.com/badges/marketforce-info-azure-translator/health.svg)](https://phpackages.com/packages/marketforce-info-azure-translator)
```

###  Alternatives

[symfony/intl

Provides access to the localization data of the ICU library

2.6k199.8M1.1k](/packages/symfony-intl)[stichoza/google-translate-php

Free Google Translate API PHP Package

2.0k7.6M124](/packages/stichoza-google-translate-php)[barryvdh/laravel-translation-manager

Manage Laravel Translations

1.7k3.6M17](/packages/barryvdh-laravel-translation-manager)[opensearch-project/opensearch-php

PHP Client for OpenSearch

15024.3M65](/packages/opensearch-project-opensearch-php)[deeplcom/deepl-php

Official DeepL API Client Library

2616.2M66](/packages/deeplcom-deepl-php)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)

PHPackages © 2026

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