<?php
/**
 * Extended Zend_Translate_Adapter with additional functionality
 *
 */
abstract class Fiktiv_Translate_Adapter extends Zend_Translate_Adapter
{
    /**
     * Performs the translation and call the transform
     * function to handle transformations.
     *
     * @return string
     */
    public function translate($messageId, $locale = null)
    {
        if ($messageId == null)
            return;

        if (stristr($messageId,':')) {

            $parts = explode(':', $messageId);
            $flag = $parts[0];
            $key = $parts[1];
            return $this->transform($flag, parent::translate($key, $locale));
        }

        return parent::translate($messageId, $locale);
    }

    /**
     * Transform the translated text.
     * This function defines the transfomation flags.
     *
     * @param string $flag
     * @param string $text
     * @return string $text
     */
    protected function transform($flag, $text)
    {
        $encoding = mb_detect_encoding($text);

        switch ($flag) {
            case 'u':
                return mb_strtoupper(mb_substr($text, 0, 1, $encoding), $encoding) . mb_substr($text, 1, strlen($text), $encoding);
                break;
            case 'uw':
                $split = mb_split(' ', $text);
                foreach ($split as &$word) {
                    $word = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding) . mb_substr($word, 1, strlen($word), $encoding);
                }
                return join(' ', $split);
                break;
            case 'ua':
                return mb_strtoupper($text, $encoding);
                break;
            case 'l':
                return mb_strtolower(mb_substr($text, 0, 1, $encoding), $encoding) . mb_substr($text, 1, strlen($text), $encoding);
                break;
            case 'la':
                return mb_strtolower($text, $encoding);
                break;
        }
    }

}