Skip to content

Commit

Permalink
Simplify Cookie Class
Browse files Browse the repository at this point in the history
  • Loading branch information
mostafakhudair committed Apr 21, 2021
1 parent 1c31da9 commit 50fa7ec
Show file tree
Hide file tree
Showing 15 changed files with 104 additions and 164 deletions.
2 changes: 1 addition & 1 deletion system/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ function config(string $name, bool $getShared = true)
*/
function cookie(string $name, string $value = '', array $options = []): Cookie
{
return Cookie::create($name, $value, $options);
return new Cookie($name, $value, $options);
}
}

Expand Down
12 changes: 4 additions & 8 deletions system/Cookie/CloneableCookieInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,15 @@ public function withValue(string $value);

/**
* Creates a new Cookie with a new cookie expires time.
*
* If $expires is equal to 0 (zero) the cookie will
* expires from the browser.
*
* @param DateTimeInterface|integer|string $expires
*
* @return static
*/
public function withExpiresAt($expires = 0);

/**
* Creates a new Cookie that will expire the cookie from the browser.
*
* @return static
*/
public function withExpired();
public function withExpires($expires = 0);

/**
* Creates a new Cookie that will virtually never expire from the browser.
Expand Down
98 changes: 21 additions & 77 deletions system/Cookie/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
* reassign this new instance to a new variable to capture it.
*
* ```php
* $cookie = Cookie::create('test_cookie', 'test_value');
* $cookie = new Cookie('test_cookie', 'test_value');
* $cookie->getName(); // test_cookie
*
* $cookie->withName('prod_cookie');
Expand Down Expand Up @@ -149,8 +149,8 @@ public static function setDefaults($config = [])
$newDefaults = $config;
}

// This array union ensures that even if passed `$config`
// is not `CookieConfig` or `array`, no empty defaults will occur.
// This array union ensures that even if passed `$config` is not
// `CookieConfig` or `array`, no empty defaults will occur.
self::$defaults = $newDefaults + $oldDefaults;

return $oldDefaults;
Expand Down Expand Up @@ -197,21 +197,19 @@ public static function fromHeaderString(string $cookie, bool $raw = false)
$data[strtolower($attr)] = $val;
}

return static::create($name, $value, $data);
return new static($name, $value, $data);
}

/**
* Create Cookie objects on the fly.
* Construct a new Cookie instance.
*
* @param string $name
* @param string $value
* @param array<string, mixed> $options
* @param string $name The cookie's name
* @param string $value The cookie's value
* @param array<string, mixed> $options The cookie's options
*
* @throws CookieException
*
* @return static
*/
public static function create(string $name, string $value = '', array $options = [])
final public function __construct(string $name, string $value = '', array $options = [])
{
$options += self::$defaults;

Expand All @@ -224,56 +222,14 @@ public static function create(string $name, string $value = '', array $options =
unset($options['max-age']);
}

return new static(
$name,
$value,
$options['expires'],
$options['prefix'],
$options['path'],
$options['domain'],
$options['secure'],
$options['httponly'],
$options['raw'],
$options['samesite']
);
}

