Search by

nolikein / cookie-factory-interface

Nolikein

A library which provides a factory interface to create cookies. Inspired by PSR practices: https://www.php-fig.org/psr/

2.0.0 2026-11-08 23:46 UTC

This package is auto-updated.

Last update: 2026-11-11 21:33:36 UTC


README

PHP Packagist version Downloads License Pipeline

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:

  • $expire is a Unix timestamp (int) or a DateTimeInterface. 0 creates a session cookie. A far-future timestamp (beyond the year 9999) makes setcookie throw a ValueError when the header is emitted: bound an expiry that comes from outside input.
  • $isHttpOnly is true by default, like the default of CookieInterface::withSecurity; pass false to let scripts read the cookie.
  • $isSecure is true by default: the browser only sends the cookie over HTTPS. Pass false only on a site served over plain HTTP, such as a local development server.
  • The factory applies every argument and returns the cookie that CookieInterface describes, with no other with* 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-Cookie header must encode it (as setcookie does) 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 $expire as DateTimeInterface|int (it was untyped).
  • Default $isSecure and $isHttpOnly to true (both were false).
  • 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-interface 2.1 or later: its with* methods return static, 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 $isSecure is now secure (HTTPS only): pass false on a site served over plain HTTP.
  • A cookie created without $isHttpOnly is now HTTP only: pass false where a script must read it.
  • An argument refused by CookieInterface throws an exception: catch CookieExceptionInterface (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.