From 7f1daf858438549d4f6a26e09e728ccf553c700b Mon Sep 17 00:00:00 2001 From: Will Rossiter Date: Thu, 21 Sep 2023 11:38:56 +1200 Subject: [PATCH] FIX Element::getPage returning the wrong page --- src/Models/BaseElement.php | 13 ++++++++++--- tests/BaseElementTest.php | 13 +++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Models/BaseElement.php b/src/Models/BaseElement.php index 3eb35761..742b0c66 100644 --- a/src/Models/BaseElement.php +++ b/src/Models/BaseElement.php @@ -692,21 +692,28 @@ public function getSimpleClassName() /** * Despite the name of the method, getPage can return any type of DataObject + * * @return null|DataObject * @throws \Psr\Container\NotFoundExceptionInterface * @throws \SilverStripe\ORM\ValidationException */ public function getPage() { - // Allow for repeated calls to be cached if (isset($this->cacheData['page'])) { - return $this->cacheData['page']; + if (isset($this->cacheData['parent_id']) && $this->cacheData['parent_id'] === $this->ParentID) { + return $this->cacheData['page']; + } } $class = DataObject::getSchema()->hasOneComponent($this, 'Parent'); $area = ($this->ParentID) ? DataObject::get_by_id($class, $this->ParentID) : null; + if ($area instanceof ElementalArea && $area->exists()) { - $this->cacheData['page'] = $area->getOwnerPage(); + $page = $area->getOwnerPage(); + + $this->cacheData['page'] = $page; + $this->cacheData['parent_id'] = $this->ParentID; + return $this->cacheData['page']; } diff --git a/tests/BaseElementTest.php b/tests/BaseElementTest.php index 2a7f871a..ad6ce471 100644 --- a/tests/BaseElementTest.php +++ b/tests/BaseElementTest.php @@ -511,4 +511,17 @@ public function testGetContentForCmsSearch() $element = $this->objFromFixture(TestElement::class, 'elementDataObject3'); $this->assertSame('Hello Test|#|Element 3', $element->getContentForCmsSearch()); } + + + public function testGetPage() + { + $element = $this->objFromFixture(ElementContent::class, 'content1'); + + $this->assertStringContainsString($element->getPage()->Title, 'Test Elemental'); + + $newArea = $this->objFromFixture(ElementalArea::class, 'area52'); + $element->ParentID = $newArea->ID; + + $this->assertStringContainsString($element->getPage()->Title, 'Page with one elements'); + } }