<?php
/**
 * Link         :   http://www.phpcorner.net
 * User         :   qingbing<780042175@qq.com>
 * Date         :   2018-12-10
 * Version      :   1.0
 */

namespace Helper;

/**
 * 实现该类，对象将可以像数组一样拥有遍历功能（可以自定定义遍历或使用foreach）
 * $obj->current(); 对应使用 \Iterator.current() : 返回当前所在游标对象
 * $obj->next(); 对应使用 \Iterator.next() : 将对象游标向下移位
 * $obj->key(); 对应使用 \Iterator.key() : 返回当前所在游标
 * $obj->valid(); 对应使用 \Iterator.valid() : 返回当前游标是否有效
 * $obj->rewind(); 对应使用 \Iterator.rewind() : 将游标重置到开始位置
 *
 * Class CListIterator
 * @package Helper
 */
class CListIterator implements \Iterator
{
    private $_items;
    private $_index;

    /**
     * CListIterator constructor.
     * @param array $data
     */
    public function __construct(&$data)
    {
        $this->_items =& $data;
        $this->_index = 0;
    }

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current()
    {
        return $this->_items[$this->_index];
    }

    /**
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next()
    {
        $this->_index++;
    }

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key()
    {
        return $this->_index;
    }

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid()
    {
        return $this->_index < count($this->_items);
    }

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind()
    {
        $this->_index = 0;
    }
}