<?php
namespace App\EntityList;

/**
 * Iterator that expects an $ADORecordSet result as input(the result from the $db->Execute()) and will instatiate an entity for each row received from the DB
 * The implementation of this class is specific to the ADODB internals, we should write another iterator specific to the PDO classes in the future
 * @author Lucian Sirbu
 */
class RecordIterator implements \Iterator
{
	private $recordSet = 		null;
	private $position = 		0;
	private $entity = 			"";

	/**
	 * Initialize this iterator
	 * @param \ADORecordSet $recordSet
	 */
	public function __construct( $recordSet, $entity )
	{
		$this->recordSet = 	$recordSet;
		$this->position = 	0;
		$this->entity =  	$entity;
	}

	/**
	 * Reset the iterator. Should be called only once, when the foreach loop starts
	 */
	public function rewind() :void
	{
		$this->position = 		0;
	}

	/**
	 * Get the current entity
	 * @return multitype:NULL boolean
	 */
	public function current() :mixed
	{
		$ret = $this->recordSet->fields;
		$ret['entity'] = call_user_func([$this->entity, "select"], $this->recordSet->fields['id']);
		return $ret;
	}

	/**
	 * Get the current index
	 * @return number
	 */
	public function key() :mixed
	{
		return $this->position;
	}

	/**
	 * Advance the iterator to the next element in the list
	 * @return boolean
	 */
	public function next() :void
	{
		$this->position++;
		$this->recordSet->MoveNext();
	}

	/**
	 * Check if the iterator should be stopped
	 * @return boolean
	 */
	public function valid() :bool
	{
		return !$this->recordSet->EOF;
	}
}

