Skip to content

Instantly share code, notes, and snippets.

@arth2o
Created January 1, 2014 19:53
Show Gist options
  • Save arth2o/8210926 to your computer and use it in GitHub Desktop.
Save arth2o/8210926 to your computer and use it in GitHub Desktop.
Yandex Translate static class
<?php
/*
* Translate URL: translate.yandex.com
* YANDEX translate documentation: http://api.yandex.com/translate/doc/dg/concepts/About.xml
*/
interface ITranslate {
public static function getMsg($return_status_code = FALSE);
public static function isAllowedTranslateLang($lang_code = false);
public static function setting($api_key, $lang = "", $text = "", $format = "plain");
public static function makeRequestUrl();
public static function sendResponse();
public static function parseResponse($data);
public static function getTranslatedText();
public static function setApiKey($api_key);
public static function getApiKey();
public static function getRequestUrl();
public static function setRequestUrl($string);
public static function getConfig();
public static function setConfig($name, $value);
public static function getErrmsg();
public static function setErrmsg($errText);
public static function setReturnType($type);
public static function getReturnType();
}
abstract class TranslateBase {
public static $_errmsg = array();
//GENERATE BY DYNAMIC
private static $_requestUrl = "";
//API KEY
public static $_apiKey = "";
//RETURN TYPE
public static $_returnType = 'json'; //json or xml
//ALLOWED LANG
public static $_allowedLang = array(
"az-ru", "be-bg", "be-cs", "be-de", "be-en", "be-es", "be-fr",
"be-it", "be-pl", "be-ro", "be-ru", "be-sr", "be-tr", "bg-be",
"bg-ru", "bg-uk", "ca-en", "ca-ru", "cs-be", "cs-en", "cs-ru",
"cs-uk", "da-en", "da-ru", "de-be", "de-en", "de-es", "de-fr",
"de-it", "de-ru", "de-tr", "de-uk", "el-en", "el-ru", "en-be",
"en-ca", "en-cs", "en-da", "en-de", "en-el", "en-es", "en-et",
"en-fi", "en-fr", "en-hu", "en-it", "en-lt", "en-lv", "en-mk",
"en-nl", "en-no", "en-pt", "en-ru", "en-sk", "en-sl", "en-sq",
"en-sv", "en-tr", "en-uk", "es-be", "es-de", "es-en", "es-ru",
"es-uk", "et-en", "et-ru", "fi-en", "fi-ru", "fr-be", "fr-de",
"fr-en", "fr-ru", "fr-uk", "hr-ru", "hu-en", "hu-ru", "hy-ru",
"it-be", "it-de", "it-en", "it-ru", "it-uk", "lt-en", "lt-ru",
"lv-en", "lv-ru", "mk-en", "mk-ru", "nl-en", "nl-ru", "no-en",
"no-ru", "pl-be", "pl-ru", "pl-uk", "pt-en", "pt-ru", "ro-be",
"ro-ru", "ro-uk", "ru-az", "ru-be", "ru-bg", "ru-ca", "ru-cs",
"ru-da", "ru-de", "ru-el", "ru-en", "ru-es", "ru-et", "ru-fi",
"ru-fr", "ru-hr", "ru-hu", "ru-hy", "ru-it", "ru-lt", "ru-lv",
"ru-mk", "ru-nl", "ru-no", "ru-pl", "ru-pt", "ru-ro", "ru-sk",
"ru-sl", "ru-sq", "ru-sr", "ru-sv", "ru-tr", "ru-uk", "sk-en",
"sk-ru", "sl-en", "sl-ru", "sq-en", "sq-ru", "sr-be", "sr-ru",
"sr-uk", "sv-en", "sv-ru", "tr-be", "tr-de", "tr-en", "tr-ru",
"tr-uk", "uk-bg", "uk-cs", "uk-de", "uk-en", "uk-es", "uk-fr",
"uk-it", "uk-pl", "uk-ro", "uk-ru", "uk-sr", "uk-tr",
);
//LANG NAMES
public static $_allowedLangNames = array(
"ar" => "Arabic",
"az" => "Azerbaijani",
"be" => "Belarusian",
"bg" => "Bulgarian",
"ca" => "Catalan",
"cs" => "Czech",
"da" => "Danish",
"de" => "German",
"el" => "Greek",
"en" => "English",
"es" => "Spanish",
"et" => "Estonian",
"fi" => "Finnish",
"fr" => "French",
"he" => "Hebrew",
"hr" => "Croatian",
"hu" => "Hungarian",
"hy" => "Armenian",
"it" => "Italian",
"ka" => "Georgian",
"lt" => "Lithuanian",
"lv" => "Latvian",
"mk" => "Macedonian",
"nl" => "Dutch",
"no" => "Norwegian",
"pl" => "Polish",
"pt" => "Portuguese",
"ro" => "Romanian",
"ru" => "Russian",
"sk" => "Slovak",
"sl" => "Slovenian",
"sq" => "Albanian",
"sr" => "Serbian",
"sv" => "Swedish",
"tr" => "Turkish",
"uk" => "Ukrainian",
);
/**
* getMsg($code=200)
* @param string $return_status_code number [200,401,402,403,404,413,422,501]
* @return array( code => "ERR_OK",
* msg => "Operation completed successfully.",
* )
* OR FALSE
*/
public static function getMsg($return_status_code = FALSE) {
if (!$return_status_code) {
self::setErrmsg('Return status code is required!');
throw new Exception('Return status code is required!');
return false;
}
$return_status_code = intval($return_status_code);
if (array_key_exists($return_status_code, self::$_responseMessages)) {
$return_code = array_keys(self::$_responseMessages[$return_status_code]);
$msg = array_values(self::$_responseMessages[$return_status_code]);
return ($return = array(
"code" => $return_code[0],
"msg" => $msg[0],
));
}
return false;
}
/**
* getErrmsg()
* @return array
* GET ALL ERRMSG
*/
public static function getErrmsg() {
return self::$_errmsg;
}
/**
* setErrmsg($errText)
* @param type $errText
* SET AN ERRMSG
*/
public static function setErrmsg($errText) {
self::$_errmsg[] = $errText;
}
/**
* setApiKey($api_key)
* SET API KEY
*/
public static function setApiKey($api_key) {
self::$_apiKey = $api_key;
}
/**
* getApiKey()
* GET API KEY
*/
public static function getApiKey() {
return self::$_apiKey;
}
/**
* getRequestUrl()
* @return type
*/
public static function getRequestUrl() {
return self::$_requestUrl;
}
/**
* setRequestUrl($string)
* @param strinig $string
*/
public static function setRequestUrl($string) {
self::$_requestUrl = $string;
}
/**
* function setReturnType($type)
* @param type $type
* SET RETURN TYPE
*/
public static function setReturnType($type) {
switch ($type) {
case "json":
case "xml":
break;
default:
throw new Exception("Invalid return type!");
break;
}
self::$_returnType = $type;
}
//GET RETURN TYPE
public static function getReturnType() {
return self::$_returnType;
}
}
class yandexTranslate extends TranslateBase implements ITranslate {
//REQUEST VARIABLES / CONFIG
private static $_config = array(
"key" => "", //API key
"format" => "plain", //plain or html
"text" => "", //array
"lang" => "", //lang code example: en-hu
);
//CALLBACK TYPE AND URL
private static $_callbackUrls = array(
"xml" => "https://translate.yandex.net/api/v1.5/tr/translate",
"json" => "https://translate.yandex.net/api/v1.5/tr.json/translate",
);
//ERROR MSGS
private static $_responseMessages = array(
"200" => array("ERR_OK" => "Operation completed successfully."),
"401" => array("ERR_KEY_INVALID" => "Invalid API key."),
"402" => array("ERR_KEY_BLOCKED" => "This API key has been blocked."),
"403" => array("ERR_DAILY_REQ_LIMIT_EXCEEDED" => "You have reached the daily limit for requests (including calls of the detect method)."),
"404" => array("ERR_DAILY_CHAR_LIMIT_EXCEEDED" => "You have reached the daily limit for the volume of translated text (including calls of the detect method)."),
"413" => array("ERR_TEXT_TOO_LONG" => "The text size exceeds the maximum."),
"422" => array("ERR_UNPROCESSABLE_TEXT" => "The text could not be translated."),
"501" => array("ERR_LANG_NOT_SUPPORTED" => "The specified translation direction is not supported."),
);
/**
* isAllowedTranslateLang($lang_code = false)
* @param string $lang_code for example: hu-ru or en-hu
* @return true if valid the $lang_code
*/
public static function isAllowedTranslateLang($lang_code = false) {
if (!$lang_code) {
throw new Exception("Lang Code is empty!");
}
//CHECK FORMAT en-ru
if (!preg_match("/(.*)-(.*)/i", $lang_code)) {
parent::setErrmsg("Invalid languange code! Required format: en-ru!");
throw new Exception("Invalid languange code! Required format: en-ru!");
}
//CHECK ARRAY EXISTS
if (!in_array($lang_code, parent::$_allowedLang)) {
parent::setErrmsg("There is no such language!");
throw new Exception("There is no such language!");
}
return true;
}
/**
* setting($api_key = "", $lang = "", $text = "", $format = "plain", $options = "")
* @param string $api_key
* @param string $lang
* @param string or array $text
* @param string $format plain or html
* @return boolean if false, then view errmsg
*/
public static function setting($api_key, $lang = "", $text = "", $format = "plain") {
$isValidSetting = true;
//SET API KEY
parent::setApiKey($api_key);
//SET AND CHECK API KEY FOR CONFIG
self::$_config["key"] = parent::getApiKey();
if (empty(self::$_config["key"]) || (strlen(self::$_config["key"]) < 70)) {
$isValidSetting = false;
parent::setErrmsg("Valid API key is required!");
throw new Exception("Valid API key is required!");
}
//SET FORMAT
$settingFormat = "plain";
switch ($format) {
case "html":
case "plain":
$settingFormat = $format;
break;
}
self::$_config["format"] = $settingFormat;
//SET LANG OR IF EMPTY SET AUTOMATICALLY DETECT
self::$_config["lang"] = $lang;
//IF EMPTY LANG
if (empty(self::$_config["lang"])) {
parent::setErrmsg("Lang is required!");
throw new Exception("Lang is required!");
}
//IS VALID LANG?
if (!empty(self::$_config["lang"]) && !self::isAllowedTranslateLang($lang)) {
$isValidSetting = false;
parent::setErrmsg("Lang paramter is invalid!");
throw new Exception("Lang paramter is invalid!");
}
//SET TEXT
self::$_config["text"] = $text;
if (empty(self::$_config["text"])) {
$isValidSetting = false;
parent::setErrmsg("Text is required!");
throw new Exception("Text is required!");
} else {
//REMOVE HTML
if (is_array(self::$_config["text"]) && $settingFormat == "plain") {
self::$_config["text"] = array_map("strip_tags", self::$_config["text"]);
}
}
//INVALID SETTINGS
if (!$isValidSetting) {
return false;
}
return true;
}
/**
* getConfig()
* @return array
*/
public static function getConfig() {
return self::$_config;
}
/**
* setConfig($name, $value)
* @param type $name
* @param type $value
* @return type
*/
public static function setConfig($name, $value) {
return self::$_config[$name] = $value;
}
/**
* makeRequestUrl()
*/
public static function makeRequestUrl() {
$configData = self::getConfig();
//IF TEXT VARIABLE AN ARRAY
$configTexts = "";
if (is_array($configData["text"])) {
$config_text = $configData["text"];
unset($configData["text"]);
foreach ($config_text as $textItem) {
$configTexts.="&text=" . urlencode($textItem);
}
}
$paramString = http_build_query($configData);
//GET BASE URL
$paramUrl = self::$_callbackUrls[self::$_returnType];
$request_url = sprintf("%s?%s", $paramUrl, $paramString . $configTexts);
self::setRequestUrl($request_url);
}
/**
* sendResponse()
* @return type
* return array assoc or xml
*/
public static function sendResponse() {
$requestUrl = self::getRequestUrl();
$data = file_get_contents($requestUrl);
if (self::getReturnType() == "json") {
return json_decode($data, TRUE);
}
return $data;
}
/**
* parseResponse($data)
* @param type $data
* @return string or array
* IF return type is JSON
*/
public static function parseResponse($data) {
if (self::$_returnType != "json") {
return $data;
}
switch ($data["code"]) {
case "200":
return $data["text"];
break;
default:
$err = parent::getMsg($data["code"]);
self::setErrmsg("{$err["code"]} / {$err["msg"]}");
throw new Exception($err["msg"]);
break;
}
}
/**
* getTranslatedText()
* @RETURN TEXT OR ARRAY
*/
public static function getTranslatedText() {
$data = self::sendResponse();
return self::parseResponse($data);
}
}
//BASE CONFIG
$api_key = "YOUR API KEY HERE!";
$text[] = "Hello világ";
$text[] = "Ez egy új világ";
$lang = "hu-en";
try {
//SETTING
yandexTranslate::setting($api_key, $lang, $text);
//SET RETURN TYPE
$return_type = "json";
yandexTranslate::setReturnType($return_type);
//MAKE REQUEST URL
yandexTranslate::makeRequestUrl();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
exit;
}
//GET REQUEST URL
//echo yandexTranslate::getRequestUrl();
//GET TRANSLATED TEXT
$data = yandexTranslate::getTranslatedText();
print_r($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment