Completed
Push — master ( d9a437...4f5efd )
by Jared
06:32
created

Translator::setDataDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * @author Jared King <[email protected]>
5
 *
6
 * @see http://jaredtking.com
7
 *
8
 * @copyright 2015 Jared King
9
 * @license MIT
10
 */
11
12
namespace Pulsar;
13
14
use Pulsar\Interfaces\TranslatorInterface;
15
16
class Translator implements TranslatorInterface
17
{
18
    /**
19
     * @var string
20
     */
21
    private $locale = 'en';
22
23
    /**
24
     * @var string
25
     */
26
    private $dataDir;
27
28
    /**
29
     * @var array
30
     */
31
    private $data = [];
32
33
    public function __construct(?string $locale = null)
34
    {
35
        if ($locale) {
36
            $this->locale = $locale;
37
        }
38
    }
39
40
    /**
41
     * Sets the locale.
42
     *
43
     * @return $this
44
     */
45
    public function setLocale(string $locale)
46
    {
47
        $this->locale = $locale;
48
49
        return $this;
50
    }
51
52
    /**
53
     * Gets the locale.
54
     *
55
     * @return string
56
     */
57
    public function getLocale()
58
    {
59
        return $this->locale;
60
    }
61
62
    /**
63
     * Sets the directory where translation files can be loaded from.
64
     * Translation files are expected to be have the same name as the
65
     * locale with a .php extension. The translation file should return
66
     * an array with translations.
67
     *
68
     * @return $this
69
     */
70
    public function setDataDir(string $dir)
71
    {
72
        $this->dataDir = $dir;
73
74
        return $this;
75
    }
76
77
    public function translate(string $phrase, array $params = [], ?string $locale = null, ?string $fallback = null): string
78
    {
79
        if (!$locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
80
            $locale = $this->locale;
81
        }
82
83
        // lazy load locale data
84
        $this->loadLocaleData($locale);
85
86
        // look up the phrase
87
        $translatedPhrase = $this->data[$locale]['phrases'][$phrase] ?? null;
88
89
        // use the fallback phrase if a translated phrase is not
90
        // available
91
        if (!$translatedPhrase) {
92
            $translatedPhrase = $fallback;
93
        }
94
95
        if (null != $translatedPhrase) {
96
            // inject parameters into phrase
97
            if (count($params) > 0) {
98
                foreach ($params as $param => $paramValue) {
99
                    $translatedPhrase = str_replace('{{'.$param.'}}', $paramValue, $translatedPhrase);
100
                }
101
            }
102
103
            return $translatedPhrase;
104
        }
105
106
        // if the phrase does not exist for this locale
107
        // just return the phrase key
108
        return $phrase;
109
    }
110
111
    /**
112
     * Loads locale data for a supplied locale.
113
     *
114
     * @return $this
115
     */
116
    private function loadLocaleData(string $locale)
117
    {
118
        if (isset($this->data[$locale])) {
119
            return $this;
120
        }
121
122
        $filename = str_replace('//', '/', $this->dataDir.'/').$locale.'.php';
123
124
        if ($this->dataDir && file_exists($filename)) {
125
            $this->data[$locale] = include $filename;
126
        } else {
127
            $this->data[$locale] = [];
128
        }
129
130
        return $this;
131
    }
132
}
133