Skip to content

SubjectIdMiddleware ​

Rasuvaeff\Yii3AbTestingWeb\SubjectIdMiddleware

Class · rasuvaeff/yii3-ab-testing-web · Source

Establishes a stable subject id for A/B assignment and exposes it as a request attribute.

Resolution order:

  1. If the configured attribute is already a non-empty string (an upstream auth middleware set subjectId = userId), the configured identity-transition strategy chooses it or an existing anonymous id.
  2. When persistence is allowed, the ab_id cookie is read; a value the SubjectIdGeneratorInterface recognises as its own is reused — anything else (tampered, truncated, oversized) is discarded and regenerated, so arbitrary client-supplied strings never become subject ids in logs and analytics.
  3. Otherwise the generator mints a new opaque id (by default random_bytes(16) as hex). With consent it is persisted in a long-lived HttpOnly, SameSite=Lax cookie; without consent it is request-only.

Because assignment is deterministic in subjectId, a stable id is enough to keep an anonymous visitor in the same variant across visits — no variant is stored. The id is opaque (not a UUID) and carries no personal data, but it is a persistent identifier. ConsentPolicyInterface is checked before a persistent identity is read or created.

Constructor ​

php
new SubjectIdMiddleware(
    string $cookieName = 'ab_id',
    string $attribute = 'ab.subjectId',
    DateInterval $maxAge = new DateInterval(),
    bool $secure = true,
    string $sameSite = Yiisoft\Cookies\Cookie::SAME_SITE_LAX,
    ?SubjectIdGeneratorInterface $idGenerator = null,
    ConsentPolicyInterface $consentPolicy = new AllowAllConsentPolicy(),
    AnonymousToAuthenticatedStrategy $identityTransition = AnonymousToAuthenticatedStrategy::MigrateAssignments,
)
  • $idGenerator — null keeps the historical format ({@see HexSubjectIdGenerator})

Methods ​

process() ​

php
process(
    Psr\Http\Message\ServerRequestInterface $request,
    Psr\Http\Server\RequestHandlerInterface $handler,
): Psr\Http\Message\ResponseInterface