Skip to content

Commit

Permalink
perf: Optimize getPagesFromFolder to avoid requests for files that al…
Browse files Browse the repository at this point in the history
…ready get obtained through directory listing

Signed-off-by: Julius Härtl <[email protected]>
  • Loading branch information
juliusknorr authored and mejo- committed Aug 13, 2024
1 parent 8c98d02 commit 63eba49
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
30 changes: 17 additions & 13 deletions lib/Service/PageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -382,27 +382,31 @@ private function getIndexPageFile(Folder $folder): File {
* @throws NotPermittedException
*/
public function getPagesFromFolder(int $collectiveId, Folder $folder, string $userId, bool $recurse = false): array {
// Find index page or create it if we have subpages, but it doesn't exist
try {
$indexPage = $this->getPageByFile($this->getIndexPageFile($folder), $folder);
} catch (NotFoundException) {
if (!NodeHelper::folderHasSubPages($folder)) {
return [];
}
$indexPage = $this->newPage($collectiveId, $folder, PageInfo::INDEX_PAGE_TITLE, $userId);
}
$pageInfos = [$indexPage];
$pageInfos = [];
$indexPage = null;

// Add subpages and recurse over subfolders
foreach ($folder->getDirectoryListing() as $node) {
if ($node instanceof File && NodeHelper::isPage($node) && !NodeHelper::isIndexPage($node)) {
$pageInfos[] = $this->getPageByFile($node, $folder);
if ($node instanceof File && NodeHelper::isPage($node)) {
$page = $this->getPageByFile($node, $folder);
if (NodeHelper::isIndexPage($node)) {
$indexPage = $page;
} else {
$pageInfos[] = $page;
}
} elseif ($recurse && $node instanceof Folder) {
array_push($pageInfos, ...$this->getPagesFromFolder($collectiveId, $node, $userId, true));
}
}

return $pageInfos;
if (!$indexPage) {
if (count($pageInfos) === 0) {
return [];
}
$indexPage = $this->newPage($collectiveId, $folder, PageInfo::INDEX_PAGE_TITLE, $userId);
}

return array_merge([$indexPage], $pageInfos);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/Unit/Service/PageServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ public function testGetPagesFromFolder(): void {
$indexPageInfo->setParentId(101);
$indexPageInfo->setTitle('testfolder');

$filesJustMd[] = $indexPageInfo;
$filesNotJustMd[] = $indexPageInfo;
$filesJustMd[] = $indexFile;
$filesNotJustMd[] = $indexFile;
$pageInfos[] = $indexPageInfo;

$fileNameList = [ 'page1.md', 'page2.md', 'page3.md', 'another.jpg', 'whatever.txt' ];
Expand Down

0 comments on commit 63eba49

Please sign in to comment.