Skip to content

Instantly share code, notes, and snippets.

@jverdeyen
Last active August 29, 2015 14:15
Show Gist options
  • Save jverdeyen/1e160c43469d3090c35b to your computer and use it in GitHub Desktop.
Save jverdeyen/1e160c43469d3090c35b to your computer and use it in GitHub Desktop.
How do you write this PHP function?

A function which has an object and a locale as parameter.

  • The object holds an array of translations ->getTranslations() and ->getTranslation($locale) are available
  • Locale is a dead simple string of 2 chars
  • The function has access to an array of locales ordered by priority
  • The locale parameter should be priority #1, otherwise the array of priorities is used to get the correct locale.

class Testing {
        private $localePriorityArray = ['nl', 'en', 'fr', 'de'];
        
        public function functionName($object, $locale = 'en')
        {
                // $object->getTranslation($locale); (null if not available)
                // return the translation
        }
}

Give it a go on: http://3v4l.org

@pix-art
Copy link

pix-art commented Feb 17, 2015

I'd use recursion

    public function getObjectTranslationByPriority($object, $locale = 'nl')
    {
        $translation = $object->getTranslation($locale);

        if (is_null($translation)) {
            $prioList = $this->localePriorityArray;
            $currentKey = array_search($locale, $prioList);
            $nextKey = $currentKey+1;

            if (!array_key_exists($nextKey, $prioList)) {
                throw new \Exception('No valid translation found');
            }

            $this->getObjectTranslationByPriority($object, $prioList[$nextKey]);
        }

        return $translation;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment