diff --git a/src/DonutBody.php b/src/DonutBody.php new file mode 100644 index 00000000..24471228 --- /dev/null +++ b/src/DonutBody.php @@ -0,0 +1,58 @@ + $body each embedded request null + * @param array $embeds toUri() of each request embedded in the body, by its key + * @param array $headers + */ + public function __construct( + private array $body, + private array $embeds, + private array $headers, + private int $code, + ) { + } + + /** The renderer reads the stored headers and code; the code is set again in case the renderer changed it */ + #[Override] + public function recompose(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void + { + $body = $this->body; + $requests = []; + foreach ($this->embeds as $key => $reference) { + $request = $resource->uri($reference); + assert($request instanceof AbstractRequest); + $requests[] = $body[$key] = $request; + } + + $ro->body = $body; + $ro->headers = $this->headers; + $ro->code = $this->code; + $ro->view = null; + $ro->toString(); + foreach ($requests as $request) { + // After rendering: what a request passes up from the requests it embeds itself is known once those have run + $dependencies->hole(DonutRequest::resultOf($request)); + } + + $ro->code = $this->code; + } +} diff --git a/src/DonutCompositionInterface.php b/src/DonutCompositionInterface.php new file mode 100644 index 00000000..1251baa4 --- /dev/null +++ b/src/DonutCompositionInterface.php @@ -0,0 +1,23 @@ +rendererProvider->get(); $donut = ResourceDonut::create($ro, $renderer, $keys, $sMaxAge, $isPage)->withStorageState($ttl, $templateTags); - $donut->render($ro, $renderer); // Checked on the rendered response before the write adds its own headers $storability = $this->declaredCacheControl->storability($ro); $keys->addTo($ro); diff --git a/src/DonutTemplate.php b/src/DonutTemplate.php new file mode 100644 index 00000000..10cb1d59 --- /dev/null +++ b/src/DonutTemplate.php @@ -0,0 +1,46 @@ + $headers */ + public function __construct( + private string $template, + private array $headers, + private int $code, + ) { + } + + /** $ro is left untouched until every hole has been read */ + #[Override] + public function recompose(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void + { + $view = preg_replace_callback(ResourceDonut::URI_REGEX, static function (array $matches) use ($resource, $dependencies): string { + $reference = rawurldecode($matches[1]); + // toString(), not (string): the cast turns a render failure into '', which would be served + $hole = $resource->get($reference); + $hole->toString(); + $dependencies->hole($hole); + + return (string) $hole->view; + }, $this->template); + $ro->headers = $this->headers; + $ro->view = $view; + $ro->code = $this->code; + } +} diff --git a/src/ResourceDonut.php b/src/ResourceDonut.php index a43adc0f..35cacee8 100644 --- a/src/ResourceDonut.php +++ b/src/ResourceDonut.php @@ -17,8 +17,6 @@ use function is_array; use function is_iterable; use function max; -use function preg_replace_callback; -use function rawurldecode; use function rawurlencode; use function serialize; use function sprintf; @@ -30,13 +28,13 @@ * * @internal */ -final class ResourceDonut +final readonly class ResourceDonut { // The reference is rawurlencode()'d: percent-encoding leaves no '&', '<', '>', '"' or '\'' for an HTML renderer's // autoescaping to change, so the placeholder reads the same echoed raw or through Twig's `{{ hole }}` private const FORMAT = '[le2:%s]'; - private const URI_REGEX = '/\[le2:([^\]]+)]/'; + public const URI_REGEX = '/\[le2:([^\]]+)]/'; /** * Build the placeholder DonutRequest::__toString() embeds and DonutRenderer matches @@ -47,28 +45,18 @@ public static function placeholder(string $reference): string } /** - * @param array $headers - * @param int|null $sMaxAge CDN lifetime and stored lifetime of the page view; unused by a template-only donut - * @param int|null $lastModified Time when the composed content last actually changed - * @param list $storageTags Invalidation tags of the donut template entry, without the application key the storage adds - * @param int $code Status code the page was stored with - * @param array|null $body The body the page returned, each embedded request null, when its renderer prints no placeholder; null when the template holds the page - * @param array $embeds toUri() of each request embedded in the body, by its key - * - * @SuppressWarnings("PHPMD.ExcessiveParameterList") + * @param int|null $sMaxAge CDN lifetime and stored lifetime of the page view; unused when $isPage is false + * @param int|null $lastModified Time when the composed content last actually changed + * @param list $storageTags Invalidation tags of the donut template entry, without the application key the storage adds */ public function __construct( - private readonly string $template, - private readonly array $headers, - public readonly int|null $sMaxAge, - public readonly bool $isPage, - private readonly int|null $lastModified = null, - private readonly string|null $contentHash = null, - private readonly int|null $templateExpiresAt = null, - private readonly array $storageTags = [], - private readonly int $code = 200, - private readonly array|null $body = null, - private readonly array $embeds = [], + private DonutCompositionInterface $composition, + public int|null $sMaxAge, + public bool $isPage, + private int|null $lastModified = null, + private string|null $contentHash = null, + private int|null $templateExpiresAt = null, + private array $storageTags = [], ) { } @@ -76,19 +64,9 @@ public function __construct( public function refresh(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): ResourceObject { try { - if ($this->body === null) { - $view = $this->compose($resource, $dependencies); - $ro->headers = $this->headers; - $ro->view = $view; - } - - if ($this->body !== null) { - $this->renderBody($this->body, $resource, $ro, $dependencies); - } + $this->composition->recompose($resource, $ro, $dependencies); - $ro->code = $this->code; - - // $this->headers lacks the group tag; add the stored tags. + // The stored headers lack the group tag (new TagSet($this->getStorageTags()))->addTo($ro); $dependencies->addTo($ro); @@ -99,58 +77,6 @@ public function refresh(ResourceInterface $resource, ResourceObject $ro, Depende return $ro; } - /** The template with the view of each embedded request, read again, in its place */ - private function compose(ResourceInterface $resource, Dependencies $dependencies): string|null - { - return preg_replace_callback(self::URI_REGEX, static function (array $matches) use ($resource, $dependencies): string { - $reference = rawurldecode($matches[1]); - // toString(), not (string): the cast turns a render failure into '', which would be served - $ro = $resource->get($reference); - $ro->toString(); - $dependencies->hole($ro); - - return (string) $ro->view; - }, $this->template); - } - - /** - * Renders the stored body with the page's own renderer, its embedded requests put back - * - * @param array $body - */ - private function renderBody(array $body, ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void - { - $requests = []; - foreach ($this->embeds as $key => $reference) { - $request = $resource->uri($reference); - assert($request instanceof AbstractRequest); - $requests[] = $body[$key] = $request; - } - - $ro->body = $body; - $ro->headers = $this->headers; - $ro->code = $this->code; - $ro->view = null; - $ro->toString(); - foreach ($requests as $request) { - // After rendering: what a request passes up from the requests it embeds itself is known once those have run - $dependencies->hole(DonutRequest::resultOf($request)); - } - } - - public function render(ResourceObject $ro, DonutRendererInterface $storage): ResourceObject - { - // A page stored as its body was rendered when the donut was created - if ($this->body !== null) { - return $ro; - } - - $view = $storage->render($this->template); - $ro->view = $view; - - return $ro; - } - /** * Return the Last-Modified time to carry over when the refreshed content is * byte-identical to the content recorded with this donut, null otherwise. @@ -180,17 +106,13 @@ public function withContentState(ResourceObject $ro): self } return new self( - $this->template, - $this->headers, + $this->composition, $this->sMaxAge, $this->isPage, $lastModified, $this->hashContent((string) $ro->view), $this->templateExpiresAt, $this->storageTags, - $this->code, - $this->body, - $this->embeds, ); } @@ -202,17 +124,13 @@ public function withContentState(ResourceObject $ro): self public function withStorageState(int|null $ttl, array $tags): self { return new self( - $this->template, - $this->headers, + $this->composition, $this->sMaxAge, $this->isPage, $this->lastModified, $this->contentHash, $ttl !== null && $ttl > 0 ? time() + $ttl : null, $tags, - $this->code, - $this->body, - $this->embeds, ); } @@ -260,7 +178,9 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag } } - return new self($donutTemplate, $ro->headers, $sMaxAge, $isPage, code: $ro->code); + $ro->view = $storage->render($donutTemplate); + + return new self(new DonutTemplate($donutTemplate, $ro->headers, $ro->code), $sMaxAge, $isPage); } /** @return array */ @@ -335,6 +255,6 @@ private static function ofBody(ResourceObject $ro, array $embeds, Dependencies $ $dependencies->hole($invoked[$key] ?? DonutRequest::resultOf($embed->request)); } - return new self('', $ro->headers, $sMaxAge, $isPage, code: $ro->code, body: $body, embeds: $references); + return new self(new DonutBody($body, $references, $ro->headers, $ro->code), $sMaxAge, $isPage); } } diff --git a/tests/AppSurrogateKeyModuleTest.php b/tests/AppSurrogateKeyModuleTest.php index b8533063..6514a9f0 100644 --- a/tests/AppSurrogateKeyModuleTest.php +++ b/tests/AppSurrogateKeyModuleTest.php @@ -158,7 +158,7 @@ public function testInvalidatingTheKeyDropsEntriesSavedDirectly(): void $view->uri = new Uri('app://self/direct-view'); $view->view = 'view'; $this->storage->saveValue($ro, 0); - $this->storage->saveDonut($ro->uri, new ResourceDonut('template', [], null, false), null, ['direct']); + $this->storage->saveDonut($ro->uri, new ResourceDonut(new DonutTemplate('template', [], 200), null, false), null, ['direct']); $this->storage->saveDonutView($view, null, ['explicit']); $this->assertNotNull($this->storage->get($ro->uri)); $this->assertNotNull($this->storage->getDonut($ro->uri)); diff --git a/tests/DonutCacheTest.php b/tests/DonutCacheTest.php index 5da73cd6..37067217 100644 --- a/tests/DonutCacheTest.php +++ b/tests/DonutCacheTest.php @@ -37,7 +37,7 @@ protected function setUp(): void public function testGetState(): void { $headers = ['Content-Type' => 'application/xml;']; - $donut = new ResourceDonut('cmt=' . ResourceDonut::placeholder('page://self/html/comment'), $headers, null, true); + $donut = new ResourceDonut(new DonutTemplate('cmt=' . ResourceDonut::placeholder('page://self/html/comment'), $headers, 200), null, true); $blog = $this->resource->get('page://self/html/blog-posting'); $ro = $donut->refresh($this->resource, $blog, $this->dependencies($blog->uri)); $this->assertInstanceOf(ResourceObject::class, $ro); @@ -50,14 +50,14 @@ public function testGetUnchangedLastModified(): void $ro = $this->resource->get('page://self/html/comment'); $view = $ro->toString(); $ro->headers[Header::LAST_MODIFIED] = gmdate(Header::RFC7231, 1000); - $donut = (new ResourceDonut('tmpl', [], null, true))->withContentState($ro); + $donut = (new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, true))->withContentState($ro); // identical content carries over the recorded Last-Modified $this->assertSame(1000, $donut->getUnchangedLastModified($view)); // changed content advances Last-Modified (null lets the caller use the current time) $this->assertNull($donut->getUnchangedLastModified('changed content')); // a donut without recorded content state (e.g. putDonut) never carries over - $this->assertNull((new ResourceDonut('tmpl', [], null, false))->getUnchangedLastModified($view)); + $this->assertNull((new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, false))->getUnchangedLastModified($view)); } public function testContentStateUpdateKeepsLastModifiedMovingForward(): void @@ -65,7 +65,7 @@ public function testContentStateUpdateKeepsLastModifiedMovingForward(): void $ro = $this->resource->get('page://self/html/comment'); $view = $ro->toString(); $ro->headers[Header::LAST_MODIFIED] = gmdate(Header::RFC7231, 1000); - $donut = (new ResourceDonut('tmpl', [], null, true))->withContentState($ro); + $donut = (new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, true))->withContentState($ro); // A→B: the state recorded at refresh becomes the new comparison base $this->assertNull($donut->getUnchangedLastModified('changed content')); @@ -85,7 +85,7 @@ public function testZeroTtlRecordsNoTemplateExpiry(): void // for a positive value, so the entry is stored with no expiry and there is no // lifetime to carry. Recording time() here would report 0 remaining on the next // refresh and stop the content-state write of an entry that never expires. - $donut = (new ResourceDonut('tmpl', [], null, true))->withStorageState(0, ['tag']); + $donut = (new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, true))->withStorageState(0, ['tag']); $this->assertNull($donut->getRemainingStorageTtl()); $this->assertSame(['tag'], $donut->getStorageTags()); @@ -93,7 +93,7 @@ public function testZeroTtlRecordsNoTemplateExpiry(): void public function testStorageStatePreservesExplicitTtlAndTags(): void { - $donut = (new ResourceDonut('tmpl', [], null, true))->withStorageState(100, ['original-tag']); + $donut = (new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, true))->withStorageState(100, ['original-tag']); $remainingTtl = $donut->getRemainingStorageTtl(); $this->assertNotNull($remainingTtl); @@ -106,7 +106,7 @@ public function testExpiringTemplateReportsNoRemainingStorageTtl(): void { // A template entry whose recorded lifetime has just lapsed: the state must not be // re-saved with a fresh one, so the remaining time reads 0 rather than negative. - $donut = new ResourceDonut('tmpl', [], null, true, 1000, 'hash', time() - 5, ['original-tag']); + $donut = new ResourceDonut(new DonutTemplate('tmpl', [], 200), null, true, 1000, 'hash', time() - 5, ['original-tag']); $this->assertSame(0, $donut->getRemainingStorageTtl()); } @@ -114,7 +114,7 @@ public function testExpiringTemplateReportsNoRemainingStorageTtl(): void public function testDonutReplaysTheStatusCodeItWasStoredWith(): void { // The refresh path has no page state to read the code from, so the donut carries it. - $donut = new ResourceDonut('tmpl', [], null, true, null, null, null, [], 301); + $donut = new ResourceDonut(new DonutTemplate('tmpl', [], 301), null, true); $ro = $this->resource->get('page://self/html/comment'); $donut->refresh($this->resource, $ro, $this->dependencies($ro->uri)); diff --git a/tests/DonutRepositoryTest.php b/tests/DonutRepositoryTest.php index a1798441..1d46a710 100644 --- a/tests/DonutRepositoryTest.php +++ b/tests/DonutRepositoryTest.php @@ -479,7 +479,7 @@ public function testRefreshRecordsTheSkippedStateWriteWhenTheTemplateLifetimeHas // A template entry the pool still answers with, five seconds past the lifetime it // was stored with: re-saving the recomposed content would restart a lifetime the // template no longer has, so the write is recorded as skipped instead. - $donut = new ResourceDonut('cmt=' . ResourceDonut::placeholder('page://self/html/comment'), [], 30, true, null, null, time() - 5, ['lapsed-tag']); + $donut = new ResourceDonut(new DonutTemplate('cmt=' . ResourceDonut::placeholder('page://self/html/comment'), [], 200), 30, true, null, null, time() - 5, ['lapsed-tag']); $storage->saveDonut($this->uri, $donut, 30, ['lapsed-tag']); $logger->flush(); // drain the seed write: this test is about the refresh that follows, not the setup $page = $resource->get((string) $this->uri); diff --git a/tests/ResourceDonutTest.php b/tests/ResourceDonutTest.php index 8725b8ff..48d5ad99 100644 --- a/tests/ResourceDonutTest.php +++ b/tests/ResourceDonutTest.php @@ -49,7 +49,7 @@ protected function setUp(): void public function testRefreshResolvesTwoPlaceholdersOnTheSameLine(): void { $ro = $this->resource->newInstance('page://self/html/blog-posting-donut'); - $donut = new ResourceDonut('

