-
Notifications
You must be signed in to change notification settings - Fork 1
/
MutableString.php
50 lines (39 loc) · 1.33 KB
/
MutableString.php
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
<?php declare(strict_types=1);
namespace TypeUtil;
/** String that can be modified without invalidating offsets into it */
class MutableString {
use NoDynamicProperties;
private $string;
// [[pos, len, newString]]
private $modifications = [];
public function __construct(string $string) {
$this->string = $string;
}
public function insert(int $pos, string $newString) : void {
$this->modifications[] = [$pos, 0, $newString];
}
public function remove(int $pos, int $len) : void {
$this->modifications[] = [$pos, $len, ''];
}
public function indexOf(string $str, int $startPos) /* : int|false */ {
return strpos($this->string, $str, $startPos);
}
public function getOrigString() : string {
return $this->string;
}
public function getModifiedString() : string {
// Sort by position
usort($this->modifications, function($a, $b) {
return $a[0] <=> $b[0];
});
$result = '';
$startPos = 0;
foreach ($this->modifications as list($pos, $len, $newString)) {
$result .= substr($this->string, $startPos, $pos - $startPos);
$result .= $newString;
$startPos = $pos + $len;
}
$result .= substr($this->string, $startPos);
return $result;
}
}