• Stars
    star
    223
  • Rank 177,903 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cookies for PSR-7 HTTP Message Interface.

FIG Cookies

Managing Cookies for PSR-7 Requests and Responses.

Latest Stable Version Total Downloads Latest Unstable Version License
Build Status Scrutinizer Code Quality Code Coverage Code Climate
Join the chat at https://gitter.im/dflydev/dflydev-fig-cookies

Installation

$> composer require dflydev/fig-cookies

Concepts

FIG Cookies tackles two problems, managing Cookie Request headers and managing Set-Cookie Response headers. It does this by way of introducing a Cookies class to manage collections of Cookie instances and a SetCookies class to manage collections of SetCookie instances.

Instantiating these collections looks like this:

// Get a collection representing the cookies in the Cookie headers
// of a PSR-7 Request.
$cookies = Dflydev\FigCookies\Cookies::fromRequest($request);

// Get a collection representing the cookies in the Set-Cookie headers
// of a PSR-7 Response
$setCookies = Dflydev\FigCookies\SetCookies::fromResponse($response);

After modifying these collections in some way, they are rendered into a PSR-7 Request or PSR-7 Response like this:

// Render the Cookie headers and add them to the headers of a
// PSR-7 Request.
$request = $cookies->renderIntoCookieHeader($request);

// Render the Set-Cookie headers and add them to the headers of a
// PSR-7 Response.
$response = $setCookies->renderIntoSetCookieHeader($response);

Like PSR-7 Messages, Cookie, Cookies, SetCookie, and SetCookies are all represented as immutable value objects and all mutators will return new instances of the original with the requested changes.

While this style of design has many benefits it can become fairly verbose very quickly. In order to get around that, FIG Cookies provides two facades in an attempt to help simplify things and make the whole process less verbose.

Basic Usage

The easiest way to start working with FIG Cookies is by using the FigRequestCookies and FigResponseCookies classes. They are facades to the primitive FIG Cookies classes. Their jobs are to make common cookie related tasks easier and less verbose than working with the primitive classes directly.

There is overhead on creating Cookies and SetCookies and rebuilding requests and responses. Each of the FigCookies methods will go through this process so be wary of using too many of these calls in the same section of code. In some cases it may be better to work with the primitive FIG Cookies classes directly rather than using the facades.

Request Cookies

Requests include cookie information in the Cookie request header. The cookies in this header are represented by the Cookie class.

use Dflydev\FigCookies\Cookie;

$cookie = Cookie::create('theme', 'blue');

To easily work with request cookies, use the FigRequestCookies facade.

Get a Request Cookie

The get method will return a Cookie instance. If no cookie by the specified name exists, the returned Cookie instance will have a null value.

The optional third parameter to get sets the value that should be used if a cookie does not exist.

use Dflydev\FigCookies\FigRequestCookies;

$cookie = FigRequestCookies::get($request, 'theme');
$cookie = FigRequestCookies::get($request, 'theme', 'default-theme');

Set a Request Cookie

The set method will either add a cookie or replace an existing cookie.

The Cookie primitive is used as the second argument.

use Dflydev\FigCookies\FigRequestCookies;

$request = FigRequestCookies::set($request, Cookie::create('theme', 'blue'));

Modify a Request Cookie

The modify method allows for replacing the contents of a cookie based on the current cookie with the specified name. The third argument is a callable that takes a Cookie instance as its first argument and is expected to return a Cookie instance.

If no cookie by the specified name exists, a new Cookie instance with a null value will be passed to the callable.

use Dflydev\FigCookies\FigRequestCookies;

$modify = function (Cookie $cookie) {
    $value = $cookie->getValue();

    // ... inspect current $value and determine if $value should
    // change or if it can stay the same. in all cases, a cookie
    // should be returned from this callback...

    return $cookie->withValue($value);
}

$request = FigRequestCookies::modify($request, 'theme', $modify);

Remove a Request Cookie

The remove method removes a cookie from the request headers if it exists.

use Dflydev\FigCookies\FigRequestCookies;

$request = FigRequestCookies::remove($request, 'theme');

Note that this does not cause the client to remove the cookie. Take a look at the SetCookie class' expire() method to do that.

Response Cookies

