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
|
|
|
private $paths; |
11
|
|
|
private $defaultDomain; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @param string[] $paths |
15
|
|
|
* @param string $defaultDomain |
16
|
|
|
*/ |
17
|
2 |
|
public function __construct(array $paths, $defaultDomain) |
18
|
|
|
{ |
19
|
2 |
|
$this->paths = $paths; |
20
|
2 |
|
$this->defaultDomain = $defaultDomain; |
21
|
2 |
|
} |
22
|
|
|
|
23
|
2 |
|
public function extract(MessageCatalogue $catalogue) |
24
|
|
|
{ |
25
|
2 |
|
$directories = array(); |
26
|
|
|
|
27
|
2 |
|
foreach ($this->paths as $path) { |
28
|
2 |
|
if (is_dir($path)) { |
29
|
1 |
|
$directories[] = $path; |
30
|
|
|
|
31
|
1 |
|
continue; |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
if (is_file($path)) { |
35
|
1 |
|
$this->extractTranslations($catalogue, file_get_contents($path)); |
36
|
1 |
|
} |
37
|
2 |
|
} |
38
|
|
|
|
39
|
2 |
|
if ($directories) { |
|
|
|
|
40
|
1 |
|
$finder = new Finder(); |
41
|
|
|
|
42
|
1 |
|
$finder->files() |
43
|
1 |
|
->in($directories) |
44
|
1 |
|
->name('*.js'); |
45
|
|
|
|
46
|
1 |
|
foreach ($finder as $file) { |
47
|
1 |
|
$this->extractTranslations($catalogue, $file->getContents()); |
48
|
1 |
|
} |
49
|
1 |
|
} |
50
|
2 |
|
} |
51
|
|
|
|
52
|
2 |
|
private function extractTranslations(MessageCatalogue $catalogue, $fileContent) |
53
|
|
|
{ |
54
|
|
|
$pattern = <<<REGEXP |
55
|
|
|
/ |
56
|
|
|
\.trans(?:Choice)?\s*+\(\s*+ |
57
|
|
|
(?: |
58
|
|
|
'([^']++)' # single-quoted string |
59
|
|
|
| |
60
|
|
|
"([^"]++)" # double-quoted string |
61
|
|
|
) |
62
|
|
|
\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) |
63
|
|
|
/x |
64
|
2 |
|
REGEXP; |
65
|
|
|
|
66
|
2 |
|
preg_match_all($pattern, $fileContent, $matches); |
67
|
|
|
|
68
|
2 |
|
foreach ($matches[1] as $match) { |
69
|
2 |
|
if (empty($match)) { |
70
|
2 |
|
continue; |
71
|
|
|
} |
72
|
|
|
|
73
|
2 |
|
$catalogue->set($match, $match, $this->defaultDomain); |
74
|
2 |
|
} |
75
|
|
|
|
76
|
2 |
|
foreach ($matches[2] as $match) { |
77
|
2 |
|
if (empty($match)) { |
78
|
2 |
|
continue; |
79
|
|
|
} |
80
|
|
|
|
81
|
2 |
|
$catalogue->set($match, $match, $this->defaultDomain); |
82
|
2 |
|
} |
83
|
2 |
|
} |
84
|
|
|
} |
85
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.