Skip to content

Add #[PurgeContext] to share a context across a controller or action - #182

Merged
HypeMC merged 9 commits into
2.xfrom
petarf-sofascore/PurgeContext
Dec 2, 2026
Merged

HypeMC merged 9 commits into
2.xfrom
petarf-sofascore/PurgeContext

Conversation

@petarf-sofascore

@petarf-sofascore petarf-sofascore commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary 📝

The context of #[PurgeOn] (#176) must be repeated on every subscription, even when all routes of a controller need the same data, for example a priority or a cache tag on every social route.

This adds a #[PurgeContext] attribute for controller classes and actions. The context of a subscription starts as the class context. The action context replaces the top-level keys it sets, and then the context of the PurgeOn does the same. It's a plain array_replace(): a key replaces the whole value, nested arrays included, so a level that sets a key writes its full value, and null removes a value.

#[PurgeContext(['priority' => 'low', 'varnish' => ['tags' => ['social'], 'ttl' => 60]])]
class SocialController
{
    #[Route('/social/feed', 'social_feed')]
    #[PurgeOn(Post::class)]        // ['priority' => 'low', 'varnish' => ['tags' => ['social'], 'ttl' => 60]]
    public function feedAction() {}

    #[Route('/social/post/{id}', 'social_post')]
    #[PurgeContext(['varnish' => ['tags' => ['social', 'post'], 'ttl' => 5]])]
    #[PurgeOn(Post::class)]        // ['priority' => 'low', 'varnish' => ['tags' => ['social', 'post'], 'ttl' => 5]]
    #[PurgeOn(Comment::class, routeParams: ['id' => 'post.id'], context: ['priority' => 'high'])]
                                   // ['priority' => 'high', 'varnish' => ['tags' => ['social', 'post'], 'ttl' => 5]]
    public function postAction(Post $post) {}

    #[Route('/social/live', 'social_live')]
    #[PurgeContext(['varnish' => null])]
    #[PurgeOn(Post::class)]        // ['priority' => 'low', 'varnish' => null]
    public function liveAction() {}
}

The action context also applies to the class-level #[PurgeOn] subscriptions of its route. #[PurgeContext] doesn't apply to YAML subscriptions, which have no class or action to put it on. It accepts the same values as the PurgeOn context and validates them the same way: the validation moved from PurgeOn to an internal PurgeContext::validate(). PurgeContext can be extended to create your own context attributes, and like its other arguments, which accept a short form or an object, the context of PurgeOn also accepts a PurgeContext or a subclass of it:

#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)]
final class PurgePriority extends PurgeContext
{
    public function __construct(Priority $priority)
    {
        parent::__construct(['priority' => $priority->value]);
    }
}

#[PurgePriority(Priority::Low)]
class SocialController
{
    #[Route('/social/post/{id}', 'social_post')]
    #[PurgeOn(Comment::class, routeParams: ['id' => 'post.id'], context: new PurgePriority(Priority::High))]
    public function postAction(Post $post) {}
}

The merge happens once, in AttributeMetadataProvider, and the result is stored on a new RouteMetadata::$context. It defaults to the PurgeOn context, so YamlMetadataProvider and other code that builds RouteMetadata keep working. The built-in subscription resolvers and PurgeSubscriptionProvider now read RouteMetadata::$context instead of PurgeOn::$context. A custom subscription resolver written against 2.1.0 that copies $routeMetadata->purgeOn->context keeps working as before, but doesn't get the #[PurgeContext] values until it switches to $routeMetadata->context. The changelog says so. Everything after the subscription (the cached configuration, PurgeRequest::$contexts, purgatory:debug and the profiler) already carries the context, so it shows the merged value without changes.

Decisions:

  • A single array, not variadic arguments. #[PurgeContext([...])] has the same shape as PurgeOn(context: [...]). The bundle uses variadics only for lists of values, never for keys and values.
  • Top-level keys only, no recursive merge. The bundle doesn't look inside the values of the user's context, so the result is easy to predict. A deeper or configurable merge can come later if a use case needs it.
  • null is a normal value. It replaces the less specific value and the key stays, so a purger that reads the context with ?? or isset() sees no value. This keeps the 2.1.0 behaviour, where PurgeOn(context: ['ttl' => null]) already reaches the purger as is.
  • The key order is fixed. Keys keep the order of the class context, and new keys go at the end. This matters because EntityChangeListener compares contexts strictly when it removes duplicates.
  • The class context comes from the class that declares the action. This is the same class that class-level #[PurgeOn] attributes are read from.
  • One PurgeContext per controller class or action, subclasses included. With several on one level, a key set by two of them would depend on the order of the attributes. Loading the subscriptions throws a LogicException that names the attributes instead, so the order of the attributes never matters, also relative to the #[PurgeOn] attributes.

Tested locally with PHPUnit on PHP 8.5 and a PHP 8.1 lint of the changed files. PHPStan and PHP CS Fixer run in CI.

