From 19b74519771dc0696c81ec6a664878e930b1dca7 Mon Sep 17 00:00:00 2001 From: Akihito Koriyama Date: Sat, 28 Nov 2026 18:41:08 +0900 Subject: [PATCH 1/2] Consolidate internal URI template, command target, and body request helpers --- src/CacheDependencyCollector.php | 7 +- src/CacheableModule.php | 1 + src/CommandInterceptor.php | 19 +-- src/CommandTargets.php | 25 ++++ src/Dependencies.php | 3 +- src/DependsOnExpansion.php | 12 +- src/DependsOnTags.php | 21 +-- src/DependsOnTemplates.php | 131 +---------------- src/DonutCacheModule.php | 1 - src/QueryRepository.php | 7 +- src/QueryRepositoryModule.php | 2 +- src/RedisDsnProvider.php | 6 +- src/RefreshAnnotatedCommand.php | 28 ++-- src/RefreshTemplateValidator.php | 20 +-- src/ResourceBodyEvaluator.php | 19 ++- src/ResourceDonut.php | 32 ++-- src/ResourceStorage.php | 8 +- src/UriTemplates.php | 139 ++++++++++++++++++ tests/CacheDependencyCollectorTest.php | 4 +- tests/DonutMaterialDependencyTest.php | 4 +- tests/EmbeddedChildMaterializationTest.php | 2 +- ...Test.php => ResourceBodyEvaluatorTest.php} | 8 +- 22 files changed, 252 insertions(+), 247 deletions(-) create mode 100644 src/CommandTargets.php create mode 100644 src/UriTemplates.php rename tests/{DependsOnTagsTest.php => ResourceBodyEvaluatorTest.php} (87%) diff --git a/src/CacheDependencyCollector.php b/src/CacheDependencyCollector.php index 93fa63f0..bb7c4dc1 100644 --- a/src/CacheDependencyCollector.php +++ b/src/CacheDependencyCollector.php @@ -20,6 +20,7 @@ public function __construct( private CacheDependencyInterface $cacheDependency, private CacheTags $cacheTags, private CacheIdentityFactory $identityFactory, + private ResourceBodyEvaluator $bodyEvaluator, #[CacheLog] private SemanticLoggerInterface $logger, ) { @@ -28,7 +29,7 @@ public function __construct( /** @param TagSet $keys the keys the response has before anything is collected */ public function begin(TagSet $keys): Dependencies { - return new Dependencies($keys, $this->dependsOnTags, $this->resourceParamSources, $this->cacheTags, $this->identityFactory); + return new Dependencies($keys, $this->dependsOnTags, $this->resourceParamSources, $this->cacheTags, $this->identityFactory, $this->bodyEvaluator); } /** @@ -40,7 +41,7 @@ public function collect(ResourceObject $ro): void { $dependencies = $this->begin(new TagSet()); $this->declared($ro); - foreach ($this->dependsOnTags->requests($ro) as $request) { + foreach ($this->bodyEvaluator->requests($ro) as $request) { $this->materialize($request); $child = $request->resourceObject; $this->depends($ro, $child, $dependencies->read($child)); @@ -51,7 +52,7 @@ public function collect(ResourceObject $ro): void public function materials(ResourceObject $ro, Dependencies $dependencies): void { $this->declared($ro); - foreach ($this->dependsOnTags->requests($ro) as $request) { + foreach ($this->bodyEvaluator->requests($ro) as $request) { $child = $request->resourceObject; $this->depends($ro, $child, $dependencies->embedded($child)); } diff --git a/src/CacheableModule.php b/src/CacheableModule.php index c018e876..bf41d711 100644 --- a/src/CacheableModule.php +++ b/src/CacheableModule.php @@ -36,6 +36,7 @@ protected function configure(): void $this->bind(ConditionalRequest::class); $this->bind(ConditionalResponseInterface::class)->to(ConditionalResponse::class); $this->bind(DeclaredCacheControl::class)->in(Scope::SINGLETON); + $this->bind(UriTemplates::class); $this->bind(RefreshTemplateValidator::class)->in(Scope::SINGLETON); $this->bind(CacheableClassMatcher::class); $this->install(new StorageExpiryModule(60, 60 * 60, 60 * 60 * 24)); diff --git a/src/CommandInterceptor.php b/src/CommandInterceptor.php index aa5da22c..16567da5 100644 --- a/src/CommandInterceptor.php +++ b/src/CommandInterceptor.php @@ -14,14 +14,11 @@ use BEAR\Resource\InvokerInterface; use BEAR\Resource\Request; use BEAR\Resource\ResourceObject; -use BEAR\Resource\Uri; use Override; use Ray\Aop\MethodInterceptor; use Ray\Aop\MethodInvocation; use ReflectionClass; -use function array_column; -use function array_merge; use function method_exists; /** @@ -74,30 +71,20 @@ private function purgeAndRefresh(MethodInvocation $invocation, ResourceObject $r { $stored = $this->isStored($invocation); $getQuery = $sent === null ? null : $this->getQuery($invocation, $sent, $stored); - $declared = $this->command->declared($invocation, $ro); + $targets = $this->command->declared($invocation, $ro); $own = $sent === null || $getQuery === null ? [] : $this->commandQuery->ownUris($sent, $getQuery); - $failure = $this->purge([...$own, ...array_merge(...array_column($declared, 0))]); + $failure = $this->purge([...$own, ...$targets->purge]); if ($stored && $sent !== null && $getQuery !== null) { $this->rebuild($invocation, $sent, $getQuery); } - $this->refreshDeclared($declared); + $this->command->refresh($targets->refresh); if ($failure !== null) { throw $failure; } } - /** @param list, bool}> $declared each declaration's URIs, and whether it is a #[Refresh] */ - private function refreshDeclared(array $declared): void - { - foreach ($declared as [$named, $refresh]) { - if ($refresh) { - $this->command->refresh($named); - } - } - } - /** The resource the write was sent to, cloned with its URI before the handler runs; none without a URI or an onGet() */ private function sent(ResourceObject $target): ResourceObject|null { diff --git a/src/CommandTargets.php b/src/CommandTargets.php new file mode 100644 index 00000000..f6e8b211 --- /dev/null +++ b/src/CommandTargets.php @@ -0,0 +1,25 @@ + $purge all declared URIs to purge, in declaration order + * @param list $refresh the #[Refresh] URIs to read again after every purge has run + */ + public function __construct( + public array $purge, + public array $refresh, + ) { + } +} diff --git a/src/Dependencies.php b/src/Dependencies.php index 7ec352ff..7748cb65 100644 --- a/src/Dependencies.php +++ b/src/Dependencies.php @@ -25,6 +25,7 @@ public function __construct( private readonly ResourceParamSources $resourceParamSources, private readonly CacheTags $cacheTags, private readonly CacheIdentityFactory $identityFactory, + private readonly ResourceBodyEvaluator $bodyEvaluator, ) { } @@ -109,7 +110,7 @@ private function ofResult(ResourceObject $ro, Closure $embedded): TagSet|null private function passedUp(ResourceObject $ro, Closure $embedded): TagSet { $tags = new TagSet(); - foreach ($this->dependsOnTags->requests($ro) as $request) { + foreach ($this->bodyEvaluator->requests($ro) as $request) { if ($embedded($request->resourceObject)) { $tags = $tags->merge($this->cacheTags->tags($request->resourceObject)); } diff --git a/src/DependsOnExpansion.php b/src/DependsOnExpansion.php index f5052ec9..dff52ddd 100644 --- a/src/DependsOnExpansion.php +++ b/src/DependsOnExpansion.php @@ -36,7 +36,7 @@ */ public function __construct( private UriTagInterface $uriTag, - private DependsOnTemplates $templates, + private UriTemplates $uriTemplates, private string $source, private array $top, private array $arguments, @@ -57,8 +57,8 @@ public function __construct( public function tags(DependsOn $dependsOn, array $rows): array { $template = $dependsOn->uri; - $variables = $this->templates->variables($template); - $exploded = $this->templates->explodedQueryNames($template); + $variables = $this->uriTemplates->variables($template); + $exploded = $this->uriTemplates->explodedQueryNames($template); $fromRows = array_map(fn (array $row): array => $this->expandable($variables, $exploded, $row), $rows); $carried = $dependsOn->key === null ? [] : array_merge(...$fromRows); $outside = array_diff_key($this->top, $carried); @@ -67,7 +67,7 @@ public function tags(DependsOn $dependsOn, array $rows): array if ($rows === []) { $named = $dependsOn->key === null && $this->missing($variables, $fallback, $outside + $given) === null; - return $named ? $this->templates->tags($this->uriTag, $template, $fallback) : []; + return $named ? $this->uriTemplates->tags($this->uriTag, $template, $fallback) : []; } $tags = []; @@ -82,11 +82,11 @@ public function tags(DependsOn $dependsOn, array $rows): array } $expanded = true; - $tags = [...$tags, ...$this->templates->tags($this->uriTag, $template, $values)]; + $tags = [...$tags, ...$this->uriTemplates->tags($this->uriTag, $template, $values)]; } if (! $expanded) { - throw new DependsOnNotExpandable($this->source, $this->templates->declaration($template), $missing); + throw new DependsOnNotExpandable($this->source, sprintf("#[DependsOn(uri: '%s')]", $template), $missing); } return $tags; diff --git a/src/DependsOnTags.php b/src/DependsOnTags.php index 4843b1f7..7b0e458d 100644 --- a/src/DependsOnTags.php +++ b/src/DependsOnTags.php @@ -5,9 +5,7 @@ namespace BEAR\QueryRepository; use BEAR\RepositoryModule\Annotation\DependsOn; -use BEAR\Resource\AbstractRequest; use BEAR\Resource\ResourceObject; -use Generator; use function array_keys; use function is_array; @@ -25,25 +23,10 @@ public function __construct( private DependsOnRows $rows, private CacheIdentityFactory $identityFactory, private DependsOnTemplates $templates, + private UriTemplates $uriTemplates, ) { } - /** - * Enumerate only immediate values of the array-cast body, in order and with duplicates. - * Do not execute requests, descend into children, or consume Traversable bodies. - * - * @return Generator - */ - public function requests(ResourceObject $ro): Generator - { - /** @var mixed $body */ - foreach ((array) $ro->body as $body) { - if ($body instanceof AbstractRequest) { - yield $body; - } - } - } - /** @return TagSet|null what onGet() declares; null when it declares nothing */ public function declared(ResourceObject $ro): TagSet|null { @@ -79,7 +62,7 @@ private function fromResult(ResourceObject $ro, array $declarations): array } $source = sprintf('%s onGet()', (string) $ro->uri); - $expansion = new DependsOnExpansion($this->uriTag, $this->templates, $source, is_array($ro->body) ? $ro->body : [], $arguments, $onGet->names(), array_keys($onGet->bound())); + $expansion = new DependsOnExpansion($this->uriTag, $this->uriTemplates, $source, is_array($ro->body) ? $ro->body : [], $arguments, $onGet->names(), array_keys($onGet->bound())); $tags = []; foreach ($declarations as $dependsOn) { $tags = [...$tags, ...$expansion->tags($dependsOn, $this->rows->of($ro, $dependsOn->key))]; diff --git a/src/DependsOnTemplates.php b/src/DependsOnTemplates.php index 3f45a9a0..722fd27e 100644 --- a/src/DependsOnTemplates.php +++ b/src/DependsOnTemplates.php @@ -6,29 +6,13 @@ use BEAR\RepositoryModule\Annotation\DependsOn; use BEAR\Resource\ResourceObject; -use BEAR\Resource\Uri; use ReflectionClass; -use Stringable; -use function array_is_list; -use function array_unique; use function array_values; -use function explode; -use function is_array; -use function preg_match_all; -use function preg_replace; use function serialize; -use function sprintf; -use function str_ends_with; -use function strpos; -use function substr; -use function uri_template; - -use const PREG_OFFSET_CAPTURE; -use const PREG_SET_ORDER; /** - * The URI templates #[DependsOn] declares, and the values #[DependsOn], #[Purge] and #[Refresh] expand theirs with + * The #[DependsOn] declarations on a resource's onGet(), cached per class * * @internal */ @@ -54,117 +38,4 @@ public function ofOnGet(ResourceObject $ro): array return $this->onGet[$ro::class] = array_values($declarations); } - - /** - * @param array $values - * - * @return list the tag of each URI the template expands to, one per element of a list given to an exploded query variable - */ - public function tags(UriTagInterface $uriTag, string $template, array $values): array - { - $tags = []; - foreach ($this->variableSets($template, $values) as $variables) { - $tag = $this->tag($uriTag, $template, $variables); - if ($tag !== null) { - $tags[] = $tag; - } - } - - return $tags; - } - - /** - * One set per element of each list given to an exploded query variable (`{?id*}`, `?id={ids*}`), the product when there are - * several. A null element names no URI and is skipped: the bare URI's group tag reaches every variant. - * - * @param array $values - * - * @return list> - */ - public function variableSets(string $template, array $values): array - { - $sets = [$values]; - foreach ($this->explodedQueryNames($template) as $name) { - if (! isset($values[$name]) || ! is_array($values[$name]) || ! array_is_list($values[$name])) { - continue; - } - - $expanded = []; - foreach ($sets as $set) { - /** @psalm-suppress MixedAssignment */ - foreach ($values[$name] as $value) { - if ($value !== null) { - $expanded[] = [$name => $value] + $set; - } - } - } - - $sets = $expanded; - } - - return $sets; - } - - /** - * @param array $values each variable of the template holds a scalar, a Stringable or null: {@see DependsOnExpansion} - * - * @return string|null the tag of the URI the template expands to; null when a variable is null, which names no URI - */ - public function tag(UriTagInterface $uriTag, string $template, array $values): string|null - { - $variables = []; - foreach ($this->variables($template) as $variable) { - /** @var scalar|Stringable|null $value */ - $value = $values[$variable]; - if ($value === null) { - return null; - } - - $variables[$variable] = $value instanceof Stringable ? (string) $value : $value; - } - - return $uriTag(new Uri(uri_template($template, $variables))); - } - - /** @return list the RFC 6570 variable names in the template */ - public function variables(string $template): array - { - preg_match_all('/\{[+#.\/;?&]?([^}]+)\}/', $template, $matches); - $variables = []; - foreach ($matches[1] as $expression) { - foreach (explode(',', $expression) as $spec) { - $variables[] = (string) preg_replace('/(\*|:\d+)$/', '', $spec); - } - } - - return $variables; - } - - public function declaration(string $template): string - { - return sprintf("#[DependsOn(uri: '%s')]", $template); - } - - /** @return list the query variables a list is given to one element at a time (`{?id*}`, `?id={ids*}`) */ - public function explodedQueryNames(string $template): array - { - preg_match_all('/\{([+#.\/;?&]?)([^}]+)\}/', $template, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); - $queryStart = strpos($template, '?'); - $names = []; - foreach ($matches as $match) { - $operator = $match[1][0]; - $inQuery = $operator === '?' || $operator === '&' || ($operator === '' && $queryStart !== false && $match[0][1] > $queryStart); - if (! $inQuery) { - continue; - } - - foreach (explode(',', $match[2][0]) as $varSpec) { - if (str_ends_with($varSpec, '*')) { - $names[] = substr($varSpec, 0, -1); - } - } - } - - return array_values(array_unique($names)); - } } diff --git a/src/DonutCacheModule.php b/src/DonutCacheModule.php index dbf702ab..c69d2f9c 100644 --- a/src/DonutCacheModule.php +++ b/src/DonutCacheModule.php @@ -50,7 +50,6 @@ protected function configure(): void private function installAopClassModule(): void { - $this->bind(DonutRepository::class)->in(Scope::SINGLETON); $this->bind(DonutRendererInterface::class)->to(DonutRenderer::class); $this->bindPriorityInterceptor( $this->matcher->annotatedWith(CacheableResponse::class), diff --git a/src/QueryRepository.php b/src/QueryRepository.php index 9145b014..e8921a41 100644 --- a/src/QueryRepository.php +++ b/src/QueryRepository.php @@ -74,7 +74,7 @@ public function put(ResourceObject $ro) private function doPut(ResourceObject $ro): bool { if ($ro->code === 200) { - $this->setCacheDependency($ro); + $this->dependencyCollector->collect($ro); } $this->cacheTags->tagHeader($ro); @@ -200,11 +200,6 @@ private function cachePolicy(ResourceObject $ro, Cacheable $cacheable, int $ttl) return new CachePolicyContext($uri, $cacheable->expiry, null, null, $ttl); } - private function setCacheDependency(ResourceObject $ro): void - { - $this->dependencyCollector->collect($ro); - } - /** * {@inheritDoc} */ diff --git a/src/QueryRepositoryModule.php b/src/QueryRepositoryModule.php index 6bb8849a..95a6e584 100644 --- a/src/QueryRepositoryModule.php +++ b/src/QueryRepositoryModule.php @@ -85,7 +85,7 @@ protected function configure(): void $this->bind(CommandQuery::class); $this->bind(UnsafeMethodMatcher::class); // Server context for thread safety (Swoole, RoadRunner, etc.) - $this->bind(ServerContextInterface::class)->to(GlobalServerContext::class)->in(Scope::SINGLETON); + $this->bind(ServerContextInterface::class)->to(GlobalServerContext::class); $this->bind(ReplacedEntry::class); // #[Cacheable] $this->install(new CacheableModule()); diff --git a/src/RedisDsnProvider.php b/src/RedisDsnProvider.php index c8866d4c..8cb1c909 100644 --- a/src/RedisDsnProvider.php +++ b/src/RedisDsnProvider.php @@ -23,12 +23,12 @@ final readonly class RedisDsnProvider implements ProviderInterface { /** - * @param string $dns Redis DSN + * @param string $dsn Redis DSN * @param array|null> $options Redis DSN Options */ public function __construct( #[RedisDsn] - private string $dns, + private string $dsn, #[RedisDsnOptions] private array $options, ) { @@ -40,7 +40,7 @@ public function get(): Redis|RedisArray|RedisCluster|ClientInterface|Relay|Relay // Connect on first use: the pool is built at boot, where a compile has no store to reach. // A `lazy` in the options or the DSN query still wins. /** @var Redis|RedisArray|RedisCluster|ClientInterface|Relay|RelayCluster $connection */ - $connection = RedisAdapter::createConnection($this->dns, $this->options + ['lazy' => true]); + $connection = RedisAdapter::createConnection($this->dsn, $this->options + ['lazy' => true]); return $connection; } diff --git a/src/RefreshAnnotatedCommand.php b/src/RefreshAnnotatedCommand.php index 6a2057ef..9304a8a9 100644 --- a/src/RefreshAnnotatedCommand.php +++ b/src/RefreshAnnotatedCommand.php @@ -36,43 +36,45 @@ public function __construct( private ResourceInterface $resource, private CacheIdentityFactory $identityFactory, - private DependsOnTemplates $templates, + private UriTemplates $uriTemplates, private UriFactory $uriFactory, ) { } /** - * The URIs each #[Purge]/#[Refresh] of the method names, in declaration order, and whether it is a #[Refresh]; then the URI - * each #[Link(rel: 'collection')] on the resource's onGet() names, purged only; an href that does not expand to a resource URI is - * skipped + * The URIs each #[Purge]/#[Refresh] of the method names, in declaration order, then the URI each + * #[Link(rel: 'collection')] on the resource's onGet() names (purged only); an href that does not expand + * to a resource URI is skipped * * @param MethodInvocation $invocation - * - * @return list, bool}> */ - public function declared(MethodInvocation $invocation, ResourceObject $ro): array + public function declared(MethodInvocation $invocation, ResourceObject $ro): CommandTargets { /** @var AbstractUri|null $uri a resource object taken from the injector has none */ $uri = $ro->uri; $query = $uri === null ? $this->passedArguments($invocation) : $uri->query; - $declared = []; + $purge = []; + $refresh = []; foreach ($invocation->getMethod()->getAnnotations() as $annotation) { if (! $annotation instanceof Purge && ! $annotation instanceof Refresh) { continue; } $uris = array_map(static fn (string $uri): Uri => new Uri($uri), $this->uris($ro, $annotation->uri, $query)); - $declared[] = [$uris, $annotation instanceof Refresh]; + $purge = [...$purge, ...$uris]; + if ($annotation instanceof Refresh) { + $refresh = [...$refresh, ...$uris]; + } } $target = $invocation->getThis(); if ($target instanceof ResourceObject) { foreach ($this->collections($target) as $href) { - $declared[] = [$this->resourceUris($this->uris($ro, $href, $query)), false]; + $purge = [...$purge, ...$this->resourceUris($this->uris($ro, $href, $query))]; } } - return $declared; + return new CommandTargets($purge, $refresh); } /** @@ -112,7 +114,7 @@ private function passedArguments(MethodInvocation $invocation): array } /** - * One URI per element of each list given to an exploded query variable: {@see DependsOnTemplates::variableSets()} + * One URI per element of each list given to an exploded query variable: {@see UriTemplates::variableSets()} * * @param array $query * @@ -122,7 +124,7 @@ private function uris(ResourceObject $ro, string $template, array $query): array { $body = is_array($ro->body) ? $ro->body : []; $uris = []; - foreach ($this->templates->variableSets($template, $body + $query) as $variables) { + foreach ($this->uriTemplates->variableSets($template, $body + $query) as $variables) { $uris[] = uri_template($template, $variables); } diff --git a/src/RefreshTemplateValidator.php b/src/RefreshTemplateValidator.php index 4f625e88..4114b4f1 100644 --- a/src/RefreshTemplateValidator.php +++ b/src/RefreshTemplateValidator.php @@ -15,13 +15,10 @@ use function array_fill_keys; use function array_key_exists; -use function explode; use function is_callable; use function parse_str; use function parse_url; use function preg_match; -use function preg_match_all; -use function preg_replace; use function sprintf; use function strrchr; use function substr; @@ -43,6 +40,7 @@ public function __construct( private readonly ResourceInterface $resource, private readonly NamedParamMetasInterface $namedParamMetas, private readonly CacheIdentityFactory $identityFactory, + private readonly UriTemplates $uriTemplates, ) { } @@ -76,7 +74,7 @@ private function validate(string $methodName, Purge|Refresh $annotation): void return; } - $uri = uri_template($template, array_fill_keys($this->variableNames($template), '0')); + $uri = uri_template($template, array_fill_keys($this->uriTemplates->variables($template), '0')); try { $destination = $this->resource->newInstance($uri); } catch (BadRequestException) { @@ -107,18 +105,4 @@ private function validate(string $methodName, Purge|Refresh $annotation): void throw new TemplateLacksRequiredParameter($methodName, sprintf("#[%s(uri: '%s')]", $attribute, $template), $missing); } - - /** @return list */ - private function variableNames(string $template): array - { - preg_match_all('/\{[+#.\/;?&]?([^}]+)\}/', $template, $matches); - $names = []; - foreach ($matches[1] as $varList) { - foreach (explode(',', $varList) as $var) { - $names[] = (string) preg_replace('/(:\d+|\*)$/', '', $var); - } - } - - return $names; - } } diff --git a/src/ResourceBodyEvaluator.php b/src/ResourceBodyEvaluator.php index 5926016b..fa067302 100644 --- a/src/ResourceBodyEvaluator.php +++ b/src/ResourceBodyEvaluator.php @@ -7,6 +7,7 @@ use BEAR\Resource\AbstractRequest; use BEAR\Resource\RequestInterface; use BEAR\Resource\ResourceObject; +use Generator; use function assert; use function is_array; @@ -21,6 +22,22 @@ */ final class ResourceBodyEvaluator { + /** + * Enumerate only immediate values of the array-cast body, in order and with duplicates. + * Do not execute requests, descend into children, or consume Traversable bodies. + * + * @return Generator + */ + public function requests(ResourceObject $ro): Generator + { + /** @var mixed $body */ + foreach ((array) $ro->body as $body) { + if ($body instanceof AbstractRequest) { + yield $body; + } + } + } + public function __invoke(mixed $body): mixed { if (! is_array($body)) { @@ -73,7 +90,7 @@ private function copyForStore(mixed $item): mixed /** * Materialize an embedded request as a copy the live response graph cannot mutate * - * The child was already run before the store (QueryRepository::setCacheDependency() + * The child was already run before the store (CacheDependencyCollector::collect() * casts it, the renderer reads it), and AbstractRequest memoizes that single * execution. Its __invoke() ignores the memo and runs the request again, which for a * non-idempotent child would leave a type: "view" entry holding a body and a view diff --git a/src/ResourceDonut.php b/src/ResourceDonut.php index c551b805..a43adc0f 100644 --- a/src/ResourceDonut.php +++ b/src/ResourceDonut.php @@ -73,17 +73,17 @@ public function __construct( } /** Answers the page again from what was stored. Whatever fails on the way degrades the hit to a fresh run of the page. */ - public function refresh(ResourceInterface $resource, ResourceObject $ro, Dependencies $etags): ResourceObject + public function refresh(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): ResourceObject { try { if ($this->body === null) { - $view = $this->compose($resource, $etags); + $view = $this->compose($resource, $dependencies); $ro->headers = $this->headers; $ro->view = $view; } if ($this->body !== null) { - $this->renderBody($this->body, $resource, $ro, $etags); + $this->renderBody($this->body, $resource, $ro, $dependencies); } $ro->code = $this->code; @@ -91,7 +91,7 @@ public function refresh(ResourceInterface $resource, ResourceObject $ro, Depende // $this->headers lacks the group tag; add the stored tags. (new TagSet($this->getStorageTags()))->addTo($ro); - $etags->addTo($ro); + $dependencies->addTo($ro); } catch (Throwable $e) { throw new CacheStoreException(previous: $e); } @@ -100,14 +100,14 @@ public function refresh(ResourceInterface $resource, ResourceObject $ro, Depende } /** The template with the view of each embedded request, read again, in its place */ - private function compose(ResourceInterface $resource, Dependencies $etags): string|null + private function compose(ResourceInterface $resource, Dependencies $dependencies): string|null { - return preg_replace_callback(self::URI_REGEX, static function (array $matches) use ($resource, $etags): string { + 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(); - $etags->hole($ro); + $dependencies->hole($ro); return (string) $ro->view; }, $this->template); @@ -118,7 +118,7 @@ private function compose(ResourceInterface $resource, Dependencies $etags): stri * * @param array $body */ - private function renderBody(array $body, ResourceInterface $resource, ResourceObject $ro, Dependencies $etags): void + private function renderBody(array $body, ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void { $requests = []; foreach ($this->embeds as $key => $reference) { @@ -134,7 +134,7 @@ private function renderBody(array $body, ResourceInterface $resource, ResourceOb $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 - $etags->hole(DonutRequest::resultOf($request)); + $dependencies->hole(DonutRequest::resultOf($request)); } } @@ -239,13 +239,13 @@ private function hashContent(string $view): string * Renders via `toString()`, not `(string) $ro`, which swallows a render failure into * an `E_USER_WARNING` and `''` - that would store an empty template for every later visitor. */ - public static function create(ResourceObject $ro, DonutRendererInterface $storage, Dependencies $etags, int|null $sMaxAge, bool $isPage): self + public static function create(ResourceObject $ro, DonutRendererInterface $storage, Dependencies $dependencies, int|null $sMaxAge, bool $isPage): self { // A resource with nothing to return leaves its body null - a 204 typically does, while // an #[Embed] would have made it an array - and a null body holds no embedded request // to wrap. It is composed as an empty one rather than refused. assert(is_iterable($ro->body) || $ro->body === null); - $embeds = self::wrapEmbeds($ro, $storage, $etags); + $embeds = self::wrapEmbeds($ro, $storage, $dependencies); try { $donutTemplate = $ro->toString(); } catch (Throwable $e) { @@ -256,7 +256,7 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag foreach ($embeds as $embed) { if ($embed->isEncoded && is_array($ro->body)) { - return self::ofBody($ro, $embeds, $etags, $sMaxAge, $isPage); + return self::ofBody($ro, $embeds, $dependencies, $sMaxAge, $isPage); } } @@ -264,7 +264,7 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag } /** @return array */ - private static function wrapEmbeds(ResourceObject $ro, DonutRendererInterface $storage, Dependencies $etags): array + private static function wrapEmbeds(ResourceObject $ro, DonutRendererInterface $storage, Dependencies $dependencies): array { if (! is_iterable($ro->body)) { return []; @@ -281,7 +281,7 @@ private static function wrapEmbeds(ResourceObject $ro, DonutRendererInterface $s } if ($maybeRequest instanceof AbstractRequest) { - $maybeRequest = $embeds[$key] = new DonutRequest($maybeRequest, $storage, $etags); + $maybeRequest = $embeds[$key] = new DonutRequest($maybeRequest, $storage, $dependencies); } } @@ -306,7 +306,7 @@ private static function restoreEmbeds(ResourceObject $ro, array $embeds): void * * @param array $embeds */ - private static function ofBody(ResourceObject $ro, array $embeds, Dependencies $etags, int|null $sMaxAge, bool $isPage): self + private static function ofBody(ResourceObject $ro, array $embeds, Dependencies $dependencies, int|null $sMaxAge, bool $isPage): self { assert(is_array($ro->body)); $body = $ro->body; @@ -332,7 +332,7 @@ private static function ofBody(ResourceObject $ro, array $embeds, Dependencies $ $ro->toString(); foreach ($embeds as $key => $embed) { // After rendering: what a request passes up from the requests it embeds itself is known once those have run - $etags->hole($invoked[$key] ?? DonutRequest::resultOf($embed->request)); + $dependencies->hole($invoked[$key] ?? DonutRequest::resultOf($embed->request)); } return new self('', $ro->headers, $sMaxAge, $isPage, code: $ro->code, body: $body, embeds: $references); diff --git a/src/ResourceStorage.php b/src/ResourceStorage.php index 1f2d2e0e..2f84507d 100644 --- a/src/ResourceStorage.php +++ b/src/ResourceStorage.php @@ -56,7 +56,7 @@ final class ResourceStorage implements ResourceStorageInterface private const KEY_RO = 'ro-'; /** - * Resource static cache prifix + * Resource static cache prefix */ private const KEY_DONUT = 'donut-'; @@ -82,11 +82,11 @@ public function __construct( private ResourceBodyEvaluator $evaluateBody, private EntityTags $entityTags, ) { - $this->initializePools($roPoolProvider); + $this->initializePool($roPoolProvider); } /** @param ProviderInterface $roPoolProvider */ - private function initializePools(ProviderInterface $roPoolProvider): void + private function initializePool(ProviderInterface $roPoolProvider): void { $this->roPoolProvider = $roPoolProvider; $this->roPool = $roPoolProvider->get(); @@ -380,6 +380,6 @@ public function __unserialize(array $data): void $this->cacheTags = $data['cacheTags']; $this->evaluateBody = $data['evaluateBody']; $this->entityTags = $data['entityTags']; - $this->initializePools($data['roProvider']); + $this->initializePool($data['roProvider']); } } diff --git a/src/UriTemplates.php b/src/UriTemplates.php new file mode 100644 index 00000000..48fe2201 --- /dev/null +++ b/src/UriTemplates.php @@ -0,0 +1,139 @@ + $values + * + * @return list the tag of each URI the template expands to, one per element of a list given to an exploded query variable + */ + public function tags(UriTagInterface $uriTag, string $template, array $values): array + { + $tags = []; + foreach ($this->variableSets($template, $values) as $variables) { + $tag = $this->tag($uriTag, $template, $variables); + if ($tag !== null) { + $tags[] = $tag; + } + } + + return $tags; + } + + /** + * One set per element of each list given to an exploded query variable (`{?id*}`, `?id={ids*}`), the product when there are + * several. A null element names no URI and is skipped: the bare URI's group tag reaches every variant. + * + * @param array $values + * + * @return list> + */ + public function variableSets(string $template, array $values): array + { + $sets = [$values]; + foreach ($this->explodedQueryNames($template) as $name) { + if (! isset($values[$name]) || ! is_array($values[$name]) || ! array_is_list($values[$name])) { + continue; + } + + $expanded = []; + foreach ($sets as $set) { + /** @psalm-suppress MixedAssignment */ + foreach ($values[$name] as $value) { + if ($value !== null) { + $expanded[] = [$name => $value] + $set; + } + } + } + + $sets = $expanded; + } + + return $sets; + } + + /** + * @param array $values each variable of the template holds a scalar, a Stringable or null: {@see DependsOnExpansion} + * + * @return string|null the tag of the URI the template expands to; null when a variable is null, which names no URI + */ + public function tag(UriTagInterface $uriTag, string $template, array $values): string|null + { + $variables = []; + foreach ($this->variables($template) as $variable) { + /** @var scalar|Stringable|null $value */ + $value = $values[$variable]; + if ($value === null) { + return null; + } + + $variables[$variable] = $value instanceof Stringable ? (string) $value : $value; + } + + return $uriTag(new Uri(uri_template($template, $variables))); + } + + /** @return list the RFC 6570 variable names in the template */ + public function variables(string $template): array + { + preg_match_all('/\{[+#.\/;?&]?([^}]+)\}/', $template, $matches); + $variables = []; + foreach ($matches[1] as $expression) { + foreach (explode(',', $expression) as $spec) { + $variables[] = (string) preg_replace('/(\*|:\d+)$/', '', $spec); + } + } + + return $variables; + } + + /** @return list the query variables a list is given to one element at a time (`{?id*}`, `?id={ids*}`) */ + public function explodedQueryNames(string $template): array + { + preg_match_all('/\{([+#.\/;?&]?)([^}]+)\}/', $template, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); + $queryStart = strpos($template, '?'); + $names = []; + foreach ($matches as $match) { + $operator = $match[1][0]; + $inQuery = $operator === '?' || $operator === '&' || ($operator === '' && $queryStart !== false && $match[0][1] > $queryStart); + if (! $inQuery) { + continue; + } + + foreach (explode(',', $match[2][0]) as $varSpec) { + if (str_ends_with($varSpec, '*')) { + $names[] = substr($varSpec, 0, -1); + } + } + } + + return array_values(array_unique($names)); + } +} diff --git a/tests/CacheDependencyCollectorTest.php b/tests/CacheDependencyCollectorTest.php index a39638af..a099eb4b 100644 --- a/tests/CacheDependencyCollectorTest.php +++ b/tests/CacheDependencyCollectorTest.php @@ -50,9 +50,9 @@ public function invoke(AbstractRequest $request): ResourceObject }; $parent->uri = new Uri('app://self/parent'); $parent->body = ['scalar', $child, [$request], $request]; - $tags = $this->injector->getInstance(DependsOnTags::class); + $evaluator = $this->injector->getInstance(ResourceBodyEvaluator::class); - $this->assertSame([$request], iterator_to_array($tags->requests($parent))); + $this->assertSame([$request], iterator_to_array($evaluator->requests($parent))); $this->assertSame(0, $invoker->calls); $this->injector->getInstance(CacheDependencyCollector::class)->collect($parent); $this->assertSame(1, $invoker->calls); diff --git a/tests/DonutMaterialDependencyTest.php b/tests/DonutMaterialDependencyTest.php index ae4f36b9..00012b21 100644 --- a/tests/DonutMaterialDependencyTest.php +++ b/tests/DonutMaterialDependencyTest.php @@ -424,7 +424,7 @@ public function fromAssoc(string $uriTemplate, array $assoc): string $storage = $injector->getInstance(ResourceStorageInterface::class); $logger = $injector->getInstance(SemanticLoggerInterface::class, CacheLog::class); $sources = new ResourceParamSources($resource, $storage, $cacheTags, $identityFactory); - $dependsOnTags = new DependsOnTags($uriTag, new DependsOnRows(), $identityFactory, $this->injector->getInstance(DependsOnTemplates::class)); + $dependsOnTags = new DependsOnTags($uriTag, new DependsOnRows(), $identityFactory, $this->injector->getInstance(DependsOnTemplates::class), new UriTemplates()); return [ $resource, @@ -449,7 +449,7 @@ public function get(): DonutRendererInterface new DeclaredCacheControl(), new ReplacedEntry($logger, $storage, $uriTag), $cacheTags, - new CacheDependencyCollector($dependsOnTags, $sources, new CacheDependency($cacheTags, $logger), $cacheTags, $identityFactory, $logger), + new CacheDependencyCollector($dependsOnTags, $sources, new CacheDependency($cacheTags, $logger), $cacheTags, $identityFactory, new ResourceBodyEvaluator(), $logger), ), ]; } diff --git a/tests/EmbeddedChildMaterializationTest.php b/tests/EmbeddedChildMaterializationTest.php index 04b070a1..5aa7f37e 100644 --- a/tests/EmbeddedChildMaterializationTest.php +++ b/tests/EmbeddedChildMaterializationTest.php @@ -38,7 +38,7 @@ protected function setUp(): void /** * One cold parent GET runs the embedded child exactly once * - * The child is materialized by setCacheDependency() and again by the storage, + * The child is materialized by CacheDependencyCollector::collect() and again by the storage, * and only AbstractRequest's memoized result makes the second pass free. */ public function testColdGetExecutesEmbeddedChildOnce(): void diff --git a/tests/DependsOnTagsTest.php b/tests/ResourceBodyEvaluatorTest.php similarity index 87% rename from tests/DependsOnTagsTest.php rename to tests/ResourceBodyEvaluatorTest.php index 79913bad..56ce6d8d 100644 --- a/tests/DependsOnTagsTest.php +++ b/tests/ResourceBodyEvaluatorTest.php @@ -16,7 +16,7 @@ use function iterator_to_array; -class DependsOnTagsTest extends TestCase +class ResourceBodyEvaluatorTest extends TestCase { private InjectorInterface $injector; @@ -44,12 +44,12 @@ public function invoke(AbstractRequest $request): ResourceObject $first = new Request($invoker, $child); $second = new Request($invoker, clone $child); $parent = clone $child; - $tags = $this->injector->getInstance(DependsOnTags::class); + $evaluator = $this->injector->getInstance(ResourceBodyEvaluator::class); $child->body = [$second]; $parent->body = (object) ['second' => $second, 'nested' => [$first], 'child' => $child, 'first' => $first, 'again' => $second]; // INV-08: enumeration preserves order and multiplicity without running a child. - $this->assertSame([$second, $first, $second], iterator_to_array($tags->requests($parent))); + $this->assertSame([$second, $first, $second], iterator_to_array($evaluator->requests($parent))); $this->assertSame(0, $invoker->calls); $parent->body = (static function () use ($first, $invoker) { @@ -57,7 +57,7 @@ public function invoke(AbstractRequest $request): ResourceObject yield $first; })(); - $this->assertSame([], iterator_to_array($tags->requests($parent))); + $this->assertSame([], iterator_to_array($evaluator->requests($parent))); $this->assertSame(0, $invoker->calls); } } From 328d9e49a3251831085db388d84afd010e13de7c Mon Sep 17 00:00:00 2001 From: Akihito Koriyama Date: Sat, 28 Nov 2026 22:06:38 +0900 Subject: [PATCH 2/2] Move embedded request enumeration into EmbeddedRequests ResourceBodyEvaluator transforms a body for storage and never enumerated requests itself, so the enumeration moves to a stateless iterable built by EmbeddedRequests::of(). CacheDependencyCollector and Dependencies no longer take a ResourceBodyEvaluator. The CommandTargets $purge docblock now states that collection link URIs follow the #[Purge]/#[Refresh] ones. --- src/CacheDependencyCollector.php | 7 ++- src/CommandTargets.php | 2 +- src/Dependencies.php | 3 +- src/EmbeddedRequests.php | 45 +++++++++++++++++++ src/ResourceBodyEvaluator.php | 17 ------- tests/CacheDependencyCollectorTest.php | 3 +- tests/DonutMaterialDependencyTest.php | 2 +- ...uatorTest.php => EmbeddedRequestsTest.php} | 16 ++----- 8 files changed, 55 insertions(+), 40 deletions(-) create mode 100644 src/EmbeddedRequests.php rename tests/{ResourceBodyEvaluatorTest.php => EmbeddedRequestsTest.php} (75%) diff --git a/src/CacheDependencyCollector.php b/src/CacheDependencyCollector.php index bb7c4dc1..f34026a1 100644 --- a/src/CacheDependencyCollector.php +++ b/src/CacheDependencyCollector.php @@ -20,7 +20,6 @@ public function __construct( private CacheDependencyInterface $cacheDependency, private CacheTags $cacheTags, private CacheIdentityFactory $identityFactory, - private ResourceBodyEvaluator $bodyEvaluator, #[CacheLog] private SemanticLoggerInterface $logger, ) { @@ -29,7 +28,7 @@ public function __construct( /** @param TagSet $keys the keys the response has before anything is collected */ public function begin(TagSet $keys): Dependencies { - return new Dependencies($keys, $this->dependsOnTags, $this->resourceParamSources, $this->cacheTags, $this->identityFactory, $this->bodyEvaluator); + return new Dependencies($keys, $this->dependsOnTags, $this->resourceParamSources, $this->cacheTags, $this->identityFactory); } /** @@ -41,7 +40,7 @@ public function collect(ResourceObject $ro): void { $dependencies = $this->begin(new TagSet()); $this->declared($ro); - foreach ($this->bodyEvaluator->requests($ro) as $request) { + foreach (EmbeddedRequests::of($ro) as $request) { $this->materialize($request); $child = $request->resourceObject; $this->depends($ro, $child, $dependencies->read($child)); @@ -52,7 +51,7 @@ public function collect(ResourceObject $ro): void public function materials(ResourceObject $ro, Dependencies $dependencies): void { $this->declared($ro); - foreach ($this->bodyEvaluator->requests($ro) as $request) { + foreach (EmbeddedRequests::of($ro) as $request) { $child = $request->resourceObject; $this->depends($ro, $child, $dependencies->embedded($child)); } diff --git a/src/CommandTargets.php b/src/CommandTargets.php index f6e8b211..55bc15f8 100644 --- a/src/CommandTargets.php +++ b/src/CommandTargets.php @@ -14,7 +14,7 @@ final readonly class CommandTargets { /** - * @param list $purge all declared URIs to purge, in declaration order + * @param list $purge the #[Purge]/#[Refresh] URIs in declaration order, then the #[Link(rel: 'collection')] URIs * @param list $refresh the #[Refresh] URIs to read again after every purge has run */ public function __construct( diff --git a/src/Dependencies.php b/src/Dependencies.php index 7748cb65..c1bad6ca 100644 --- a/src/Dependencies.php +++ b/src/Dependencies.php @@ -25,7 +25,6 @@ public function __construct( private readonly ResourceParamSources $resourceParamSources, private readonly CacheTags $cacheTags, private readonly CacheIdentityFactory $identityFactory, - private readonly ResourceBodyEvaluator $bodyEvaluator, ) { } @@ -110,7 +109,7 @@ private function ofResult(ResourceObject $ro, Closure $embedded): TagSet|null private function passedUp(ResourceObject $ro, Closure $embedded): TagSet { $tags = new TagSet(); - foreach ($this->bodyEvaluator->requests($ro) as $request) { + foreach (EmbeddedRequests::of($ro) as $request) { if ($embedded($request->resourceObject)) { $tags = $tags->merge($this->cacheTags->tags($request->resourceObject)); } diff --git a/src/EmbeddedRequests.php b/src/EmbeddedRequests.php new file mode 100644 index 00000000..b491453a --- /dev/null +++ b/src/EmbeddedRequests.php @@ -0,0 +1,45 @@ + + * @internal + */ +final readonly class EmbeddedRequests implements IteratorAggregate +{ + private function __construct( + private ResourceObject $ro, + ) { + } + + public static function of(ResourceObject $ro): self + { + return new self($ro); + } + + /** @return Generator */ + #[Override] + public function getIterator(): Generator + { + /** @var mixed $body */ + foreach ((array) $this->ro->body as $body) { + if ($body instanceof AbstractRequest) { + yield $body; + } + } + } +} diff --git a/src/ResourceBodyEvaluator.php b/src/ResourceBodyEvaluator.php index fa067302..2496d5a7 100644 --- a/src/ResourceBodyEvaluator.php +++ b/src/ResourceBodyEvaluator.php @@ -7,7 +7,6 @@ use BEAR\Resource\AbstractRequest; use BEAR\Resource\RequestInterface; use BEAR\Resource\ResourceObject; -use Generator; use function assert; use function is_array; @@ -22,22 +21,6 @@ */ final class ResourceBodyEvaluator { - /** - * Enumerate only immediate values of the array-cast body, in order and with duplicates. - * Do not execute requests, descend into children, or consume Traversable bodies. - * - * @return Generator - */ - public function requests(ResourceObject $ro): Generator - { - /** @var mixed $body */ - foreach ((array) $ro->body as $body) { - if ($body instanceof AbstractRequest) { - yield $body; - } - } - } - public function __invoke(mixed $body): mixed { if (! is_array($body)) { diff --git a/tests/CacheDependencyCollectorTest.php b/tests/CacheDependencyCollectorTest.php index a099eb4b..b49cfb90 100644 --- a/tests/CacheDependencyCollectorTest.php +++ b/tests/CacheDependencyCollectorTest.php @@ -50,9 +50,8 @@ public function invoke(AbstractRequest $request): ResourceObject }; $parent->uri = new Uri('app://self/parent'); $parent->body = ['scalar', $child, [$request], $request]; - $evaluator = $this->injector->getInstance(ResourceBodyEvaluator::class); - $this->assertSame([$request], iterator_to_array($evaluator->requests($parent))); + $this->assertSame([$request], iterator_to_array(EmbeddedRequests::of($parent))); $this->assertSame(0, $invoker->calls); $this->injector->getInstance(CacheDependencyCollector::class)->collect($parent); $this->assertSame(1, $invoker->calls); diff --git a/tests/DonutMaterialDependencyTest.php b/tests/DonutMaterialDependencyTest.php index 00012b21..ec9d80ab 100644 --- a/tests/DonutMaterialDependencyTest.php +++ b/tests/DonutMaterialDependencyTest.php @@ -449,7 +449,7 @@ public function get(): DonutRendererInterface new DeclaredCacheControl(), new ReplacedEntry($logger, $storage, $uriTag), $cacheTags, - new CacheDependencyCollector($dependsOnTags, $sources, new CacheDependency($cacheTags, $logger), $cacheTags, $identityFactory, new ResourceBodyEvaluator(), $logger), + new CacheDependencyCollector($dependsOnTags, $sources, new CacheDependency($cacheTags, $logger), $cacheTags, $identityFactory, $logger), ), ]; } diff --git a/tests/ResourceBodyEvaluatorTest.php b/tests/EmbeddedRequestsTest.php similarity index 75% rename from tests/ResourceBodyEvaluatorTest.php rename to tests/EmbeddedRequestsTest.php index 56ce6d8d..c1300ed4 100644 --- a/tests/ResourceBodyEvaluatorTest.php +++ b/tests/EmbeddedRequestsTest.php @@ -11,20 +11,11 @@ use BEAR\Resource\Uri; use Override; use PHPUnit\Framework\TestCase; -use Ray\Di\Injector; -use Ray\Di\InjectorInterface; use function iterator_to_array; -class ResourceBodyEvaluatorTest extends TestCase +class EmbeddedRequestsTest extends TestCase { - private InjectorInterface $injector; - - protected function setUp(): void - { - $this->injector = new Injector(ModuleFactory::getInstance('FakeVendor\HelloWorld'), __DIR__ . '/tmp'); - } - public function testRequestsPreserveOrderAndDuplicatesWithoutConsumingTraversableBodies(): void { $child = new class extends ResourceObject { @@ -44,12 +35,11 @@ public function invoke(AbstractRequest $request): ResourceObject $first = new Request($invoker, $child); $second = new Request($invoker, clone $child); $parent = clone $child; - $evaluator = $this->injector->getInstance(ResourceBodyEvaluator::class); $child->body = [$second]; $parent->body = (object) ['second' => $second, 'nested' => [$first], 'child' => $child, 'first' => $first, 'again' => $second]; // INV-08: enumeration preserves order and multiplicity without running a child. - $this->assertSame([$second, $first, $second], iterator_to_array($evaluator->requests($parent))); + $this->assertSame([$second, $first, $second], iterator_to_array(EmbeddedRequests::of($parent))); $this->assertSame(0, $invoker->calls); $parent->body = (static function () use ($first, $invoker) { @@ -57,7 +47,7 @@ public function invoke(AbstractRequest $request): ResourceObject yield $first; })(); - $this->assertSame([], iterator_to_array($evaluator->requests($parent))); + $this->assertSame([], iterator_to_array(EmbeddedRequests::of($parent))); $this->assertSame(0, $invoker->calls); } }