Skip to content

Commit

Permalink
Prevent forward-slashes in segment column from breaking hierarachy
Browse files Browse the repository at this point in the history
  • Loading branch information
bennothommo committed Dec 12, 2023
1 parent 1edb90e commit 9e57356
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
6 changes: 3 additions & 3 deletions src/Database/Traits/PathEnumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ public function getEnumerableSegment(): string
);
}

return (string) $this->getAttribute($this->getSegmentColumn());
return preg_replace('/(?<!\\\\)\//', '\\/', (string) $this->getAttribute($this->getSegmentColumn()));
}

/**
Expand Down Expand Up @@ -321,7 +321,7 @@ public function restoreDescendants(): void
*/
public function getDepth(): int
{
return substr_count($this->getPath(), '/') - 1;
return count(preg_split('/(?<!\\\\)\//', $this->getPath())) - 2;
}

/**
Expand Down Expand Up @@ -357,7 +357,7 @@ public function getParentId(): ?int
*/
public function getAncestorPaths(): array
{
$ids = explode('/', $this->getPath());
$ids = preg_split('/(?<!\\\\)\//', $this->getPath());
array_shift($ids);
array_pop($ids);

Expand Down
16 changes: 8 additions & 8 deletions tests/Database/Traits/PathEnumerableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ public function testPathsEnumeratedOnCreateWithDifferentSegmentColumn()
$daughter = new TestModelEnumerablePathNameSegment([
'name' => 'Daughter',
]);
$child = new TestModelEnumerablePathNameSegment([
'name' => 'Child',
$grandchild = new TestModelEnumerablePathNameSegment([
'name' => 'Grandaughter / Grandson',
]);

$grandparents->save();
Expand All @@ -211,14 +211,14 @@ public function testPathsEnumeratedOnCreateWithDifferentSegmentColumn()
$this->assertEquals(2, $daughter->getDepth());
$this->assertEquals(2, $daughter->getParents()->count());

$child->parent = $daughter;
$child->save();
$this->assertEquals('/Grandparents/Parents/Daughter/Child', $child->path);
$this->assertEquals(3, $child->getDepth());
$this->assertEquals(3, $child->getParents()->count());
$grandchild->parent = $daughter;
$grandchild->save();
$this->assertEquals('/Grandparents/Parents/Daughter/Grandaughter \/ Grandson', $grandchild->path);
$this->assertEquals(3, $grandchild->getDepth());
$this->assertEquals(3, $grandchild->getParents()->count());

// Check hierarchy
$hierarchy = $child->getParents();
$hierarchy = $grandchild->getParents();
$this->assertEquals($grandparents->name, $hierarchy->get(0)->name);
$this->assertEquals($parents->name, $hierarchy->get(1)->name);
$this->assertEquals($daughter->name, $hierarchy->get(2)->name);
Expand Down

0 comments on commit 9e57356

Please sign in to comment.