Completed
Push — master ( 1099f2...b313d2 )
by Tom
10:52 queued 20s
created

StringExtractor   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 9
c 3
b 1
f 0
lcom 1
cbo 0
dl 0
loc 38
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A extractStrings() 0 14 4
A getNextPosEscaped() 0 4 2
A rebuild() 0 3 1
A __toString() 0 3 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 (isset($str[$pos]) && ($pos = strpos($str, '"', $pos)) !== false) {
23
			$end = strpos($str, '"', $pos+1);
24
			if (!$end) break;
25
			$end = $this->getNextPosEscaped($str, '\\', '"', $end);
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
	private function getNextPosEscaped($str, $escape, $chr, $start) {
34
		while ($str[$start-1] == $escape) $start = strpos($str, $chr, $start+1);
35
		return $start;
36
	}
37
38
	public function rebuild($str) {
39
		return str_replace(array_keys($this->stringTable), array_values($this->stringTable), $str);
40
	}
41
42
	public function __toString() {
43
		return $this->str;
44
	}
45
}