Skip to content

Instantly share code, notes, and snippets.

@hijarian
Created March 10, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hijarian/4a3b631f7c3e8e68b715 to your computer and use it in GitHub Desktop.
Save hijarian/4a3b631f7c3e8e68b715 to your computer and use it in GitHub Desktop.
Countable iterator and MongoDataModelGenerator
interface CountableIterator extends \Iterator, \Countable { }
class MongoDataModelGenerator implements CountableIterator
{
/** @var MongoCursor */
private $cursor;
/**
* This should be the function accepting array representing mongo document from MongoCursor and returning something else based on it.
* @var callable
*/
private $transformer;
public function __construct(MongoCursor $cursor, callable $transformer)
{
$this->cursor = $cursor;
$this->transformer = $transformer;
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current()
{
return call_user_func($this->transformer, $this->cursor->current());
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next()
{
$this->cursor->next();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* 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.
*/
public function key()
{
return $this->cursor->key();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* 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.
*/
public function valid()
{
return $this->cursor->valid();
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
$this->cursor->rewind();
}
/**
* (PHP 5 &gt;= 5.1.0)<br/>
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
*/
public function count()
{
return $this->cursor->count($foundOnly = true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment