nolikein / cookie-factory-interface
A library which provides a factory interface to create cookies. Inspired by PSR practices: https://www.php-fig.org/psr/
Package info
gitlab.com/Come-Wasik/php-cookie-factory-interface
pkg:composer/nolikein/cookie-factory-interface
Requires
- php: ^8.4
- nolikein/cookie-interface: ^2.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- pestphp/pest: ^4.0
- phpstan/phpstan: ^2.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-11 21:33:36 UTC
README
Overview
Managing cookies may be difficult without any constraint. So, in the spirit of the PSR (PHP Standards Recommendations) I created nolikein/cookie-interface, the interface of an immutable cookie.
The generic nature of that interface allows the factory design pattern. This library provides the interface of such a factory: Nolikein\Cookie\CookieFactoryInterface creates a Nolikein\Cookie\CookieInterface from the arguments of the native setcookie function. It ships no implementation.
Requirements
PHP 8.4 or later.
Installation
composer require nolikein/cookie-factory-interface ^2.0
It installs nolikein/cookie-interface ^2.1 as well.
Usage
Create a class which implements Nolikein\Cookie\CookieFactoryInterface: it declares one method, createCookie.
use DateTimeInterface;
use Nolikein\Cookie\CookieFactoryInterface;
use Nolikein\Cookie\CookieInterface;
final class CookieFactory implements CookieFactoryInterface
{
public function createCookie(
string $name,
string $value = '',
DateTimeInterface|int $expire = 0,
string $path = '',
string $domain = '',
bool $isSecure = true,
bool $isHttpOnly = true,
): CookieInterface {
return (new Cookie()) // Cookie implements CookieInterface
->withName($name)
->withValue($value)
->withExpirationTime($expire)
->withPath($path)
->withDomain($domain)
->withSecurity($isSecure, $isHttpOnly);
}
}
Any implementation can then be used like this:
function createLoginCookie(CookieFactoryInterface $factory): CookieInterface
{
// An empty domain (the default) makes a host-only cookie, the narrowest scope.
return $factory->createCookie('session_id', 'abc123', time() + 3600, '/');
}
The contract in short:
$expireis a Unix timestamp (int) or aDateTimeInterface.0creates a session cookie. A far-future timestamp (beyond the year 9999) makessetcookiethrow aValueErrorwhen the header is emitted: bound an expiry that comes from outside input.$isHttpOnlyistrueby default, like the default ofCookieInterface::withSecurity; passfalseto let scripts read the cookie.$isSecureistrueby default: the browser only sends the cookie over HTTPS. Passfalseonly on a site served over plain HTTP, such as a local development server.- The factory applies every argument and returns the cookie that
CookieInterfacedescribes, with no otherwith*call:getSameSite()is'Lax'. The rules of that interface (RFC 6265 name, path and domain, SameSite) are the ones of its README. - The value is stored unchanged and the client controls it: whoever builds the
Set-Cookieheader must encode it (assetcookiedoes) or refuse it, and your code must not trust it.
Implementing
PHP does not check that an implementation keeps the types and the default values of the interface: an implementation may widen $expire to untyped or default $isSecure or $isHttpOnly to false without any error. The contract forbids it (an implementation MUST declare the types and the defaults of the signature), so pin it in a test of your own:
$parameters = (new ReflectionMethod(CookieFactory::class, 'createCookie'))->getParameters();
assert((string) $parameters[2]->getType() === 'DateTimeInterface|int');
assert($parameters[5]->getDefaultValue() === true); // $isSecure
assert($parameters[6]->getDefaultValue() === true); // $isHttpOnly
A caller who needs a secure or HTTP only cookie whatever the implementation can also pass $isSecure or $isHttpOnly explicitly.
Exceptions
A name, a path or a domain refused by CookieInterface (or a value, when the implementation refuses one) makes the factory throw an exception which extends \InvalidArgumentException and implements Nolikein\Cookie\CookieExceptionInterface (provided by nolikein/cookie-interface), so one catch handles any refused value:
use Nolikein\Cookie\CookieExceptionInterface;
try {
$cookie = $factory->createCookie($name, $value);
} catch (CookieExceptionInterface $exception) {
// a value was refused
}
The message of the exception never contains the value of the cookie, which may be a session id: CookieInterface forbids it since nolikein/cookie-interface 2.1.0, and this contract forbids it for an exception the factory throws. Log the message, never the value.
A TypeError raised by the native type of $expire is not covered. It comes from the type that the implementation declares, and PHP only guarantees it for callers which declare strict_types.
Upgrading from 1.x
Version 2.0 requires PHP 8.4 or later and nolikein/cookie-interface ^2.1:
composer require nolikein/cookie-factory-interface ^2.0
In a class which implements CookieFactoryInterface:
- Type
$expireasDateTimeInterface|int(it was untyped). - Default
$isSecureand$isHttpOnlytotrue(both werefalse). - Call every
with*method of the signature, even for a default argument, and no other one (see the example in "Usage"). - Return a cookie which follows
nolikein/cookie-interface2.1 or later: itswith*methods returnstatic,getExpirationTime()returns?DateTimeInterface, SameSite is'Lax'by default.
PHP raises no error when an implementation keeps the 1.x signature: change it by hand and pin it with the test of "Implementing".
In the code which calls createCookie:
- A cookie created without
$isSecureis now secure (HTTPS only): passfalseon a site served over plain HTTP. - A cookie created without
$isHttpOnlyis now HTTP only: passfalsewhere a script must read it. - An argument refused by
CookieInterfacethrows an exception: catchCookieExceptionInterface(see "Exceptions").
The full list of changes is in the changelog.
Development
Every command runs in the Docker container, never on the host. The default PHP version is 8.4; set PHP_VERSION=8.5 to use another one.
docker compose build
docker compose run --rm php composer install
docker compose run --rm php composer qa
composer qa runs the format check, PHPStan and the Pest tests.
Links
Licence
The project is under licence MIT.