Cookie example

$this->assertEquals('Request: /', $client->getResponse()->getContent(), '->getScript() returns a script that uses the request handler to make the request');
    }

    public function testFilterResponseConvertsCookies()
    {
        $client = new HttpKernelBrowser(new TestHttpKernel());

        $r = new \ReflectionObject($client);
        $m = $r->getMethod('filterResponse');

        $response = new Response();
        $response->headers->setCookie($cookie1 = new Cookie('foo', 'bar', \DateTimeImmutable::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true, false, null));
        $domResponse = $m->invoke($client$response);
        $this->assertSame((string) $cookie1$domResponse->getHeader('Set-Cookie'));

        $response = new Response();
        $response->headers->setCookie($cookie1 = new Cookie('foo', 'bar', \DateTimeImmutable::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true, false, null));
        $response->headers->setCookie($cookie2 = new Cookie('foo1', 'bar1', \DateTimeImmutable::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true, false, null));
        $domResponse = $m->invoke($client$response);
        $this->assertSame((string) $cookie1$domResponse->getHeader('Set-Cookie'));
        $this->assertSame([(string) $cookie1(string) $cookie2]$domResponse->getHeader('Set-Cookie', false));
    }

    

    protected function createCookie(?RememberMeDetails $rememberMeDetails)
    {
        $request = $this->requestStack->getMainRequest();
        if (!$request) {
            throw new \LogicException('Cannot create the remember-me cookie; no master request available.');
        }

        // the ResponseListener configures the cookie saved in this attribute on the final response object         $request->attributes->set(ResponseListener::COOKIE_ATTR_NAME, new Cookie(
            $this->options['name'],
            $rememberMeDetails?->toString(),
            $rememberMeDetails?->getExpires() ?? 1,
            $this->options['path'],
            $this->options['domain'],
            $this->options['secure'] ?? $request->isSecure(),
            $this->options['httponly'],
            false,
            $this->options['samesite']
        ));
    }
}
<?php
use Symfony\Component\HttpFoundation\Cookie;

$r = require __DIR__.'/common.inc';

try {
    $r->headers->setCookie(new Cookie('Hello + world', 'hodor', 0, null, null, null, false, true));
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage();
}
/** * Tests copying of redirect response. * * @covers ::createFromRedirectResponse * @covers ::fromResponse */
  public function testRedirectCopy() {
    $redirect = new RedirectResponse('/magic_redirect_url', 301, ['x-cache-foobar' => 123]);
    $redirect->setProtocolVersion('2.0');
    $redirect->setCharset('ibm-943_P14A-2000');
    $redirect->headers->setCookie(new Cookie('name', 'value', 0, '/', NULL, FALSE, TRUE, FALSE, NULL));

    // Make a cloned redirect.     $secureRedirect = SecuredRedirectStub::createFromRedirectResponse($redirect);
    $this->assertEquals('/magic_redirect_url', $secureRedirect->getTargetUrl());
    $this->assertEquals(301, $secureRedirect->getStatusCode());
    // We pull the headers from the original redirect because there are default headers applied.     $headers1 = $redirect->headers->allPreserveCase();
    $headers2 = $secureRedirect->headers->allPreserveCase();
    // We unset cache headers so we don't test arcane Symfony weirdness.     // https://github.com/symfony/symfony/issues/16171     unset($headers1['Cache-Control']$headers2['Cache-Control']);
    
return $flattenedCookies;
    }

    /** * Clears a cookie in the browser. * * @return void */
    public function clearCookie(string $name, ?string $path = '/', string $domain = null, bool $secure = false, bool $httpOnly = true, string $sameSite = null)
    {
        $this->setCookie(new Cookie($name, null, 1, $path$domain$secure$httpOnly, false, $sameSite));
    }

    /** * @see HeaderUtils::makeDisposition() * * @return string */
    public function makeDisposition(string $disposition, string $filename, string $filenameFallback = '')
    {
        return HeaderUtils::makeDisposition($disposition$filename$filenameFallback);
    }

    
namespace Symfony\Component\BrowserKit\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\Exception\InvalidArgumentException;
use Symfony\Component\BrowserKit\Exception\UnexpectedValueException;

class CookieTest extends TestCase
{
    public function testToString()
    {
        $cookie = new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
        $this->assertEquals('foo=bar; expires=Fri, 20 May 2011 15:25:52 GMT; domain=.myfoodomain.com; path=/; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie');

        $cookie = new Cookie('foo', 'bar with white spaces', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
        $this->assertEquals('foo=bar%20with%20white%20spaces; expires=Fri, 20 May 2011 15:25:52 GMT; domain=.myfoodomain.com; path=/; secure; httponly', (string) $cookie, '->__toString() encodes the value of the cookie according to RFC 3986 (white space = %20)');

        $cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com');
        $this->assertEquals('foo=; expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=.myfoodomain.com; path=/admin/; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL');

        $cookie = new Cookie('foo', 'bar', 0, '/', '');
        $this->assertEquals('foo=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; httponly', (string) $cookie);

        
public function testFromStringWithHttpOnly()
    {
        $cookie = Cookie::fromString('foo=bar; expires=Fri, 20 May 2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly');
        $this->assertTrue($cookie->isHttpOnly());

        $cookie = Cookie::fromString('foo=bar; expires=Fri, 20 May 2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure');
        $this->assertFalse($cookie->isHttpOnly());
    }

    public function testSameSiteAttribute()
    {
        $cookie = new Cookie('foo', 'bar', 0, '/', null, false, true, false, 'Lax');
        $this->assertEquals('lax', $cookie->getSameSite());

        $cookie = new Cookie('foo', 'bar', 0, '/', null, false, true, false, '');
        $this->assertNull($cookie->getSameSite());

        $cookie = Cookie::create('foo')->withSameSite('Lax');
        $this->assertEquals('lax', $cookie->getSameSite());
    }

    public function testSetSecureDefault()
    {
        
$request->getSession()->start();

        return $request;
    }

    protected function createResponse()
    {
        $response = new Response();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/json');
        $response->headers->set('X-Foo-Bar', null);
        $response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true, false, null));
        $response->headers->setCookie(new Cookie('bar', 'foo', new \DateTimeImmutable('@946684800'), '/', null, false, true, false, null));
        $response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12', '/', null, false, true, false, null));

        return $response;
    }

