private function instanceTranslate($data)
{
// Whether or not is the data an array
$isArray = is_array($data);
// Rethrow exceptions
try {
$responseArray = $this->getResponse($data);
} catch (Exception $e) {
throw $e;
}
// if response in text and the content has zero the empty returns true, lets check
// if response is string and not empty and create array for further logic
if (is_string($responseArray) && $responseArray != '') {
$responseArray = [$responseArray];
}
// Check if translation exists
if (!isset($responseArray[0]) || empty($responseArray[0])) {
return false;
}
// Detect languages
$detectedLanguages = [];
// the response contains only single translation, dont create loop that will end with
// invalide foreach and warning
if ($isArray || !is_string($responseArray)) {
$responseArrayForLanguages = $isArray ? $responseArray[0] : [$responseArray];
foreach ($responseArrayForLanguages as $itemArray) {
foreach ($itemArray as $item) {
if (is_string($item)) {
$detectedLanguages[] = $item;
}
}
}
}
// Another case of detected language
if (isset($responseArray[count($responseArray) - 2][0][0])) {
$detectedLanguages[] = $responseArray[count($responseArray) - 2][0][0];
}
// Set initial detected language to null
$this::$lastDetectedSource = false;
// Iterate and set last detected language
foreach ($detectedLanguages as $lang) {
if ($this->isValidLocale($lang)) {
$this::$lastDetectedSource = $lang;
break;
}
}
// Reduce array to generate translated sentenece
if ($isArray) {
$carry = [];
foreach ($responseArray[0] as $item) {
$carry[] = $item[0][0][0];
}
return $carry;
} elseif (is_string($responseArray)) {
return $responseArray;
} else {
if (is_array($responseArray[0])) {
return array_reduce($responseArray[0], function ($carry, $item) {
$carry .= $item[0];
return $carry;
});
} else {
return $responseArray[0];
}
}
}