' . ResourceDonut::placeholder('page://self/html/comment') . ResourceDonut::placeholder('page://self/html/like') . '

', [], null, false); + $donut = new ResourceDonut(new DonutTemplate('

' . ResourceDonut::placeholder('page://self/html/comment') . ResourceDonut::placeholder('page://self/html/like') . '

', [], 200), null, false); $refreshed = $donut->refresh($this->resource, $ro, $this->dependencies($ro->uri)); @@ -61,7 +61,7 @@ public function testRefreshResolvesTwoPlaceholdersOnTheSameLine(): void public function testRefreshResolvesPlaceholdersOnSeparateLines(): void { $ro = $this->resource->newInstance('page://self/html/blog-posting-donut'); - $donut = new ResourceDonut('

' . ResourceDonut::placeholder('page://self/html/comment') . "

\n

" . ResourceDonut::placeholder('page://self/html/like') . '

', [], null, false); + $donut = new ResourceDonut(new DonutTemplate('

' . ResourceDonut::placeholder('page://self/html/comment') . "

\n

" . ResourceDonut::placeholder('page://self/html/like') . '

', [], 200), null, false); $refreshed = $donut->refresh($this->resource, $ro, $this->dependencies($ro->uri)); @@ -90,7 +90,7 @@ public function testRefreshRoundTripsThePlaceholdersQueryValue(string $value): v { $ro = $this->resource->newInstance('page://self/html/blog-posting-donut'); $placeholder = ResourceDonut::placeholder('app://self/query-hole?' . http_build_query(['token' => $value])); - $donut = new ResourceDonut('

