summaryrefslogtreecommitdiff
path: root/app/frontend/mail/MailTemplateTranslator.php
blob: 0e9d7c9e2941921ceef634cc33bb505ff3c97a8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php

Prado::using('Lib.phptal.PHPTAL.TranslationService');

class MailTemplateTranslator implements PHPTAL_TranslationService {

    private $_module;
    private $_catalogue = 'messages';
    private $_charset;
    private $_formatter;
    private $_source;

    public function __construct($catalogue=NULL) {
        $this->_module = Prado::getApplication()->getGlobalization(FALSE);
        $this->_catalogue = $catalogue;
    }

    private $_language = NULL;

    function setLanguage(/* ... */) {
        $this->_source = NULL;
        $langs = array_filter(func_get_args());
        if ($langs) {
            $availableLangs = $this->_module->AllowedCultures;
            foreach ($langs as $lang) {
                if (in_array($lang, $availableLangs)) {
                    $this->_language = $lang;
                    return;
                }
            }
            throw new TInvalidDataValueException(
                Prado::localize(
                    'Languages [{lang}] not available',
                    ['lang' => implode(',', $langs)]
                )
            );
        } else {
            $this->_language = NULL;
        }
    }

    function setEncoding($encoding) {
        $this->_charset = $encoding;
    }

    function useDomain($domain) {
        $this->_catalogue = $domain;
    }

    private $_variables = [];

    function setVar($key, $value) {
        $this->_variables[$key] = $value;
    }

    function translate($key, $htmlescape=TRUE) {
        $key = preg_replace('/\$(\{.*\})/', '\1', $key);
        if ($this->_language) {
            if (!$this->_source) {
                $appConfig = Prado::getApplication()->getGlobalization()->getTranslationConfiguration();
                $this->_source = MessageSource::factory($appConfig['type'], $appConfig['source'], $appConfig['filename']);
                $this->_source->setCulture($this->_language);
            }
            $this->_formatter = new MessageFormat(
                $this->_source,
                $this->_charset ?: Prado::getApplication()->getGlobalization()->getCharset()
            );
            $variables = [];
            foreach ($this->_variables as $varKey => $value) {
                $variables['{' . $varKey . '}'] = $value;
            }
            return $this->_formatter->format($key, $variables, $this->_catalogue);
        } else {
            return Prado::localize($key, $this->_variables);
        }
    }

}

?>