/**
* Construct a new Cookie instance.
*
* @param string $name The name of the cookie
* @param string $value The value of the cookie
* @param DateTimeInterface|integer|string $expires The time the cookie expires
* @param string|null $prefix The prefix of the cookie
* @param string|null $path The path on the server in which the cookie is available
* @param string|null $domain The domain in which the cookie is available
* @param boolean $secure Whether to send back the cookie over HTTPS
* @param boolean $httponly Whether to forbid JavaScript access to cookies
* @param boolean $raw Whether the cookie should be sent with no URL encoding
* @param string $samesite Whether the cookie will be available for cross-site requests
*
* @throws CookieException
*/
final public function __construct(
string $name,
string $value = '',
$expires = 0,
string $prefix = null,
string $path = null,
string $domain = null,
bool $secure = false,
bool $httponly = true,
bool $raw = false,
string $samesite = self::SAMESITE_LAX
)
{
// to retain BC
$prefix = $prefix ?: self::$defaults['prefix'];
$path = $path ?: self::$defaults['path'];
$domain = $domain ?: self::$defaults['domain'];
$secure = $secure ?: self::$defaults['secure'];
$httponly = $httponly ?: self::$defaults['httponly'];
$samesite = $samesite ?: self::$defaults['samesite'];
$prefix = $options['prefix'] ?: self::$defaults['prefix'];
$path = $options['path'] ?: self::$defaults['path'];
$domain = $options['domain'] ?: self::$defaults['domain'];
$secure = $options['secure'] ?: self::$defaults['secure'];
$httponly = $options['httponly'] ?: self::$defaults['httponly'];
$samesite = $options['samesite'] ?: self::$defaults['samesite'];
$raw = $options['raw'] ?: self::$defaults['raw'];

$this->validateName($name, $raw);
$this->validatePrefix($prefix, $secure, $path, $domain);
Expand All @@ -282,7 +238,7 @@ final public function __construct(
$this->prefix = $prefix;
$this->name = $name;
$this->value = $value;
$this->expires = static::convertExpiresTimestamp($expires);
$this->expires = static::convertExpiresTimestamp($options['expires']);
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
Expand Down Expand Up @@ -354,7 +310,7 @@ public function getValue(): string
/**
* {@inheritDoc}
*/
public function getExpiresTimestamp(): int
public function getExpires(): int
{
return $this->expires;
}
Expand Down Expand Up @@ -438,7 +394,7 @@ public function isRaw(): bool
*/
public function getOptions(): array
{
// This is the order of options in `setcookie`. DO NOT change.
// This is the order of options in `setcookie`. DO NOT CHANGE.
return [
'expires' => $this->expires,
'path' => $this->path,
Expand Down Expand Up @@ -496,7 +452,7 @@ public function withValue(string $value)
/**
* {@inheritDoc}
*/
public function withExpiresAt($expires = 0)
public function withExpires($expires = 0)
{
$cookie = clone $this;

Expand All @@ -505,18 +461,6 @@ public function withExpiresAt($expires = 0)
return $cookie;
}

/**
* {@inheritDoc}
*/
public function withExpired()
{
$cookie = clone $this;

$cookie->expires = 0;

return $cookie;
}

/**
* {@inheritDoc}
*/
Expand Down Expand Up @@ -709,7 +653,7 @@ public function __toString()

$cookieHeader[] = sprintf('%s=%s', $this->getPrefixedName(), $value);

if ($this->getExpiresTimestamp() !== 0)
if ($this->getExpires() !== 0)
{
$cookieHeader[] = 'Expires=' . $this->getExpiresString();
$cookieHeader[] = 'Max-Age=' . $this->getMaxAge();
Expand Down
2 changes: 1 addition & 1 deletion system/Cookie/CookieInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public function getValue(): string;
*
* @return integer
*/
public function getExpiresTimestamp(): int;
public function getExpires(): int;

/**
* Gets the formatted expires time.
Expand Down
8 changes: 3 additions & 5 deletions system/HTTP/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -607,17 +607,15 @@ public function setCookie(
$expire = $expire > 0 ? time() + $expire : 0;
}

$options = [
$cookie = new Cookie($name, $value, [
'expires' => $expire ?: 0,
'domain' => $domain,
'path' => $path,
'prefix' => $prefix,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $samesite ?? '',
];

$cookie = Cookie::create($name, $value, $options);
]);

$this->cookieStore = $this->cookieStore->put($cookie);

Expand Down Expand Up @@ -715,7 +713,7 @@ public function deleteCookie(string $name = '', string $domain = '', string $pat
continue;
}

$cookie = $cookie->withValue('')->withExpired();
$cookie = $cookie->withValue('')->withExpires();
$found = true;

$this->cookieStore = $store->put($cookie);
Expand Down
2 changes: 1 addition & 1 deletion system/Security/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public function __construct(App $config)
$expires = $security->expires ?? $config->CSRFExpire ?? 7200;

Cookie::setDefaults($cookie);
$this->cookie = Cookie::create($rawCookieName, $this->generateHash(), [
$this->cookie = new Cookie($rawCookieName, $this->generateHash(), [
'expires' => $expires === 0 ? 0 : time() + $expires,
]);
}
Expand Down
4 changes: 2 additions & 2 deletions system/Session/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public function __construct(SessionHandlerInterface $driver, App $config)
*/
$config = config('Cookie');

$this->cookie = Cookie::create($this->sessionCookieName, '', [
$this->cookie = new Cookie($this->sessionCookieName, '', [
'expires' => $this->sessionExpiration === 0 ? 0 : time() + $this->sessionExpiration,
'path' => $config->path,
'domain' => $config->domain,
Expand Down Expand Up @@ -1009,7 +1009,7 @@ protected function startSession()
protected function setCookie()
{
$expiration = $this->sessionExpiration === 0 ? 0 : time() + $this->sessionExpiration;
$this->cookie = $this->cookie->withValue(session_id())->withExpiresAt($expiration);
$this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration);

cookies([$this->cookie], false)->dispatch();
}
Expand Down
2 changes: 1 addition & 1 deletion system/Test/Mock/MockSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ protected function startSession()
protected function setCookie()
{
$expiration = $this->sessionExpiration === 0 ? 0 : time() + $this->sessionExpiration;
$this->cookie = $this->cookie->withValue(session_id())->withExpiresAt($expiration);
$this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration);

$this->cookies[] = $this->cookie;
}
Expand Down
2 changes: 1 addition & 1 deletion system/Test/TestResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ public function assertCookieMissing(string $key)
public function assertCookieExpired(string $key, string $prefix = '')
{
$this->assertTrue($this->response->hasCookie($key, null, $prefix));
$this->assertGreaterThan(time(), $this->response->getCookie($key, $prefix)->getExpiresTimestamp());
$this->assertGreaterThan(time(), $this->response->getCookie($key, $prefix)->getExpires());
}

//--------------------------------------------------------------------
Expand Down
14 changes: 7 additions & 7 deletions tests/system/Cookie/CookieStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ protected function tearDown(): void
public function testCookieStoreInitialization(): void
{
$cookies = [
Cookie::create('dev', 'cookie'),
Cookie::create('prod', 'cookie', ['raw' => true]),
new Cookie('dev', 'cookie'),
new Cookie('prod', 'cookie', ['raw' => true]),
];

$store = new CookieStore($cookies);
Expand Down Expand Up @@ -76,12 +76,12 @@ public function testInvalidCookieStored(): void
public function testPutRemoveCookiesInStore(): void
{
$cookies = [
Cookie::create('dev', 'cookie'),
Cookie::create('prod', 'cookie', ['raw' => true]),
new Cookie('dev', 'cookie'),
new Cookie('prod', 'cookie', ['raw' => true]),
];

$store = new CookieStore($cookies);
$bottle = $store->put(Cookie::create('test', 'cookie'));
$bottle = $store->put(new Cookie('test', 'cookie'));
$jar = $store->remove('dev');

$this->assertNotSame($store->display(), $bottle->display());
Expand All @@ -94,8 +94,8 @@ public function testPutRemoveCookiesInStore(): void
public function testCookieDispatching(): void
{
$cookies = [
'dev' => Cookie::create('dev', 'cookie'),
'prod' => Cookie::create('prod', 'cookie', ['raw' => true]),
'dev' => new Cookie('dev', 'cookie'),
'prod' => new Cookie('prod', 'cookie', ['raw' => true]),
];

$dev = $cookies['dev']->getOptions();
Expand Down
Loading

0 comments on commit 50fa7ec

Please sign in to comment.