for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace nebula\route\collection;
use Iterator;
use IteratorAggregate;
/**
* 逐行读文件迭代器
*
*/
class ReadLineIterator implements IteratorAggregate
{
protected $path;
protected $bufferSize;
protected $offset;
* 构建迭代器
* @param string $path 路径
* @param integer|null $offset 起始偏移
* @param integer $bufferSize
public function __construct(string $path, ?int $offset = 0, int $bufferSize = 1024)
$this->path = $path;
$this->offset = $offset;
$this->bufferSize = $bufferSize;
}
* 获取迭代器
* @return Iterator
public function getIterator():Iterator
if (file_exists($this->path) && ($fp = fopen($this->path, 'rb')) !== false) {
$offset = 0;
while (!feof($fp)) {
fseek($fp, $offset);
$content = fread($fp, $this->bufferSize);
$content.=(feof($fp))? "\n":'';
$size = strpos($content, "\n");
$offset += $size;
if ($content[$size - 1] === "\r") {
$content = substr($content, 0, $size -1);
} else {
$content = substr($content, 0, $size);
if (is_null($this->offset)) {
yield $content;
yield $offset => $content;
throw new \Exception(sprintf('readline iterator: file note exists %s', $this->path));