Checklist ✅

  • Tests updated 🐛
  • Docs updated 📚
  • Changelog updated 📋
  • Breaking change ⚠️

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.49%. Comparing base (a3021e4) to head (454bee9).

Additional details and impacted files
@@             Coverage Diff              @@
##                2.x     #182      +/-   ##
============================================
+ Coverage     97.46%   97.49%   +0.03%     
- Complexity      729      737       +8     
============================================
  Files            76       77       +1     
  Lines          1736     1759      +23     
============================================
+ Hits           1692     1715      +23     
  Misses           44       44              
Flag Coverage Δ
8.1 91.41% <100.00%> (+0.11%) ⬆️
8.2 91.46% <100.00%> (+0.11%) ⬆️
8.3 91.29% <100.00%> (+0.11%) ⬆️
8.4 92.31% <100.00%> (+0.10%) ⬆️
8.5 97.38% <100.00%> (+0.03%) ⬆️
8.6 97.38% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@petarf-sofascore
petarf-sofascore marked this pull request as ready for review November 16, 2026 11:22
Comment thread src/Attribute/PurgeContext.php Resolved
Comment thread src/Attribute/PurgeOn.php Resolved
@petarf-sofascore
petarf-sofascore force-pushed the petarf-sofascore/PurgeContext branch from 223fae5 to 1682d31 Compare November 17, 2026 06:42
@Brajk19
Brajk19 requested a review from HypeMC November 19, 2026 09:18
@HypeMC
HypeMC force-pushed the petarf-sofascore/PurgeContext branch from 1682d31 to 8be890f Compare November 19, 2026 09:22
@petarf-sofascore petarf-sofascore self-assigned this Nov 25, 2026
Brajk19
Brajk19 previously approved these changes Nov 30, 2026
The `context` of a purge subscription can now also be set with the
`#[PurgeContext]` attribute on a controller class or an action. The
context of a subscription is the class context, merged with the action
context and then with the `context` of the `PurgeOn`: arrays with keys
are merged key by key, lists are appended without duplicates, and any
other value replaces the previous one.

The merged context is stored on `RouteMetadata::$context`, which the
subscription resolvers now pass to the purge subscriptions.
As agreed in review, a more specific context now replaces the whole
value of each top-level key it sets (`array_replace`), instead of
merging nested arrays and appending lists. A level that sets a key must
write its full value, and `null` removes a value.

This removes `ContextMerger`, as the merge is a single `array_replace`.
Like its other arguments, which accept a short form or an object,
`PurgeOn` now also takes a `PurgeContext` for its `context` and turns it
into its array.
`AGENTS.md` asks not to add tests that only check that a constructor
keeps its arguments, to only add comments that say something the code
doesn't, and to put a new test right after the test it relates to,
not between two tests that belong together.

So this removes the test of the `PurgeContext` constructor, the comments
that named the rule each block of the attribute provider test checks,
and moves the new `PurgeOn` and debug command tests after their groups.
As agreed in review, applications can now extend `PurgeContext` to
create their own context attributes, such as a `#[PurgePriority]` that
sets one key. The attribute provider finds them with `IS_INSTANCEOF`,
and `PurgeOn` already accepts them as its `context`.

A controller class or method can still have only one of these
attributes. With several on one level, their contexts would have to be
merged before the class, method and `PurgeOn` precedence applies, and
a key set by two of them would depend on the order of the attributes.
Loading the subscriptions fails with an exception instead, so the order
never matters.
@HypeMC
HypeMC force-pushed the petarf-sofascore/PurgeContext branch from 4d4e9b9 to 6c54091 Compare December 2, 2026 06:29
The resolvers now read the context from `RouteMetadata::$context`, which
the YAML provider leaves to its default, the context of the `PurgeOn`.
No test failed when that default was changed to an empty array, which
would drop the context of every YAML subscription.
The other docs and the changelog write `#[PurgeOn]` and talk about its
parameters, start a how-to with "You can", use "In this example", link
attributes to their source and say an invalid attribute throws "an
exception during cache warmup". The `PurgeContext` docs now do the same.

Setting a key to `null` doesn't remove the key, the purger still gets
it with a `null` value, so the docs now say it clears the value, and
name the actions of the example instead of "the action above".
When a controller class or method had the same context attribute more
than once, such as a repeatable subclass of `PurgeContext`, the message
repeated its class name for each of them. It now names each class once,
followed by how many times it was found, as in `"PurgeReason" 2 times`.

A count of one is left out, so with one attribute of each class the
message stays the same. The count follows the name because before it,
as in `found 2 "A", "B"`, it would read as the total.
@HypeMC HypeMC mentioned this pull request Dec 2, 2026
1 of 4 tasks
@HypeMC
HypeMC merged commit 1d200ac into 2.x Dec 2, 2026
109 of 110 checks passed
@HypeMC
HypeMC deleted the petarf-sofascore/PurgeContext branch December 2, 2026 08:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants