Skip to content

Commit

Permalink
FileStorage: Fix bug retrieving the first record
Browse files Browse the repository at this point in the history
The file pointer is positioned at the line of the previously read record.
When reading the next record, the current one is skipped. After opening
the index file, the position is zero and reading the next record then skips
the first record. The fix adds a flag that handles this corner-case.
  • Loading branch information
UlrichEckhardt committed Feb 24, 2024
1 parent deca809 commit f4e0305
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions Clockwork/Storage/FileStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class FileStorage extends Storage
// Index file handle
protected $indexHandle;

// Flag whether the first record is to be retrieved next
/** @var bool */
protected $indexInitial;

// Return new storage, takes path where to store files as argument
public function __construct($path, $pathPermissions = 0700, $expiration = null, $compress = false)
{
Expand Down Expand Up @@ -176,6 +180,7 @@ protected function openIndex($position = 'start', $lock = false, $force = false)
}

$this->indexHandle = fopen("{$this->path}/index", 'r');
$this->indexInitial = true;

if ($lock) flock($this->indexHandle, LOCK_EX);
if ($position == 'end') fseek($this->indexHandle, 0, SEEK_END);
Expand Down Expand Up @@ -236,8 +241,14 @@ protected function readNextIndex()
{
if (feof($this->indexHandle)) return;

// File pointer is always at the start of the line, call extra fgets to skip current line
fgets($this->indexHandle);
// File pointer is always at the start of the last retrieved line.
// Call an extra `fgets()` to skip current line, unless it is the
// first line actually being read.
if (!$this->indexInitial) {
fgets($this->indexHandle);
} else {
$this->indexInitial = false;
}
$line = fgets($this->indexHandle);

// Check if we read an empty line or reached the end of file
Expand Down

0 comments on commit f4e0305

Please sign in to comment.