Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- interface TranslationProviderInterface
- {
- /**
- * @param string $text Text to translate
- * @param string $targetLang Target language code (format depends on provider)
- * @param string|null $sourceLang Source language code, or null for auto-detect
- * @return string Translated text
- * @throws RuntimeException on request failure
- */
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string;
- }
- // ---------------------------------------------------------------------
- // Small shared HTTP helper (cURL) so providers don't duplicate this
- // ---------------------------------------------------------------------
- final class HttpClient
- {
- /**
- * @param array<string> $headers
- * @param string|array $body Raw string (JSON/form-encoded) or array for multipart
- */
- public static function post(string $url, array $headers, $body): array
- {
- $ch = curl_init($url);
- curl_setopt_array($ch, [
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POST => true,
- CURLOPT_HTTPHEADER => $headers,
- CURLOPT_POSTFIELDS => $body,
- CURLOPT_TIMEOUT => 15,
- CURLOPT_CONNECTTIMEOUT => 10,
- ]);
- $response = curl_exec($ch);
- if ($response === false) {
- $error = curl_error($ch);
- curl_close($ch);
- throw new RuntimeException("cURL error: {$error}");
- }
- $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- if ($statusCode < 200 || $statusCode >= 300) {
- throw new RuntimeException("HTTP error {$statusCode}: {$response}");
- }
- $decoded = json_decode($response, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- throw new RuntimeException('Failed to decode JSON response: ' . json_last_error_msg());
- }
- return $decoded ?? [];
- }
- }
- // ---------------------------------------------------------------------
- // Provider: DeepL (https://www.deepl.com/docs-api)
- // Target lang example: 'DE', 'ES', 'FR' (uppercase)
- // ---------------------------------------------------------------------
- final class DeepLProvider implements TranslationProviderInterface
- {
- private string $apiKey;
- private string $endpoint;
- public function __construct(string $apiKey, bool $useFreeTier = false)
- {
- $this->apiKey = $apiKey;
- $this->endpoint = $useFreeTier
- ? 'https://api-free.deepl.com/v2/translate'
- : 'https://api.deepl.com/v2/translate';
- }
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string
- {
- $params = [
- 'text' => $text,
- 'target_lang' => strtoupper($targetLang),
- ];
- if ($sourceLang !== null) {
- $params['source_lang'] = strtoupper($sourceLang);
- }
- $result = HttpClient::post(
- $this->endpoint,
- [
- 'Authorization: DeepL-Auth-Key ' . $this->apiKey,
- 'Content-Type: application/x-www-form-urlencoded',
- ],
- http_build_query($params)
- );
- return $result['translations'][0]['text'] ?? '';
- }
- }
- // ---------------------------------------------------------------------
- // Provider: Google Cloud Translation API v2
- // Target lang example: 'es', 'fr', 'de' (lowercase ISO 639-1)
- // ---------------------------------------------------------------------
- final class GoogleTranslateProvider implements TranslationProviderInterface
- {
- private string $apiKey;
- private string $endpoint = 'https://translation.googleapis.com/language/translate/v2';
- public function __construct(string $apiKey)
- {
- $this->apiKey = $apiKey;
- }
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string
- {
- $params = [
- 'key' => $this->apiKey,
- 'q' => $text,
- 'target' => $targetLang,
- 'format' => 'text',
- ];
- if ($sourceLang !== null) {
- $params['source'] = $sourceLang;
- }
- $result = HttpClient::post(
- $this->endpoint,
- ['Content-Type: application/x-www-form-urlencoded'],
- http_build_query($params)
- );
- return $result['data']['translations'][0]['translatedText'] ?? '';
- }
- }
- // ---------------------------------------------------------------------
- // Provider: Microsoft Translator (Azure Cognitive Services)
- // Target lang example: 'es', 'fr', 'de'
- // ---------------------------------------------------------------------
- final class MicrosoftTranslatorProvider implements TranslationProviderInterface
- {
- private string $apiKey;
- private string $region;
- private string $endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0';
- public function __construct(string $apiKey, string $region)
- {
- $this->apiKey = $apiKey;
- $this->region = $region;
- }
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string
- {
- $url = $this->endpoint . '&to=' . urlencode($targetLang);
- if ($sourceLang !== null) {
- $url .= '&from=' . urlencode($sourceLang);
- }
- $headers = [
- 'Ocp-Apim-Subscription-Key: ' . $this->apiKey,
- 'Ocp-Apim-Subscription-Region: ' . $this->region,
- 'Content-Type: application/json',
- ];
- $body = json_encode([['Text' => $text]]);
- $result = HttpClient::post($url, $headers, $body);
- return $result[0]['translations'][0]['text'] ?? '';
- }
- }
- // ---------------------------------------------------------------------
- // Provider: LibreTranslate (self-hosted or public instance, no vendor lock-in)
- // Target lang example: 'es', 'fr', 'de'
- // ---------------------------------------------------------------------
- final class LibreTranslateProvider implements TranslationProviderInterface
- {
- private string $endpoint;
- private ?string $apiKey;
- public function __construct(string $endpoint = 'https://libretranslate.com/translate', ?string $apiKey = null)
- {
- $this->endpoint = $endpoint;
- $this->apiKey = $apiKey;
- }
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string
- {
- $payload = [
- 'q' => $text,
- 'source' => $sourceLang ?? 'auto',
- 'target' => $targetLang,
- 'format' => 'text',
- ];
- if ($this->apiKey !== null) {
- $payload['api_key'] = $this->apiKey;
- }
- $result = HttpClient::post(
- $this->endpoint,
- ['Content-Type: application/json'],
- json_encode($payload)
- );
- return $result['translatedText'] ?? '';
- }
- }
- // ---------------------------------------------------------------------
- // Facade: what your application code actually talks to
- // ---------------------------------------------------------------------
- final class Translator
- {
- private TranslationProviderInterface $provider;
- public function __construct(TranslationProviderInterface $provider)
- {
- $this->provider = $provider;
- }
- public function translate(string $text, string $targetLang, ?string $sourceLang = null): string
- {
- return $this->provider->translate($text, $targetLang, $sourceLang);
- }
- /**
- * Convenience for translating several strings in one call.
- * (Loops client-side; providers with native batch endpoints could
- * override this for efficiency.)
- *
- * @param string[] $texts
- * @return string[]
- */
- public function translateBatch(array $texts, string $targetLang, ?string $sourceLang = null): array
- {
- $results = [];
- foreach ($texts as $key => $text) {
- $results[$key] = $this->translate($text, $targetLang, $sourceLang);
- }
- return $results;
- }
- }
- // ---------------------------------------------------------------------
- // Usage examples (uncomment the one you need)
- // ---------------------------------------------------------------------
- // DeepL
- // $translator = new Translator(new DeepLProvider('YOUR_DEEPL_API_KEY'));
- // echo $translator->translate('Hello, world!', 'DE');
- // Google Cloud Translation
- // $translator = new Translator(new GoogleTranslateProvider('YOUR_GOOGLE_API_KEY'));
- // echo $translator->translate('Hello, world!', 'es');
- // Microsoft Translator
- // $translator = new Translator(new MicrosoftTranslatorProvider('YOUR_MS_KEY', 'YOUR_REGION'));
- // echo $translator->translate('Hello, world!', 'it');
- // LibreTranslate (free/self-hosted, no API key required by default)
- // $translator = new Translator(new LibreTranslateProvider());
- // echo $translator->translate('Hello, world!', 'fr');
- // Batch example
- // $translator = new Translator(new DeepLProvider('YOUR_DEEPL_API_KEY'));
- // $translated = $translator->translateBatch(
- // ['Hello', 'Goodbye', 'Thank you'],
- // 'FR'
- // );
- // print_r($translated);
Advertisement
Add Comment
Please, Sign In to add comment