summaryrefslogtreecommitdiff
path: root/tools/inc/lib/jsgettext/JSParser.php
blob: 739d1195963be9ae9892394b1722b383311b6d43 (plain)
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
<?php

class JSParser {

	protected $content;
	protected $keywords;
	protected $regs = [];
	protected $regsCounter = 0;
	protected $strings = [];
	protected $stringsCounter = 0;

	protected function _extractRegs($match) {
		$this->regs[$this->regsCounter] = $match[1];
		$id = "<<reg{$this->regsCounter}>>";
		$this->regsCounter++;
		return $id;
	}
	protected function _extractStrings($match) {
		$this->strings[$this->stringsCounter] = $this->importRegExps($match[0]);
		$id = "<<s{$this->stringsCounter}>>";
		$this->stringsCounter++;
		return $id;
	}
	protected function importRegExps($input) {
		$regs = $this->regs;
		return preg_replace_callback("#<<reg(\d+)>>#", fn($match) => $regs[$match[1]], $input);
	}

	protected function importStrings($input) {
		$strings = $this->strings;
		return preg_replace_callback("#<<s(\d+)>>#", fn($match) => $strings[$match[1]], $input);
	}

	public function __construct($file, $keywords = '_') {
		$this->content = file_get_contents($file);
		$this->keywords = (array)$keywords;
	}
	
	public function parse() {
		$output = $this->content; //htmlspecialchars($this->content, ENT_NOQUOTES);

		// extract reg exps
		$output = preg_replace_callback(
			'# ( / (?: (?>[^/\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\/ )+ (?<!\\\\)/ ) [a-z]* \b #ix',
			$this->_extractRegs(...), $output
		);

		// extract strings
		$output = preg_replace_callback(
			['# " ( (?: (?>[^"\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\" )* ) (?<!\\\\)" #ix', "# ' ( (?: (?>[^'\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\' )* ) (?<!\\\\)' #ix"], $this->_extractStrings(...), $output
		);

		// delete line comments
		$output = preg_replace("#(//.*?)$#m", '', $output);

		// delete multiline comments
		$output = preg_replace('#/\*(.*?)\*/#is', '', $output);

		$strings = $this->strings;
		$output = preg_replace_callback("#<<s(\d+)>>#", fn($match) => $strings[$match[1]], $output);

		$keywords = implode('|', $this->keywords);

		$strings = [];

		// extract func calls
		preg_match_all(
			'# (?:'.$keywords.') \(\\ *" ( (?: (?>[^"\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\" )* ) (?<!\\\\)"\\ *\) #ix',
			$output, $matches, PREG_SET_ORDER
		);

		foreach ($matches as $m) $strings[] = stripslashes((string) $m[1]);

		$matches = [];
		preg_match_all(
			"# (?:$keywords) \(\\ *' ( (?: (?>[^'\\\\]++) | \\\\\\\\ | (?<!\\\\)\\\\(?!\\\\) | \\\\' )* ) (?<!\\\\)'\\ *\) #ix",
			$output, $matches, PREG_SET_ORDER
		);

		foreach ($matches as $m) $strings[] = stripslashes((string) $m[1]);

		return $strings;
	}
}
?>