Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/TextEdit.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,14 @@ 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 ($prevEditStart < $edit->start || $prevEditStart < $edit->start + $edit->length) {
throw new \OutOfBoundsException(sprintf(
'Supplied TextEdit[] "%s" must not overlap and be in increasing start position order.',
$edit->content
));
}

if ($edit->start < 0 || $edit->length < 0 || $edit->start + $edit->length > \strlen($text)) {
throw new \OutOfBoundsException("Applied TextEdit range out of bounds.");
}
Expand Down
25 changes: 23 additions & 2 deletions tests/api/TextEditTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ public function testApplyMultipleEdits() {
$this->assertEquals($expected, TextEdit::applyEdits($edits, $content));
}

public function testApplyMultipleEditsAtSameOffset() {
$content = self::INPUT_TEXT;

$expected = <<< 'PHP'
helloawesome<?php

function a () { }

function b () { }
PHP
;
$edits = [
new TextEdit(0, 0, "hello"),
new TextEdit(0, 0, "awesome"),
new TextEdit(0, 0, "")
];

$this->assertEquals($expected, TextEdit::applyEdits($edits, $content));
}


public function testApplyingEmptyTextEditArray() {
$content = self::INPUT_TEXT;

Expand All @@ -88,7 +109,7 @@ public function testOutOfOrderTextEdits() {
new TextEdit(0, 10, 10),
new TextEdit(0, 4 ,3)
];
$this->expectException(AssertionError::class);
$this->expectException(OutOfBoundsException::class);
TextEdit::applyEdits($edits, $content);
}

Expand All @@ -98,7 +119,7 @@ public function testOverlappingTextEdits() {
new TextEdit(0, 4, 10),
new TextEdit(0, 10, 10)
];
$this->expectException(AssertionError::class);
$this->expectException(OutOfBoundsException::class);
TextEdit::applyEdits($edits, $content);
}

Expand Down