<?php
/**
 * User: dongdx
 * Date: 2017/9/5
 * Time: 16:23
 */

namespace PhpLife\Library;


class FileIterator extends \IteratorIterator
{
    private $fp;
    private $index = 0;
    private $line;

    public function __construct($filename)
    {
        $fp = fopen($filename, "r");
        if (!$fp) {
            die("can't open this file");
        }
        $this->fp = $fp;
        $this->line = rtrim(fgets($this->fp), "\n");
    }

    public function rewind()
    {
        $this->index = 0;
        rewind($this->fp);
        $this->line = rtrim(fgets($this->fp), "\n");
    }

    public function next()
    {
        $this->index++;
        $this->line = rtrim(fgets($this->fp), "\n");
        if (!feof($this->fp)) {
            return $this->line;
        } else {
            return null;
        }
    }

    public function key()
    {
        return $this->index;
    }

    public function current()
    {
        return $this->line;
    }

    public function valid()
    {
        return feof($this->fp) ? false : true;
    }
}