-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathTextEdit.php
53 lines (47 loc) · 1.92 KB
/
TextEdit.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
50
51
52
53
<?php
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft\PhpParser;
class TextEdit {
/** @var int */
public $start;
/** @var int */
public $length;
/** @var string */
public $content;
public function __construct(int $start, int $length, string $content) {
$this->start = $start;
$this->length = $length;
$this->content = $content;
}
/**
* Applies array of edits to the document, and returns the resulting text.
* Supplied $edits must not overlap, and be ordered by increasing start position.
*
* Note that after applying edits, the original AST should be invalidated.
*
* @param TextEdit[] $edits
* @param string $text
* @return string
*/
public static function applyEdits(array $edits, string $text) : string {
$prevEditStart = PHP_INT_MAX;
for ($i = \count($edits) - 1; $i >= 0; $i--) {
$edit = $edits[$i];
\assert(
$prevEditStart > $edit->start && $prevEditStart > $edit->start + $edit->length,
"Supplied TextEdit[] must not overlap, and be in increasing start position order."
);
if ($edit->start < 0 || $edit->length < 0 || $edit->start + $edit->length > \strlen($text)) {
throw new \OutOfBoundsException("Applied TextEdit range out of bounds.");
}
$prevEditStart = $edit->start;
$head = \substr($text, 0, $edit->start);
$tail = \substr($text, $edit->start + $edit->length);
$text = $head . $edit->content . $tail;
}
return $text;
}
}