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:
- 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. - When persistence is allowed, the
ab_idcookie is read; a value theSubjectIdGeneratorInterfacerecognises 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. - Otherwise the generator mints a new opaque id (by default
random_bytes(16)as hex). With consent it is persisted in a long-livedHttpOnly,SameSite=Laxcookie; 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