' . $placeholder . '

', [], null, false); + $donut = new ResourceDonut(new DonutTemplate('

' . $placeholder . '

', [], 200), null, false); $refreshed = $donut->refresh($this->resource, $ro, $this->dependencies($ro->uri)); @@ -106,7 +106,7 @@ public function testRefreshLeavesTheHoleScopeEvenWhenTheReFetchThrows(): void { $ro = $this->resource->newInstance('page://self/html/blog-posting-donut'); $uri = 'app://self/query-hole?token=x'; - $donut = new ResourceDonut('

' . ResourceDonut::placeholder($uri) . '

', [], null, false); + $donut = new ResourceDonut(new DonutTemplate('

' . ResourceDonut::placeholder($uri) . '

', [], 200), null, false); $throwingResource = new class implements ResourceInterface { public function newInstance($uri): ResourceObject { @@ -280,20 +280,14 @@ protected function configure(): void } } - /** - * The render must not be disturbed when nothing throws - `$ro->toString()` behaves - * exactly like the magic cast it replaced for the success path, only diverging on a - * Throwable. - */ - public function testCreateStillStoresTheTemplateWhenNothingThrows(): void + public function testCreateLeavesTheRenderedViewOnTheResponse(): void { $ro = $this->resource->newInstance('page://self/html/plain-donut-hole'); $ro->body = ['value' => 'plain']; - $donut = ResourceDonut::create($ro, new DonutRenderer(), $this->dependencies($ro->uri), null, false); - $rendered = $donut->render($ro, new DonutRenderer()); + ResourceDonut::create($ro, new DonutRenderer(), $this->dependencies($ro->uri), null, false); - $this->assertStringContainsString('plain-donut-hole:plain', (string) $rendered->view); + $this->assertStringContainsString('plain-donut-hole:plain', (string) $ro->view); } /** @@ -308,7 +302,7 @@ public function testRefreshRefusesToServeWhenAHoleThrows(): void { $ro = $this->resource->newInstance('page://self/html/blog-posting-donut'); $uri = 'app://self/throwing-hole'; - $donut = new ResourceDonut('

' . ResourceDonut::placeholder($uri) . '

', [], null, false); + $donut = new ResourceDonut(new DonutTemplate('

' . ResourceDonut::placeholder($uri) . '

', [], 200), null, false); try { $donut->refresh($this->resource, $ro, $this->dependencies($ro->uri));