Responses include cookie information in the Set-Cookie response header. The cookies in these headers are represented by the SetCookie class.

use Dflydev\FigCookies\Modifier\SameSite;
use Dflydev\FigCookies\SetCookie;

$setCookie = SetCookie::create('lu')
    ->withValue('Rg3vHJZnehYLjVg7qi3bZjzg')
    ->withExpires('Tue, 15-Jan-2013 21:47:38 GMT')
    ->withMaxAge(500)
    ->rememberForever()
    ->withPath('/')
    ->withDomain('.example.com')
    ->withSecure(true)
    ->withHttpOnly(true)
    ->withSameSite(SameSite::lax())
;

To easily work with response cookies, use the FigResponseCookies facade.

Get a Response Cookie

The get method will return a SetCookie instance. If no cookie by the specified name exists, the returned SetCookie instance will have a null value.

The optional third parameter to get sets the value that should be used if a cookie does not exist.

use Dflydev\FigCookies\FigResponseCookies;

$setCookie = FigResponseCookies::get($response, 'theme');
$setCookie = FigResponseCookies::get($response, 'theme', 'simple');

Set a Response Cookie

The set method will either add a cookie or replace an existing cookie.

The SetCookie primitive is used as the second argument.

use Dflydev\FigCookies\FigResponseCookies;

$response = FigResponseCookies::set($response, SetCookie::create('token')
    ->withValue('a9s87dfz978a9')
    ->withDomain('example.com')
    ->withPath('/firewall')
);

Modify a Response Cookie

The modify method allows for replacing the contents of a cookie based on the current cookie with the specified name. The third argument is a callable that takes a SetCookie instance as its first argument and is expected to return a SetCookie instance.

If no cookie by the specified name exists, a new SetCookie instance with a null value will be passed to the callable.

use Dflydev\FigCookies\FigResponseCookies;

$modify = function (SetCookie $setCookie) {
    $value = $setCookie->getValue();

    // ... inspect current $value and determine if $value should
    // change or if it can stay the same. in all cases, a cookie
    // should be returned from this callback...

    return $setCookie
        ->withValue($newValue)
        ->withExpires($newExpires)
    ;
}

$response = FigResponseCookies::modify($response, 'theme', $modify);

Remove a Response Cookie

The remove method removes a cookie from the response if it exists.

use Dflydev\FigCookies\FigResponseCookies;

$response = FigResponseCookies::remove($response, 'theme');

Expire a Response Cookie

The expire method sets a cookie with an expiry date in the far past. This causes the client to remove the cookie.

Note that in order to expire a cookie, you need to configure its Set-Cookie header just like when you initially wrote the cookie (i.e. same domain/path). The easiest way to do this is to re-use the same code for configuring the header when setting as well as expiring the cookie:

use Dflydev\FigCookies\FigResponseCookies;
use Dflydev\FigCookies\SetCookie;

$setCookie = SetCookie::create('ba')
    ->withValue('UQdfdafpJJ23k111m')
    ->withPath('/')
    ->withDomain('.example.com')
;

FigResponseCookies::set($response, $setCookie->expire());

FAQ

Do you call setcookies?

No.

Delivery of the rendered SetCookie instances is the responsibility of the PSR-7 client implementation.

Do you do anything with sessions?

No.

It would be possible to build session handling using cookies on top of FIG Cookies but it is out of scope for this package.

Do you read from $_COOKIES?

No.

FIG Cookies only pays attention to the Cookie headers on PSR-7 Request instances. In the case of ServerRequestInterface instances, PSR-7 implementations should be including $_COOKIES values in the headers so in that case FIG Cookies may be interacting with $_COOKIES indirectly.

License

MIT, see LICENSE.

Community

Want to get involved? Here are a few ways:

  • Find us in the #dflydev IRC channel on irc.freenode.org.
  • Mention @dflydev on Twitter.
  • Join the chat at https://gitter.im/dflydev/dflydev-fig-cookies

More Repositories

1

dflydev-dot-access-data

Given a deep data structure representing a configuration, access configuration by dot notation.
PHP
590
star
2

git-subsplit

Automate and simplify the process of managing one-way read-only subtree splits.
Shell
328
star
3

dflydev-doctrine-orm-service-provider

