Skip to content

Commit

Permalink
feat: switch blog for PostObjectFromOtherBlog::getPermalink() (#1248)
Browse files Browse the repository at this point in the history
* feat: switch blog for PostObjectFromOtherBlog::getPermalink()

* docs: add documentation for blog switching methods in PostObjectFromOtherBlog
  • Loading branch information
thorbrink authored Jan 15, 2025
1 parent 0888428 commit 286fc1d
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions library/PostObject/Decorators/PostObjectFromOtherBlog.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ public function getTitle(): string
*/
public function getPermalink(): string
{
return $this->postObject->getPermalink();
if (!$this->shouldSwitch()) {
return $this->postObject->getPermalink();
}

return $this->getValueFromOtherBlog(fn() => $this->postObject->getPermalink());
}

/**
Expand All @@ -69,18 +73,11 @@ public function getPostType(): string
*/
public function getIcon(): ?IconInterface
{
if (!$this->wpService->isMultisite()) {
return $this->postObject->getIcon();
}

if ($this->getBlogId() === $this->wpService->getCurrentBlogId()) {
if (!$this->shouldSwitch()) {
return $this->postObject->getIcon();
}

$this->wpService->switchToBlog($this->getBlogId());
$icon = $this->postObject->getIcon();
$this->wpService->restoreCurrentBlog();
return $icon;
return $this->getValueFromOtherBlog(fn() => $this->postObject->getIcon());
}

/**
Expand All @@ -90,4 +87,42 @@ public function getBlogId(): int
{
return $this->blogId ?? $this->postObject->getBlogId();
}

/**
* Get the value from another blog.
*/
private function getValueFromOtherBlog(callable $callback)
{
$this->switch();
$value = $callback();
$this->restore();

return $value;
}

/**
* Determine if we should switch to another blog.
*
* @return bool
*/
private function shouldSwitch(): bool
{
return $this->wpService->isMultisite() && $this->getBlogId() !== $this->wpService->getCurrentBlogId();
}

/**
* Switch to another blog.
*/
private function switch(): void
{
$this->wpService->switchToBlog($this->getBlogId());
}

/**
* Restore the current blog.
*/
private function restore(): void
{
$this->wpService->restoreCurrentBlog();
}
}

0 comments on commit 286fc1d

Please sign in to comment.