xref: /plugin/struct/meta/TranslationUtilities.php (revision 5b808f9f3f75388ac6c41d0df9054f222dd3b92b)
1<?php
2
3namespace  dokuwiki\plugin\struct\meta;
4
5trait TranslationUtilities
6{
7
8
9    /**
10     * Add the translatable keys to the configuration
11     *
12     * This checks if a configuration for the translation plugin exists and if so
13     * adds all configured languages to the config array. This ensures all types
14     * can have translatable labels.
15     *
16     * @param string[] $keysToInitialize the keys for which to initialize language fields
17     */
18    protected function initTransConfig(array $keysToInitialize = array('label', 'hint'))
19    {
20        global $conf;
21        $lang = $conf['lang'];
22        if (isset($conf['plugin']['translation']['translations'])) {
23            $lang .= ' ' . $conf['plugin']['translation']['translations'];
24        }
25        $langs = explode(' ', $lang);
26        $langs = array_map('trim', $langs);
27        $langs = array_filter($langs);
28        $langs = array_unique($langs);
29
30        foreach ($keysToInitialize as $key) {
31            if (!isset($this->config[$key])) {
32                $this->config[$key] = array();
33            }
34            // initialize missing keys
35            foreach ($langs as $lang) {
36                if (!isset($this->config[$key][$lang])) {
37                    $this->config[$key][$lang] = '';
38                }
39            }
40            // strip unknown languages
41            foreach (array_keys($this->config[$key]) as $langKey) {
42                if (!in_array($langKey, $langs)) {
43                    unset($this->config[$key][$langKey]);
44                }
45            }
46        }
47    }
48
49    /**
50     * Returns the translated key
51     *
52     * Uses the current language as determined by $conf['lang']. Falls back to english
53     * and then to the provided default
54     *
55     * @param string $key
56     * @param string $default the default to return if there is no translation set for $key
57     *
58     * @return string
59     */
60    public function getTranslatedKey($key, $default)
61    {
62        global $conf;
63        $lang = $conf['lang'];
64        if (!blank($this->config[$key][$lang])) {
65            return $this->config[$key][$lang];
66        }
67        if (!blank($this->config[$key]['en'])) {
68            return $this->config[$key]['en'];
69        }
70        return $default;
71    }
72}
73