php-spark/plugins/com.noccy.apiclient/Log/LogIterator.php
Christopher Vagnetoft 9050c74a08 Plugin fixes
* Added vertical rendering to com.noccy.pdo.shell
* Added missing Log classes for com.noccy.apiclient
2021-12-22 03:03:16 +01:00

80 lines
1.7 KiB
PHP

<?php
namespace SparkPlug\Com\Noccy\ApiClient\Log;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface;
use SparkPlug\Com\Noccy\ApiClient\Log\RequestData as LogRequestData;
use SparkPlug\Com\Noccy\ApiClient\Request\Request;
class LogIterator implements \Iterator
{
private ?string $lastLog = null;
private string $filename;
private array $log = [];
private ?int $index = null;
private ?int $lindex = null;
public function __construct(string $logfile)
{
$this->filename = $logfile;
}
private function readLog(string $filename)
{
if (!file_exists($filename)) {
$this->lastLog = null;
$this->log = [];
$this->index = null;
$this->lindex = null;
return;
}
$log = json_decode(file_get_contents($filename), true);
$this->lastLog = $log['lastlog']??null;
$this->log = $log['events'];
$this->lindex = 0;
if ($this->index === null) {
$this->index = 0;
}
}
public function rewind(): void
{
$this->index = null;
$this->readLog($this->filename);
}
public function current()
{
return $this->log[$this->lindex];
}
public function key()
{
return $this->index;
}
public function next(): void
{
$this->index++;
$this->lindex++;
if ($this->lindex >= count($this->log)) {
if ($this->lastLog) {
$this->readLog($this->lastLog);
} else {
$this->lindex = null;
}
}
}
public function valid(): bool
{
return $this->lindex !== null;
}
}