Skip to content

Commit

Permalink
Add isExpired() to Cookie.
Browse files Browse the repository at this point in the history
This will make comparison logic simpler in consumers of this class.
  • Loading branch information
markstory committed Apr 11, 2017
1 parent b6ad881 commit 9310ee7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 17 deletions.
52 changes: 35 additions & 17 deletions src/Http/Cookie/Cookie.php
Expand Up @@ -174,23 +174,6 @@ protected function getFormattedExpires()
return $this->expiresAt->format(static::EXPIRES_FORMAT);
}

/**
* Get the timestamp from the expiration time
*
* Timestamps are strings as large timestamps can overflow MAX_INT
* in 32bit systems.
*
* @return string|null The expiry time as a string timestamp.
*/
public function getExpiresTimestamp()
{
if (!$this->expiresAt) {
return null;
}

return $this->expiresAt->format('U');
}

/**
* Returns a header value as string
*
Expand Down Expand Up @@ -477,6 +460,41 @@ public function getExpiry()
return $this->expiresAt;
}

/**
* Get the timestamp from the expiration time
*
* Timestamps are strings as large timestamps can overflow MAX_INT
* in 32bit systems.
*
* @return string|null The expiry time as a string timestamp.
*/
public function getExpiresTimestamp()
{
if (!$this->expiresAt) {
return null;
}

return $this->expiresAt->format('U');
}

/**
* Check if a cookie is expired when compared to $time
*
* Cookies without an expiration date always return false.
*
* @param \DatetimeInterface $time The time to test against. Defaults to 'now' in UTC.
* @return bool
*/
public function isExpired(DatetimeInterface $time = null)
{
$time = $time ?: new DateTimeImmutable('now', new DateTimezone('UTC'));
if (!$this->expiresAt) {
return false;
}

return $this->expiresAt < $time;
}

/**
* Create a new cookie that will virtually never expire.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/Http/Cookie/CookieTest.php
Expand Up @@ -375,6 +375,27 @@ public function testWithExpiryChangesTimezone()
$this->assertSame($date->format('U'), $new->getExpiresTimestamp());
}

/**
* Test the isExpired method
*
* @return void
*/
public function testIsExpired()
{
$date = Chronos::now();
$cookie = new Cookie('cakephp', 'yay');
$this->assertFalse($cookie->isExpired($date));

$cookie = new Cookie('cakephp', 'yay', $date);
$this->assertFalse($cookie->isExpired($date), 'same time, not expired');

$date = $date->modify('+10 seconds');
$this->assertTrue($cookie->isExpired($date), 'future now');

$date = $date->modify('-1 minute');
$this->assertFalse($cookie->isExpired($date), 'expires later');
}

/**
* Test the withName method
*
Expand Down

0 comments on commit 9310ee7

Please sign in to comment.