-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Parser.php
109 lines (80 loc) · 2.2 KB
/
Parser.php
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
<?php
namespace LaravelLang\Lang\Support;
use Helldar\Support\Concerns\Makeable;
use Helldar\Support\Facades\Helpers\Arr;
use Helldar\Support\Facades\Helpers\Str;
class Parser
{
use Makeable;
protected const REGEX = '/\b(__|trans|lang|Lang\:\:get|fail)\(\r*\s*(.+)\r*\s*(\)|,\s?\[)/U';
protected array $files = [];
protected array $keys = [];
public function files(array $files): self
{
$this->files = $files;
return $this;
}
public function get(): array
{
$this->clear();
$this->each();
$this->sort();
return $this->keys();
}
protected function clear(): void
{
$this->keys = [];
}
protected function each(): void
{
foreach ($this->files as $file) {
$content = file_get_contents($file);
$this->parse($content);
}
}
protected function sort(): void
{
Arr::ksort($this->keys);
}
protected function parse(string $content): void
{
foreach ($this->match($content) as $match) {
$value = $match;
if (Str::contains((string) $value, ['__', 'trans', '@lang', 'Lang::get', '->fail('])) {
$sub_key = $this->subkey($value);
$sub_value = $this->keys[$sub_key] ?? null;
$this->push($sub_value);
}
$this->push($value);
}
}
protected function match(string $content, string $pattern = self::REGEX): array
{
preg_match_all($pattern, $content, $matches);
return $matches[2] ?? [];
}
protected function push(mixed $value): void
{
$value = $this->trim($value);
if (! isset($this->keys[$value])) {
$this->keys[$value] = $value;
}
}
protected function subkey(string $value): string
{
$sub_key = $this->match($value)[0];
return $this->trim($sub_key);
}
protected function keys(): array
{
return $this->keys;
}
protected function trim($value)
{
if (is_string($value)) {
$chars = " \t\n\r\0\x0B'\"";
return trim(stripslashes($value), $chars);
}
return $value;
}
}