diff --git a/src/services/Elements.php b/src/services/Elements.php index 4876e3ba6e2..8886c13eafd 100644 --- a/src/services/Elements.php +++ b/src/services/Elements.php @@ -779,9 +779,9 @@ public function stopCollectingCacheInfo(): array if (!empty($this->_cacheTagBuffers)) { $this->_cacheTags = array_merge(array_pop($this->_cacheTagBuffers), $tags); - // Override the parent duration if ours is shorter + // Preserve the shortest duration across nested collections $this->_cacheDuration = array_pop($this->_cacheDurationBuffers); - if ($duration && $duration < $this->_cacheDuration) { + if ($duration && (!$this->_cacheDuration || $duration < $this->_cacheDuration)) { $this->_cacheDuration = $duration; } } else { diff --git a/tests/unit/services/ElementsTest.php b/tests/unit/services/ElementsTest.php index e567e77dd62..a4c41821fcb 100644 --- a/tests/unit/services/ElementsTest.php +++ b/tests/unit/services/ElementsTest.php @@ -12,6 +12,7 @@ use Craft; use craft\elements\Entry; +use craft\helpers\DateTimeHelper; use craft\services\Elements; use craft\test\TestCase; use craft\test\TestSetup; @@ -83,6 +84,20 @@ public function testParseRefs(): void } } + public function testNestedCacheInfoPreservesExpiry(): void + { + $this->elements->startCollectingCacheInfo(); + $this->elements->collectCacheTags(['test']); + $this->elements->startCollectingCacheInfo(); + $this->elements->setCacheExpiryDate(DateTimeHelper::now()->modify('+60 seconds')); + $this->elements->stopCollectingCacheInfo(); + [, $duration] = $this->elements->stopCollectingCacheInfo(); + + self::assertNotNull($duration); + self::assertGreaterThan(0, $duration); + self::assertLessThanOrEqual(60, $duration); + } + /** * @inheritdoc */