Doctrine ORM Service Provider
PHP
211
star
4

dflydev-markdown

PHP Markdown & Extra — DEPRECATED
PHP
171
star
5

dflydev-placeholder-resolver

Provides a mechanism to resolve placeholders from an arbitrary data source.
PHP
143
star
6

dflydev-dot-access-configuration

Given a deep data structure representing a configuration, access configuration by dot notation.
PHP
134
star
7

dflydev-embedded-composer

Embed Composer into another application
PHP
71
star
8

dflydev-apache-mime-types

Apache MIME Types
PHP
71
star
9

es-cqrs-broadway-workshop

Introduction to Event Sourcing & CQRS with Broadway workshop project
PHP
68
star
10

dflydev-hawk

Hawk — A PHP Implementation
PHP
67
star
11

embed-github-gist

Embed GitHub Gist WordPress plugin
PHP
47
star
12

dflydev-canal

Analyze content to determine the appropriate Internet media type
PHP
34
star
13

dflydev-git-subsplit-github-webhook

GitHub WebHook for Git subsplits managed by dflydev-git-subsplit.
PHP
28
star
14

just-run-phpunit

Allow developers to "just run phpunit."
27
star
15

check-runs-action

✅ GitHub Check Runs Action
TypeScript
15
star
16

dflydev-base32-crockford

Encode/decode numbers using Douglas Crockford's Base32 Encoding
PHP
13
star
17

dflydev-stack-basic-authentication

HTTP Basic Authentication Stack middleware
PHP
12
star
18

repose-php

Repose is an Object-Relational Mapping (ORM) library for PHP5. Repose implements a Unit of Work (UoW), an Identity Map and generated proxy classes to provide transparent unobtrusive persistence in PHP.
PHP
11
star
19

dflydev-stack-hawk

Hawk Stack middleware
PHP
10
star
20

dflydev-encrypted-fig-cookies

Encrypted Cookies for PSR-7 HTTP Message Interface.
PHP
7
star
21

dflydev-finite-state-machine

Yet another finite-state machine implementation
PHP
7
star
22

dflydev-github-gist-twig-extension

GitHub Gist Twig Extension
PHP
7
star
23

dflydev-util-antPathMatcher

Ant Path Matcher Utility
PHP
6
star
24

old-ninjagrl.com

Architecture demo application for ninjagrl.com
PHP
6
star
25

dflydev-symfony-finder-factory

Symfony Finder Factory
PHP
6
star
26

dflydev-event-store

Naive event store.
PHP
6
star
27

substrate-php

Substrate - An IoC/DI Container for PHP
PHP
5
star
28

dflydev-stack-firewall

Firewall Stack middleware
PHP
5
star
29

dflydev-psr0-resource-locator-service-provider

PSR-0 Resource Locator Service Provider
PHP
4
star
30

dflydev-identity-generator

Provide a standard interface for generating unique string-based identifiers.
PHP
4
star
31

dflydev-embedded-composer-application

Embedded Composer Example Application
PHP
4
star
32

dd-ci-ddauth

Dragonfly Development CodeIgniter Auth Add-on
PHP
4
star
33

composer-tutorial

PHP
3
star
34

jquery-ddNamespace

jQuery Namespace Add-on
JavaScript
3
star
35

dflydev-common-domain-model-identity

Identity for domain models.
PHP
3
star
36

dflydev-psr0-resource-locator-composer

Composer PSR-0 Resource Locator
PHP
3
star
37

dflydev-stack-authentication

STACK-2 Authentication Middlewares
PHP
3
star
38

dflydev-event-store-doctrine-dbal

Doctrine DBAL implementation of a naive event store.
PHP
3
star
39

repose-ci-php

Repose PHP ORM CodeIgniter Library
PHP
3
star
40

streamdeck-restreamio

🔌 Stream Deck Restream.io plugin
CSS
3
star
41

halo-php

Halo Web Application Framework for PHP
PHP
3
star
42

dflydev-psr0-resource-locator

PSR-0 Resource Locator
PHP
3
star
43

dflydev-github-gist-twig-bundle

GitHub Gist Twig Bundle
PHP
3
star
44

dflydev-twig-gitHub-gist-sculpin-bundle