    /** * Inject the given controller callable into the data collector. */
    protected function injectController($collector$controller$request)
    {
        

    public function testCreateResponse(PsrHttpFactory $factory)
    {
        $response = new Response(
            'Response content.',
            202,
            [
                'X-Symfony' => ['3.4'],
                ' X-Broken-Header' => 'abc',
            ]
        );
        $response->headers->setCookie(new Cookie('city', 'Lille', new \DateTime('Wed, 13 Jan 2021 22:23:01 GMT'), '/', null, false, true, false, 'lax'));

        $psrResponse = $factory->createResponse($response);
        $this->assertSame('Response content.', $psrResponse->getBody()->__toString());
        $this->assertSame(202, $psrResponse->getStatusCode());
        $this->assertSame(['3.4']$psrResponse->getHeader('x-symfony'));
        $this->assertFalse($psrResponse->hasHeader(' X-Broken-Header'));
        $this->assertFalse($psrResponse->hasHeader('X-Broken-Header'));

        $cookieHeader = $psrResponse->getHeader('Set-Cookie');
        $this->assertIsArray($cookieHeader);
        $this->assertCount(1, $cookieHeader);
        
return $flattenedCookies;
    }

    /** * Clears a cookie in the browser. * * @return void */
    public function clearCookie(string $name, ?string $path = '/', string $domain = null, bool $secure = false, bool $httpOnly = true, string $sameSite = null)
    {
        $this->setCookie(new Cookie($name, null, 1, $path$domain$secure$httpOnly, false, $sameSite));
    }

    /** * @see HeaderUtils::makeDisposition() * * @return string */
    public function makeDisposition(string $disposition, string $filename, string $filenameFallback = '')
    {
        return HeaderUtils::makeDisposition($disposition$filename$filenameFallback);
    }

    
public static function normalize_cookies( $cookies ) {
        $cookie_jar = new WpOrg\Requests\Cookie\Jar();

        foreach ( $cookies as $name => $value ) {
            if ( $value instanceof WP_Http_Cookie ) {
                $attributes                 = array_filter(
                    $value->get_attributes(),
                    static function( $attr ) {
                        return null !== $attr;
                    }
                );
                $cookie_jar[ $value->name ] = new WpOrg\Requests\Cookie( $value->name, $value->value, $attributes, array( 'host-only' => $value->host_only ) );
            } elseif ( is_scalar( $value ) ) {
                $cookie_jar[ $name ] = new WpOrg\Requests\Cookie( $name(string) $value );
            }
        }

        return $cookie_jar;
    }

    /** * Match redirect behavior to browser handling. * * Changes 302 redirects from POST to GET to match browser handling. Per * RFC 7231, user agents can deviate from the strict reading of the * specification for compatibility purposes. * * @since 4.6.0 * * @param string $location URL to redirect to. * @param array $headers Headers for the redirect. * @param string|array $data Body to send with the request. * @param array $options Redirect request options. * @param WpOrg\Requests\Response $original Response object. */
<?php
use Symfony\Component\HttpFoundation\Cookie;

$r = require __DIR__.'/common.inc';

$str1 = "=,; \t\r\n\v\f";
$r->headers->setCookie(new Cookie($str1$str1, 0, '', null, false, false, false, null));

$str2 = '?*():@&+$/%#[]';

$r->headers->setCookie(new Cookie($str2$str2, 0, '', null, false, false, false, null));
$r->sendHeaders();

setcookie($str2$str2, 0, '/');
<?php
use Symfony\Component\HttpFoundation\Cookie;

$r = require __DIR__.'/common.inc';

$r->headers->setCookie(new Cookie('CookieSamesiteStrictTest', 'StrictValue', 0, '/', null, false, true, false, Cookie::SAMESITE_STRICT));
$r->sendHeaders();

        $client = $this->createMock(KernelBrowser::class);
        $client->expects($this->any())->method('getCrawler')->willReturn($crawler);

        return $this->getTester($client);
    }

    private function getClientTester(): WebTestCase
    {
        $client = $this->createMock(KernelBrowser::class);
        $jar = new CookieJar();
        $jar->set(new Cookie('foo', 'bar', null, '/path', 'example.com'));
        $client->expects($this->any())->method('getCookieJar')->willReturn($jar);

        return $this->getTester($client);
    }

    private function getRequestTester(): WebTestCase
    {
        $client = $this->createMock(KernelBrowser::class);
        $request = new Request();
        $request->attributes->set('foo', 'bar');
        $request->attributes->set('_route', 'homepage');
        
if ('samesite' === strtolower($name) && null !== $value) {
                $samesite = $value;

                continue;
            }
        }

        if (!isset($cookieName)) {
            throw new \InvalidArgumentException('The value of the Set-Cookie header is malformed.');
        }

        return new Cookie(
            $cookieName,
            $cookieValue,
            $cookieExpire ?? 0,
            $cookiePath ?? '/',
            $cookieDomain ?? null,
            isset($cookieSecure),
            isset($cookieHttpOnly),
            true,
            $samesite ?? null
        );
    }

    
Home | Imprint | This part of the site doesn't use cookies.