0

i'm looking into an issue and I would like to solve it in a general way. To get translations for an API response i use the following code:

$array['name'] = getTranslation($key);

This gets an translation based on the user settings, and can result the following into returning the key with the translation or just the key. This makes the array as follows:

//user only can get the key
$array['name']['key'] = 'key';

or

//user can get both key and translation
$array['name']['key'] = 'key';
$array['name']['translation'] = 'translation';

This solution worked fine, but unfortunately it has to change. The translation key must always be into the key, and the translation must be placed in the _key. But only if the user settings enabled them to get translations. this results into the following result:

$array['name'] = 'key';
$array['_name'] = 'translation';

or just:

 $array['name'] = 'key';

Unfortunately the translations are widely used an i do not want to make an check in every method if the user can have translations.

So for now i am wondering, if there is a way to solve this globally. Ideally would be to create a method to solve it this way:

$arraykey = 'name';
$array[$arraykey] = getTranslations('translationkey', $arraykey);

and it would end up in the array as:

$array['name'] = 'translationkey';
$array['_name'] = 'translated value';
1
  • It's hard to understand the purpose of all this stuff and therefore hard to answer. You seem to be asking how to simplify checking what kind of data a user has access to. If you can focus the question more clearly on that issue then you will probably get some answers. Commented Apr 14, 2016 at 10:17

1 Answer 1

1

Starting from your suggestion to create a new function, you can try something like:

function getTranslations($translationKey, $arrayKey)
{
     $translation = getTranslation($translationKey);

     $result = array($arrayKey => $translation['key']);
     if (/*user settings enabled translations*/) {
         $result['_' . $arrayKey] = $translation['translation'];
     }

     return $result;
}

// usage
$translation = getTranslations('namekey', 'name');

// if you have more translations in the final array then you can use array_merge
$translation = getTranslations('namekey', 'name');
$translation = array_merge($translation, getTranslations('phonekey', 'phone'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.