Twig GitHub Gist Sculpin Bundle
PHP
2
star
45

dflydev.com

Dragonfly Development Website
HTML
2
star
46

dflydev-embedded-composer-core

[READ-ONLY] Subtree split of Dflydev\EmbeddedComposer\Core.
PHP
2
star
47

skittle-php

Skittle - A lightweight pure PHP template inclusion library
PHP
2
star
48

dd-ci-vendorlibs

Dragonfly Development CodeIgniter Vendor Libs Add-on
2
star
49

dd-configuration-php

Dragonfly Development PHP Configuration Library
PHP
2
star
50

dflydev-common-domain-model-identity-rhumsaa

Implementation of identity for domain models using rhumsaa/uuid.
PHP
2
star
51

safsi-php

Simple Abstract File System Interface
PHP
2
star
52

nimble-tutorial

Nimble Tutorial
Makefile
2
star
53

dflydev-embedded-composer-console

[READ-ONLY] Subtree split of Dflydev\EmbeddedComposer\Console.
PHP
2
star
54

ddvash

ddVash WordPress Theme
PHP
1
star
55

dflydev-snort

Sniff content to determine things about it.
PHP
1
star
56

dflydev-theme

Generic Theme Framework
PHP
1
star
57

dflydev-snort-buffer

[READ-ONLY] Subtree split of Dflydev\Snort\Buffer.
PHP
1
star
58

just-run-anything

Allow developers to "just run <anything>" where <anything> may exist at arbitrary paths *or* installed globally.
Shell
1
star
59

dflydev-theme-twig-extension

Theme Twig Extension
PHP
1
star
60

dflydev-doctrine-commands-service-provider

Doctrine Commands Service Provider
PHP
1
star
61

dflydev-composer-autoload

Composer Autoload Tools
PHP
1
star
62

lithe-php-single-site

Lithe - Single Site Application
PHP
1
star
63

raffl.io

CSS
1
star
64

dflydev-wp-theme

dflydev WordPress Theme
PHP
1
star
65

dd-image-php

dd-image is useful for doing simple image manipulation operations.
PHP
1
star
66

page-shortcodes

Page Shortcodes WordPress Plugin
PHP
1
star
67

lithe-php

Lithe - a lightweight web application framework for PHP built on Halo and Substrate
PHP
1
star
68

ddrem

ddRem WordPress Them
PHP
1
star
69

dflydev-core-php

Provides basic bootstrapping functionality such as resource locating and class loading.
PHP
1
star
70

dd-logging-php

Dragonfly Development PHP Logging Library
PHP
1
star
71

dd-uri-php

Dragonfly Development PHP URI Library
PHP
1
star
72

dd-idgen-php

Dragonfly Development PHP ID Generation Library
PHP
1
star
73

lithe-php-multiple-sites

Lithe - Multiple Sites Application
PHP
1
star
74

dflydev-common-domain-model-identity-ramsey

Implementation of identity for domain models using ramsey/uuid
PHP
1
star
75

d2code-core-wp-theme

d2code Core WordPress Theme
PHP
1
star
76

dflydev-identity-generator-dbal

Provides a Doctrine DBAL implemetnation of the identity generator data store.
PHP
1
star
77

dd-core-php

Dragonfly Development PHP Core Library
PHP
1
star
78

dflydev-theme-service-provider

Theme Service Provider
PHP
1
star
79

ddrem-iaous

Imagine Arts One's WordPress Theme. Based on ddRem.
JavaScript
1
star
80

dflydev-psr0-resource-locator-composer-service-provider

Composer PSR-0 Resource Locator Service Provider
PHP
1
star
81

dflydev-snort-textorbinary

[READ-ONLY] Subtree split of Dflydev\Snort\TextOrBinary.
PHP
1
star
82

ddknives

ddKnives WordPress Theme
PHP
1
star
83

dflydev-embedded-composer-bundle

[READ-ONLY] Subtree split of Dflydev\EmbeddedComposer\Bundle.
PHP
1
star
84

ddknives-offloc

Offloc's WordPress Theme. Based on ddKnives.
JavaScript
1
star
85

d2code-dflydev-wp-theme

d2code dflydev WordPress Theme
PHP
1
star