]> _ Git - cubist_azuretranslation.git/commitdiff
wip #6945 @0.5
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Wed, 5 Jun 2024 12:39:33 +0000 (14:39 +0200)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Wed, 5 Jun 2024 12:39:33 +0000 (14:39 +0200)
src/Api.php

index e7123ce29e3960dafcd10cacd1e5df7e213cc977..e73857a218a4d7f2f3cb510f6956a868aa112012 100644 (file)
@@ -1,5 +1,6 @@
 <?php
 
+namespace Cubist\Azure\Translate;
 
 use GuzzleHttp\Client;
 use GuzzleHttp\Psr7\Request;
@@ -23,6 +24,8 @@ class Api
      */
     protected $token = null;
 
+    protected static $_cache = null;
+
     /**
      * @var int
      */
@@ -42,6 +45,21 @@ class Api
     }
 
     public function translate($text, $toLanguage, $fromLanguage)
+    {
+        if (null === static::$_cache) {
+            return $this->_translate($text, $toLanguage, $fromLanguage);
+        }
+        $key = $fromLanguage . '-' . $toLanguage . '-' . hash('sha256', $text);
+        $cacheFile = static::$_cache . '/' . $key;
+        if (file_exists($cacheFile)) {
+            return file_get_contents($cacheFile);
+        }
+        $res = $this->_translate($text, $toLanguage, $fromLanguage);
+        file_put_contents($cacheFile, $res);
+        return $res;
+    }
+
+    protected function _translate($text, $toLanguage, $fromLanguage)
     {
         $res = $this->_call('/translate?api-version=3.0&from=' . $fromLanguage . '&to=' . $toLanguage, 'post', [
             'Content-type' => 'application/json'
@@ -70,4 +88,9 @@ class Api
 
         return $this->client->send(new Request($method, $baseURL . ltrim($url, '/'), $headers, $body), $options);
     }
+
+    public static function setCache($cache)
+    {
+        self::$_cache = $cache;
+    }
 }
\ No newline at end of file