summaryrefslogtreecommitdiff
path: root/lib/translator.php
blob: d9d9a84ac7293e6322952f8355ba92bcb614eb52 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php

namespace Translator {

    const PATH = 'locales/';

    function translate($identifier)
    {
        $args = \func_get_args();

        \array_shift($args);
        \array_unshift($args, get($identifier, $identifier));

        return \call_user_func_array(
            'sprintf',
            $args
        );
    }

    function number($number)
    {
        return number_format(
            $number,
            get('number.decimals', 2),
            get('number.decimals_separator', '.'),
            get('number.thousands_separator', ',')
        );
    }

    function currency($amount)
    {
        $position = get('currency.position', 'before');
        $symbol = get('currency.symbol', '$');
        $str = '';

        if ($position === 'before') {
            $str .= $symbol;
        }

        $str .= number($amount);

        if ($position === 'after') {
            $str .= ' '.$symbol;
        }

        return $str;
    }

    function datetime($format, $timestamp)
    {
        return strftime(get($format, $format), (int) $timestamp);
    }

    function get($identifier, $default = '')
    {
        $locales = container();

        if (isset($locales[$identifier])) {
            return $locales[$identifier];
        }
        else {
            return $default;
        }
    }

    function load($language)
    {
        setlocale(LC_TIME, $language.'.UTF-8');

        $path = PATH.$language;
        $locales = array();

        if (is_dir($path)) {

            $dir = new \DirectoryIterator($path);

            foreach ($dir as $fileinfo) {

                if (strpos($fileinfo->getFilename(), '.php') !== false) {

                    $locales = array_merge($locales, include $fileinfo->getPathname());
                }
            }
        }

        container($locales);
    }

    function container($locales = null)
    {
        static $values = array();

        if ($locales !== null) {

            $values = $locales;
        }

        return $values;
    }
}


namespace {

    function t() {
        return call_user_func_array('\Translator\translate', func_get_args());
    }

    function c() {
        return call_user_func_array('\Translator\currency', func_get_args());
    }

    function n() {
        return call_user_func_array('\Translator\number', func_get_args());
    }

    function dt() {
        return call_user_func_array('\Translator\datetime', func_get_args());
    }
}