Skip to content

Commit

Permalink
fix: circular parent reference detection (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
sitepark-veltrup authored Sep 2, 2024
1 parent c40eb7f commit ca6c4f7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/Loader/SiteKitResourceHierarchyLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,18 @@ public function cleanup(): void
public function loadRoot(ResourceLocation $location): Resource
{
$resource = $this->resourceLoader->load($location);
$loaded = [$resource->location];
while (!$this->isRoot($resource)) {
$resource = $this->loadPrimaryParentResource($resource);
$parent = $this->loadPrimaryParentResource($resource);
if (in_array($parent->location, $loaded, true)) {
$loaded[] = $parent->location;
throw new InvalidResourceException(
$resource->toLocation(),
'circular parent reference detected: ' . implode(' -> ', $loaded),
);
}
$resource = $parent;
$loaded[] = $resource->location;
}

return $resource;
Expand Down
16 changes: 16 additions & 0 deletions test/Loader/SiteKitResourceHierarchyLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ public function testLoadRoot(): void
);
}

public function testLoadRootWithSelfRecursion(): void
{
$this->expectException(InvalidResourceException::class);
$this->hierarchyLoader->loadRoot(
ResourceLocation::of('/withSelfRecursion.php'),
);
}

public function testLoadRootWithRecursion(): void
{
$this->expectException(InvalidResourceException::class);
$this->hierarchyLoader->loadRoot(
ResourceLocation::of('/withRecursionA.php'),
);
}

public function testIsRoot(): void
{
$root = TestResourceFactory::create([]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Atoolo\Resource\Test\TestResourceFactory;

return TestResourceFactory::create([
'url' => '/dir/a.php',
'url' => '/dir/b.php',
'id' => 'a',
'name' => 'a',
'locale' => 'en_US',
Expand Down

0 comments on commit ca6c4f7

Please sign in to comment.