|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Incenteev\TranslationCheckerBundle\Translator\Extractor; |
|
4
|
|
|
|
|
5
|
|
|
use Symfony\Component\Finder\Finder; |
|
6
|
|
|
use Symfony\Component\Translation\MessageCatalogue; |
|
7
|
|
|
|
|
8
|
|
|
class JsExtractor implements ExtractorInterface |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var string[] |
|
12
|
|
|
*/ |
|
13
|
|
|
private array $paths; |
|
14
|
|
|
private string $defaultDomain; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
2 |
|
* @param string[] $paths |
|
18
|
|
|
*/ |
|
19
|
2 |
|
public function __construct(array $paths, string $defaultDomain) |
|
20
|
2 |
|
{ |
|
21
|
2 |
|
$this->paths = $paths; |
|
22
|
|
|
$this->defaultDomain = $defaultDomain; |
|
23
|
2 |
|
} |
|
24
|
|
|
|
|
25
|
2 |
|
public function extract(MessageCatalogue $catalogue): void |
|
26
|
|
|
{ |
|
27
|
2 |
|
$directories = array(); |
|
28
|
2 |
|
|
|
29
|
1 |
|
foreach ($this->paths as $path) { |
|
30
|
|
|
if (is_dir($path)) { |
|
31
|
1 |
|
$directories[] = $path; |
|
32
|
|
|
|
|
33
|
|
|
continue; |
|
34
|
1 |
|
} |
|
35
|
1 |
|
|
|
36
|
|
|
if (is_file($path)) { |
|
37
|
|
|
$contents = file_get_contents($path); |
|
38
|
|
|
if ($contents === false) { |
|
39
|
2 |
|
throw new \RuntimeException(sprintf('Failed to read the file "%s"', $path)); |
|
40
|
1 |
|
} |
|
41
|
|
|
|
|
42
|
1 |
|
$this->extractTranslations($catalogue, $contents); |
|
43
|
1 |
|
} |
|
44
|
1 |
|
} |
|
45
|
|
|
|
|
46
|
1 |
|
if ($directories) { |
|
47
|
1 |
|
$finder = new Finder(); |
|
48
|
|
|
|
|
49
|
|
|
$finder->files() |
|
50
|
2 |
|
->in($directories) |
|
51
|
|
|
->name('*.js'); |
|
52
|
2 |
|
|
|
53
|
|
|
foreach ($finder as $file) { |
|
54
|
|
|
$this->extractTranslations($catalogue, $file->getContents()); |
|
55
|
2 |
|
} |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function extractTranslations(MessageCatalogue $catalogue, string $fileContent): void |
|
60
|
|
|
{ |
|
61
|
|
|
$pattern = <<<REGEXP |
|
62
|
|
|
/ |
|
63
|
|
|
\.trans(?:Choice)?\s*+\(\s*+ |
|
64
|
|
|
(?: |
|
65
|
|
|
'([^']++)' # single-quoted string |
|
66
|
2 |
|
| |
|
67
|
|
|
"([^"]++)" # double-quoted string |
|
68
|
2 |
|
) |
|
69
|
2 |
|
\s*+[,)] # followed by a comma (for next arguments) or the closing parenthesis, to be sure we got the whole argument (no concatenation to something else) |
|
70
|
2 |
|
/x |
|
71
|
|
|
REGEXP; |
|
72
|
|
|
|
|
73
|
2 |
|
preg_match_all($pattern, $fileContent, $matches); |
|
74
|
|
|
|
|
75
|
|
|
foreach ($matches[1] as $match) { |
|
76
|
2 |
|
if (empty($match)) { |
|
77
|
2 |
|
continue; |
|
78
|
2 |
|
} |
|
79
|
|
|
|
|
80
|
|
|
$catalogue->set($match, $match, $this->defaultDomain); |
|
81
|
2 |
|
} |
|
82
|
|
|
|
|
83
|
2 |
|
foreach ($matches[2] as $match) { |
|
84
|
|
|
if (empty($match)) { |
|
85
|
|
|
continue; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
$catalogue->set($match, $match, $this->defaultDomain); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|