germania-kg/cookie

2.1.0 2023-01-03 14:45 UTC

This package is auto-updated.

Last update: 2024-11-30 02:38:56 UTC


README

Callable wrapper around PHP's setcookie() and filter_input( INPUT_COOKIE )

Packagist PHP version Tests

Installation with Composer

$ composer require germania-kg/cookie

Getting cookies

<?php
use Germania\Cookie\CookieGetter;

// Optionally:
// have your PSR-3 Logger at hand
// or set filter type:
$getter = new CookieGetter( INPUT_COOKIE);
$getter = new CookieGetter( INPUT_COOKIE, $log);
$getter = new CookieGetter( INPUT_COOKIE, $log, \FILTER_SANITIZE_STRING);
$value = $getter( 'foo' );

Setting cookies

<?php
use Germania\Cookie\CookieSetter;

// Optional/Defaults
$defaults = [
    'path'     => '',
    'domain'   => '',
    'secure'   => true,
    'httponly' => true,
    'samesite'  => 'Lax'
];

// Optionally, have your PSR-3 Logger at hand
$setter = new CookieSetter( $defaults );
$setter = new CookieSetter( $defaults, $log);
$boolean = $setter( 'foo', 'bar', time()+3600 );

Service Providers and Dependency Injection

PHP-DI

use Germania\Cookie\Providers\PhpDiDefinitions;
use Germania\Cookie\CookieGetter;
use Germania\Cookie\CookieSetter;

$defs = new PhpDiDefinitions();
$cookie_config = [
    "path" =>     "/path/to/...",
    "secure" =>   true,
    "httponly" => true,
    'samesite'  => 'Lax'
];
$defs = new PhpDiDefinitions( $cookie_config, $psr3_logger );

// Setup PHP-DI
$builder = new \DI\ContainerBuilder();
$builder->addDefinitions( $defs->getArray() );
$container = $builder->build();


// Grab your services;
// See also above examaples.
$setter = $container->get('Cookie.Setter');
$setter = $container->get(CookieSetter::class);

$getter = $container->get('Cookie.Getter');
$getter = $container->get(CookieGetter::class);

Pimple Service Provider

<?php
use Germania\Cookie\Providers\PimpleServiceProvider;
use Psr\Log\LoggerInterface;
use Germania\Cookie\CookieGetter;
use Germania\Cookie\CookieSetter;

// have your Pimple DIC ready, and optionally a PSR3 Logger:
$sp = new PimpleServiceProvider;

$cookie_config = [
    "path" =>     "/path/to/...",
    "secure" =>   true,
    "httponly" => true,
    'samesite'  => 'Lax'
];
$sp = new PimpleServiceProvider( $cookie_config, $psr3_logger );

$sp->register( $dic );

// Grab your services;
// See also above examaples.
$setter = $dic['Cookie.Setter'];
$setter = $dic[CookieSetter::class];

$getter = $dic['Cookie.Getter'];
$getter = $dic[CookieGetter::class];

Issues

See issues list.

Development

$ git clone https://github.com/GermaniaKG/Cookie.git
$ cd Cookie
$ composer install

Unit tests

Either copy phpunit.xml.dist to phpunit.xml and adapt to your needs, or leave as is. Run PhpUnit test or composer scripts like this:

$ composer test
# or
$ vendor/bin/phpunit