Skip to content

Commit

Permalink
Killing time()
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonkelly committed Dec 15, 2024
1 parent 2df06c0 commit f2786e7
Show file tree
Hide file tree
Showing 17 changed files with 82 additions and 47 deletions.
3 changes: 2 additions & 1 deletion src/Craft.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\Component;
use craft\helpers\DateTimeHelper;
use craft\helpers\FileHelper;
use craft\helpers\StringHelper;
use GuzzleHttp\Client;
Expand Down Expand Up @@ -334,7 +335,7 @@ private static function _generateCustomFieldBehavior(array $fieldHandles, ?strin

// Delete any CustomFieldBehavior files that are over 10 seconds old
$basename = basename($filePath);
$time = time() - 10;
$time = DateTimeHelper::currentTimeStamp() - 10;
FileHelper::clearDirectory($dir, [
'filter' => function(string $path) use ($basename, $time): bool {
$b = basename($path);
Expand Down
5 changes: 3 additions & 2 deletions src/cache/DbCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Craft;
use craft\db\Connection;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use Exception;
use PDO;
Expand Down Expand Up @@ -60,7 +61,7 @@ protected function setValue($key, $value, $duration): bool
$this->db->noCache(function(Connection $db) use ($key, $value, $duration) {
Db::upsert($this->cacheTable, [
'id' => $key,
'expire' => $duration > 0 ? $duration + time() : 0,
'expire' => $duration > 0 ? DateTimeHelper::currentTimeStamp() + $duration : 0,
'data' => new PdoValue($value, PDO::PARAM_LOB),
], db: $db);
});
Expand All @@ -83,7 +84,7 @@ protected function addValue($key, $value, $duration): bool
$this->db->noCache(function(Connection $db) use ($key, $value, $duration) {
Db::insert($this->cacheTable, [
'id' => $key,
'expire' => $duration > 0 ? $duration + time() : 0,
'expire' => $duration > 0 ? DateTimeHelper::currentTimeStamp() + $duration : 0,
'data' => new PdoValue($value, PDO::PARAM_LOB),
], $db);
});
Expand Down
3 changes: 2 additions & 1 deletion src/console/controllers/ProjectConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use craft\console\Controller;
use craft\events\ConfigEvent;
use craft\helpers\Console;
use craft\helpers\DateTimeHelper;
use craft\helpers\FileHelper;
use craft\helpers\ProjectConfig;
use craft\services\ProjectConfig as ProjectConfigService;
Expand Down Expand Up @@ -459,7 +460,7 @@ public function actionRebuild(): int
*/
public function actionTouch(): int
{
$time = time();
$time = DateTimeHelper::currentTimeStamp();
ProjectConfig::touch($time);
$this->stdout("The dateModified value in project.yaml is now set to $time." . PHP_EOL, Console::FG_GREEN);
return ExitCode::OK;
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public static function processResponseHeaders(array $headers): void
) {
$timestamp = $oldLicenseInfo[$handle]['timestamp'];
} else {
$timestamp = time();
$timestamp = DateTimeHelper::currentTimeStamp();
}
}
$licenseInfo[$handle] = [
Expand Down
8 changes: 2 additions & 6 deletions src/helpers/DateTimeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -524,9 +524,7 @@ public static function currentUTCDateTime(): DateTime
*/
public static function currentTimeStamp(): int
{
$date = static::currentUTCDateTime();

return $date->getTimestamp();
return static::now()->getTimestamp();
}

/**
Expand Down Expand Up @@ -671,9 +669,7 @@ public static function isWithinLast(mixed $date, mixed $timeInterval): bool
*/
public static function isInThePast(mixed $date): bool
{
$date = static::toDateTime($date);

return $date->getTimestamp() < time();
return static::toDateTime($date)->getTimestamp() < static::currentTimeStamp();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/ProjectConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ public static function diff(bool $invert = false): string
public static function touch(?int $timestamp = null): void
{
if ($timestamp === null) {
$timestamp = time();
$timestamp = DateTimeHelper::currentTimeStamp();
}

$timestampLine = "dateModified: $timestamp\n";
Expand Down
3 changes: 2 additions & 1 deletion src/models/ImageTransformIndex.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use craft\base\imagetransforms\ImageTransformerInterface;
use craft\base\Model;
use craft\helpers\DateTimeHelper;
use craft\helpers\ImageTransforms;
use craft\validators\DateTimeValidator;
use DateTime;
Expand Down Expand Up @@ -102,7 +103,7 @@ public function init(): void

// Only respect inProgress if it's been less than 30 seconds since the last time the index was updated
if ($this->inProgress) {
$duration = time() - ($this->dateUpdated?->getTimestamp() ?? 0);
$duration = DateTimeHelper::currentTimeStamp() - ($this->dateUpdated?->getTimestamp() ?? 0);
if ($duration > 30) {
$this->inProgress = false;
}
Expand Down
26 changes: 18 additions & 8 deletions src/queue/Queue.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use craft\errors\MutexException;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Json;
use craft\helpers\Queue as QueueHelper;
Expand Down Expand Up @@ -381,7 +382,7 @@ public function setProgress(int $progress, ?string $label = null): void
$this->_lock(function() use ($progress, $label) {
$data = [
'progress' => $progress,
'timeUpdated' => time(),
'timeUpdated' => DateTimeHelper::currentTimeStamp(),
];

if ($label !== null) {
Expand Down Expand Up @@ -546,7 +547,9 @@ public function getJobInfo(?int $limit = null): array
// then running first
->addOrderBy(new Expression("CASE WHEN $runningSql THEN 1 ELSE 0 END DESC"))
// then earliest start time (now or timePushed + delay)
->addOrderBy(new Expression('GREATEST(:time, [[timePushed]] + [[delay]]) ASC', [':time' => time()]))
->addOrderBy(new Expression('GREATEST(:time, [[timePushed]] + [[delay]]) ASC', [
':time' => DateTimeHelper::currentTimeStamp(),
]))
// then priority and ID
->addOrderBy(['priority' => SORT_ASC, 'id' => SORT_ASC])
->limit($limit);
Expand Down Expand Up @@ -661,7 +664,7 @@ protected function pushMessage($message, $ttr, $delay, $priority): string
'channel' => $this->channel(),
'job' => $message,
'description' => $this->_jobDescription,
'timePushed' => time(),
'timePushed' => DateTimeHelper::currentTimeStamp(),
'ttr' => $ttr,
'delay' => $delay,
'priority' => $priority ?: 1024,
Expand Down Expand Up @@ -733,7 +736,9 @@ protected function reserve(?string $id = null): ?array
$payload = $this->db->usePrimary(function() use ($id) {
$query = $this->_createJobQuery()
->andWhere(['fail' => false, 'timeUpdated' => null])
->andWhere('[[timePushed]] + [[delay]] <= :time', ['time' => time()])
->andWhere('[[timePushed]] + [[delay]] <= :time', [
'time' => DateTimeHelper::currentTimeStamp(),
])
->orderBy(['priority' => SORT_ASC, 'id' => SORT_ASC])
->limit(1);

Expand Down Expand Up @@ -793,8 +798,9 @@ private function _jobData(mixed $job): string
*/
private function _moveExpired(): void
{
if ($this->_reserveTime !== time()) {
$this->_reserveTime = time();
$timestamp = DateTimeHelper::currentTimeStamp();
if ($this->_reserveTime !== $timestamp) {
$this->_reserveTime = $timestamp;

$expiredIds = $this->db->usePrimary(function() {
return (new Query())
Expand Down Expand Up @@ -856,7 +862,9 @@ private function _createWaitingJobQuery(): Query
{
return $this->_createJobQuery()
->andWhere(['fail' => false, 'timeUpdated' => null])
->andWhere('[[timePushed]] + [[delay]] <= :time', ['time' => time()]);
->andWhere('[[timePushed]] + [[delay]] <= :time', [
'time' => DateTimeHelper::currentTimeStamp(),
]);
}

/**
Expand All @@ -868,7 +876,9 @@ private function _createDelayedJobQuery(): Query
{
return $this->_createJobQuery()
->andWhere(['fail' => false, 'timeUpdated' => null])
->andWhere('[[timePushed]] + [[delay]] > :time', ['time' => time()]);
->andWhere('[[timePushed]] + [[delay]] > :time', [
'time' => DateTimeHelper::currentTimeStamp(),
]);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/services/Elements.php
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ public function setCacheExpiryDate(DateTime $expiryDate): void
return;
}

$duration = $expiryDate->getTimestamp() - time();
$duration = $expiryDate->getTimestamp() - DateTimeHelper::currentTimeStamp();

if ($duration > 0 && (!$this->_cacheDuration || $duration < $this->_cacheDuration)) {
$this->_cacheDuration = $duration;
Expand Down
3 changes: 2 additions & 1 deletion src/services/Fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
use craft\fields\Users as UsersField;
use craft\helpers\ArrayHelper;
use craft\helpers\Component as ComponentHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\ElementHelper;
use craft\helpers\FieldHelper;
Expand Down Expand Up @@ -1840,7 +1841,7 @@ private function _backupFieldColumn(Connection $db, string $table, string $colum
$shortTableName = Db::rawTableShortName($table);
$schema = $db->getSchema();
$prefix = "{$shortTableName}_$column";
$timestamp = time();
$timestamp = DateTimeHelper::currentTimeStamp();
$n = 1;
do {
$suffix = $n === 1 ? '' : "_$n";
Expand Down
2 changes: 1 addition & 1 deletion src/services/TemplateCaches.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ public function endTemplateCache(string $key, bool $global, ?string $duration, m
$expiration = (new DateTime($duration));
}
if ($expiration !== null) {
$duration = DateTimeHelper::toDateTime($expiration)->getTimestamp() - time();
$duration = DateTimeHelper::toDateTime($expiration)->getTimestamp() - DateTimeHelper::currentTimeStamp();
}

if ($duration <= 0) {
Expand Down
4 changes: 3 additions & 1 deletion src/web/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Craft;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Session;
use craft\helpers\UrlHelper;
use Throwable;
Expand Down Expand Up @@ -122,7 +123,8 @@ public function setCacheHeaders(int $duration = 31536000, bool $overwrite = true
return $this;
}

$this->setHeader('Expires', sprintf('%s GMT', gmdate('D, d M Y H:i:s', time() + $duration)), $overwrite);
$expires = DateTimeHelper::currentTimeStamp() + $duration;
$this->setHeader('Expires', sprintf('%s GMT', gmdate('D, d M Y H:i:s', $expires)), $overwrite);
$this->setHeader('Pragma', 'cache', $overwrite);
$this->setHeader('Cache-Control', "public, max-age=$duration", $overwrite);
return $this;
Expand Down
9 changes: 5 additions & 4 deletions src/web/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use craft\errors\UserLockedException;
use craft\events\LoginFailureEvent;
use craft\helpers\ConfigHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Session as SessionHelper;
use craft\helpers\UrlHelper;
Expand Down Expand Up @@ -99,7 +100,7 @@ public function sendUsernameCookie(UserElement $user): void
$cookie = new Cookie($this->usernameCookie);
$cookie->value = $user->username;
$seconds = ConfigHelper::durationInSeconds($generalConfig->rememberUsernameDuration);
$cookie->expire = time() + $seconds;
$cookie->expire = DateTimeHelper::currentTimeStamp() + $seconds;
Craft::$app->getResponse()->getCookies()->add($cookie);
} else {
Craft::$app->getResponse()->getCookies()->remove(new Cookie($this->usernameCookie));
Expand Down Expand Up @@ -234,7 +235,7 @@ public function getRemainingSessionTime(): int
}

$expire = SessionHelper::get($this->authTimeoutParam);
$time = time();
$time = DateTimeHelper::currentTimeStamp();

if ($expire !== null && $expire > $time) {
return $expire - $time;
Expand Down Expand Up @@ -285,7 +286,7 @@ public function getElevatedSessionTimeout(): int|false
$expires = SessionHelper::get($this->elevatedSessionTimeoutParam);

if ($expires !== null) {
$currentTime = time();
$currentTime = DateTimeHelper::currentTimeStamp();

if ($expires > $currentTime) {
return $expires - $currentTime;
Expand Down Expand Up @@ -364,7 +365,7 @@ public function startElevatedSession(string $password): bool
}

// Set the elevated session expiration date
$timeout = time() + $generalConfig->elevatedSessionDuration;
$timeout = DateTimeHelper::currentTimeStamp() + $generalConfig->elevatedSessionDuration;
SessionHelper::set($this->elevatedSessionTimeoutParam, $timeout);

return true;
Expand Down
6 changes: 5 additions & 1 deletion src/web/twig/nodes/ExpiresNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ public function compile(Compiler $compiler): void
->write('$expiration = ')
->subcompile($expiration)
->raw(";\n")
->write('$duration = \craft\helpers\DateTimeHelper::toDateTime($expiration)->getTimestamp() - time();');
->write(sprintf(
'$duration = %s::toDateTime($expiration)->getTimestamp() - %s::currentTimeStamp();',
DateTimeHelper::class,
DateTimeHelper::class,
));
} else {
$duration = DateTimeHelper::relativeTimeToSeconds(
$this->getAttribute('durationNum'),
Expand Down
8 changes: 5 additions & 3 deletions tests/unit/helpers/ProjectConfigHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
namespace crafttests\unit\helpers;

use Craft;
use craft\helpers\DateTimeHelper;
use craft\helpers\FileHelper;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
Expand Down Expand Up @@ -68,10 +69,11 @@ public function testTouch(string $input, string $expected): void
FileHelper::writeToFile($path, $input);

// Test
$timestamp = time();
$expected = str_replace('__TIMESTAMP__', (string)$timestamp, $expected);
ProjectConfigHelper::touch($timestamp);
DateTimeHelper::pause();
$expected = str_replace('__TIMESTAMP__', (string)DateTimeHelper::currentTimeStamp(), $expected);
ProjectConfigHelper::touch();
self::assertSame($expected, file_get_contents($path));
DateTimeHelper::resume();

// Put the old project.yaml back
FileHelper::unlink($path);
Expand Down
8 changes: 5 additions & 3 deletions tests/unit/web/ResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
namespace crafttests\unit\web;

use Codeception\Test\Unit;
use craft\helpers\DateTimeHelper;
use craft\test\TestCase;
use craft\web\Response;

Expand Down Expand Up @@ -47,15 +48,16 @@ public function testGetContentType(?string $expected, ?string $format = null, ?s
*/
public function testSetCacheHeaders(): void
{
DateTimeHelper::pause();
$this->response->setCacheHeaders();
$headers = $this->response->getHeaders();

$cacheTime = 31536000; // 1 year

self::assertSame('cache', $headers->get('Pragma'));
self::assertSame('cache', $headers->get('Pragma'));
self::assertSame('public, max-age=31536000', $headers->get('Cache-Control'));
self::assertSame(gmdate('D, d M Y H:i:s', time() + $cacheTime) . ' GMT', $headers->get('Expires'));
$expectedExpires = DateTimeHelper::currentTimeStamp() + $cacheTime;
self::assertSame(gmdate('D, d M Y H:i:s', $expectedExpires) . ' GMT', $headers->get('Expires'));
DateTimeHelper::resume();
}

/**
Expand Down
Loading

0 comments on commit f2786e7

Please sign in to comment.