Completed
Push — master ( 9caa90...8321d8 )
by Tom
02:40
created

StringExtractor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2015 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.0                                                             */
7
namespace Transphporm\Parser;
8
class StringExtractor {
9
	private $str;
10
	private $stringTable;
11
12
	public function __construct($str) {
13
		$parts = $this->extractStrings($str);
14
		$this->str = $parts[0];
15
		$this->stringTable = $parts[1];
16
	}
17
18
	private function extractStrings($str) {
19
		$pos = 0;
20
		$num = 0;
21
		$strings = [];
22
		while (($pos = strpos($str, '"', $pos+1)) !== false) {
23
			$end = strpos($str, '"', $pos+1);
24
			while ($str[$end-1] == '\\') $end = strpos($str, '"', $end+1);
25
			$strings['$+STR' . ++$num] = substr($str, $pos, $end-$pos+1);
26
			$str = substr_replace($str, '$+STR' . $num, $pos, $end-$pos+1);
27
		}
28
29
		return [$str, $strings];
30
	}
31
32
	public function rebuild($str) {
33
		return str_replace(array_keys($this->stringTable), array_values($this->stringTable), $str);
34
	}
35
36
	public function __toString() {
37
		return $this->str;
38
	}
39
}