1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of byrokrat\autogiro. |
5
|
|
|
* |
6
|
|
|
* byrokrat\autogiro is free software: you can redistribute it and/or |
7
|
|
|
* modify it under the terms of the GNU General Public License as published |
8
|
|
|
* by the Free Software Foundation, either version 3 of the License, or |
9
|
|
|
* (at your option) any later version. |
10
|
|
|
* |
11
|
|
|
* byrokrat\autogiro is distributed in the hope that it will be useful, |
12
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
13
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14
|
|
|
* GNU General Public License for more details. |
15
|
|
|
* |
16
|
|
|
* You should have received a copy of the GNU General Public License |
17
|
|
|
* along with byrokrat\autogiro. If not, see <http://www.gnu.org/licenses/>. |
18
|
|
|
* |
19
|
|
|
* Copyright 2016-21 Hannes Forsgård |
20
|
|
|
*/ |
21
|
|
|
|
22
|
|
|
declare(strict_types=1); |
23
|
|
|
|
24
|
|
|
namespace byrokrat\autogiro; |
25
|
|
|
|
26
|
|
|
class MessageRetriever |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* Match all wildcard key |
30
|
|
|
*/ |
31
|
|
|
public const WILDCARD = '*'; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Default location of messages file |
35
|
|
|
*/ |
36
|
|
|
public const DEFAULT_MESSAGE_STORE = __DIR__ . '/messages.json'; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var array<string, array> |
40
|
|
|
*/ |
41
|
|
|
private $messages; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param array<string, array> $messages |
45
|
|
|
*/ |
46
|
|
|
public function __construct(array $messages = []) |
47
|
|
|
{ |
48
|
|
|
$this->messages = $messages ?: json_decode((string)file_get_contents(self::DEFAULT_MESSAGE_STORE), true); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function readMessage(string ...$keys): string |
52
|
|
|
{ |
53
|
|
|
return $this->pickMessage($this->messages, ...$keys); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param array<string, array> $messages |
58
|
|
|
*/ |
59
|
|
|
private function pickMessage(array $messages, string $key, string ...$additionalKeys): string |
60
|
|
|
{ |
61
|
|
|
$value = $messages[$key] ?? []; |
62
|
|
|
|
63
|
|
|
if (!empty($additionalKeys)) { |
64
|
|
|
$value = $this->pickMessage((array)$value, ...$additionalKeys); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (!$value && $key != self::WILDCARD) { |
68
|
|
|
$value = $this->pickMessage($messages, self::WILDCARD, ...$additionalKeys); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if (!is_scalar($value)) { |
72
|
|
|
return ''; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return (string)$value; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|