summaryrefslogtreecommitdiff
path: root/includes/helper/internationalization_helper.php
blob: 01aca71f4719d0307e51d15f1a5a4981aa6d332d (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

/**
 * Return currently active locale
 *
 * @return string
 */
function locale()
{
    return session()->get('locale');
}

/**
 * Returns two letter language code from currently active locale
 *
 * @return string
 */
function locale_short()
{
    return substr(locale(), 0, 2);
}

/**
 * Initializes gettext for internationalization and updates the sessions locale to use for translation.
 */
function gettext_init()
{
    $locales = config('locales');
    $request = request();
    $session = session();

    if ($request->has('set_locale') && isset($locales[$request->input('set_locale')])) {
        $session->set('locale', $request->input('set_locale'));
    } elseif (!$session->has('locale')) {
        $session->set('locale', config('default_locale'));
    }

    gettext_locale();
    bindtextdomain('default', app('path.lang'));
    bind_textdomain_codeset('default', 'UTF-8');
    textdomain('default');
}

/**
 * Swich gettext locale.
 *
 * @param string $locale
 */
function gettext_locale($locale = null)
{
    if ($locale == null) {
        $locale = session()->get('locale');
    }

    putenv('LC_ALL=' . $locale);
    setlocale(LC_ALL, $locale);
}

/**
 * Renders language selection.
 *
 * @return array
 */
function make_langselect()
{
    $request = app('request');

    $items = [];
    foreach (config('locales') as $locale => $name) {
        $url = url($request->getPathInfo(), ['set_locale' => $locale]);

        $items[] = toolbar_item_link(
            htmlspecialchars($url),
            '',
            $name,
            $locale == locale()
        );
    }
    return $items;
}