<?php 
/**
 * This class provides access to the Counters collection. The counters collection 
 * keeps track of counters for various sequences. These counters can be used as unique 
 * identifiers for items in these sequences.
 * 
 * For example, a sequence of items in an entity collection could have
 * the following id's:
 * 
 *  - entity/text/domain/type/0
 *  - entity/text/domain/type/1
 *  - entity/text/domain/type/2
 *  - entity/text/domain/type/3
 * 
 * In this example, the sequence name is 'entity/text/domain/type/', and the 
 * incremental ID's are the identifiers generated by a counter.
 * 
 * @author carlosm
 */
class Counter extends Moloquent {
	protected static $collectionName = 'counters';
	protected $collection = 'counters';

	/**
	 * Returns the next ID for the given sequence.
	 * 
	 * @param $sequence Name of the desired sequence.
	 * @return The next numeric ID for the desired sequence.
	 */
	public static function getNextId($sequence) {
		$seq = DB::getCollection(static::$collectionName)->findAndModify(
				array('_id' => $sequence),
				array('$inc' => array('seq' => 1)),
				null,
				array('new' => true, 'upsert' => true)
		);
		return $seq['seq'];
	}
}
