php composer.phar require --prefer-dist jumper423/file-iterator
или
"jumper423/yfile-iterator": "*"
в файле composer.json.
$fileIterator = new \jumper423\FileIterator(__DIR__ . '/file');
$fileIterator->rewind();
$fileIterator->next();
$fileIterator->next();
$fileIterator->seek(3);
$fileIterator->next();
echo $fileIterator->current();
$fileIterator->next();
echo $fileIterator->current();
$fileIterator->seek(9);
$fileIterator->next();
$fileIterator->next();
if ($fileIterator->valid()) {
...
}
vendor/bin/phpunit
<?php
namespace jumper423;
class File
{
private static $instances = [];
public static function getInstance(string $path)
{
if (!array_key_exists($path, self::$instances)) {
self::$instances[$path] = new self($path);
}
return self::$instances[$path];
}
private $handle;
private $strings = [];
private $count;
public function __construct(string $path)
{
$this->count = 0;
$this->handle = fopen($path, "r");
$this->definitionStrings();
}
private function definitionStrings()
{
while (fgets($this->handle) !== false) {
$this->strings[] = ftell($this->handle);
++$this->count;
}
}
public function getCount(){
return $this->count;
}
public function getString(int $index) {
if ($index >= $this->getCount()) {
throw new \Exception('Not');
}
if ($index === 0){
fseek($this->handle, 0);
} else {
fseek($this->handle, $this->strings[$index - 1]);
}
return rtrim(fgets($this->handle), "\r\n");
}
}
<?php
namespace jumper423;
class FileIterator implements \SeekableIterator
{
private $position;
/**
* @var File
*/
private $file;
public function __construct($path)
{
$this->file = File::getInstance($path);
}
public function seek($position)
{
if ($position < 0 || $position >= $this->file->getCount()) {
throw new \OutOfBoundsException("invalid seek position ($position)");
}
$this->position = $position;
}
public function rewind()
{
$this->position = 0;
}
public function current()
{
return $this->file->getString($this->position);
}
public function key()
{
return $this->position;
}
public function next()
{
++$this->position;
}
public function valid()
{
return $this->position < $this->file->getCount();
}
}
Чтобы увидеть комментарии, нужно быть участником сообщества
Регистрация