Completed
Push — master ( 9fb92e...1099f2 )
by Tom
02:18
created

StringExtractor::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
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 (isset($str[$pos]) && ($pos = strpos($str, '"', $pos)) !== false) {
23
			$end = strpos($str, '"', $pos+1);
24
			if (!$end) break;
25
			while ($str[$end-1] == '\\') $end = strpos($str, '"', $end+1);
26
			$strings['$___STR' . ++$num] = substr($str, $pos, $end-$pos+1);
27
			$str = substr_replace($str, '$___STR' . $num, $pos, $end-$pos+1);
28
		}
29
30
		return [$str, $strings];
31
	}
32
33
	public function rebuild($str) {
34
		return str_replace(array_keys($this->stringTable), array_values($this->stringTable), $str);
35
	}
36
37
	public function __toString() {
38
		return $this->str;
39
	}
40
}