Location: PHPKode > scripts > ps queue > ps-queue/queue.class.php
<?php

/* Basic Queue Class
 * Asher Holley ( http://www.wolfoxinc.com/opensource/ )
 * Based on the Stack class ( http://www.phpclasses.org/browse/package/3442.html )
 * Released under the GNU General Public License ( http://www.opensource.org/licenses/gpl-license.html )
 * Copyright © 2006 Asher Holley
 *
 * This queue is based on the "ps stack" class available at PHP Classes
 *   that I have authored. */

class Queue {
	var $fifo;

	function Queue( $data = null ) {
		if ( is_array( $data ) ) {
			$this->fifo = $data;
		} else if ( is_a( $data, 'Queue' ) ) {
			$this->fifo = $data->fifo;
		} else if ( $data ) {
			$this->fifo = array();
			$this->fifo[] = $data;
		} else {
			$this->fifo = array();
		}

		return;
	}
	
	function top() {
		if ( !empty( $this->fifo ) ) {
			return $this->fifo[0];
		} else {
			return null;
		}
	}
	
	function &top_ref() {
		if ( !empty( $this->fifo ) ) {
			return $this->fifo[0];
		} else {
			return null;
		}
	}

	function push() {
		$args = func_get_args();
		$exec = 'array_push( $this->fifo';
		for ( $a = 0; $a < count( $args ); $a++ ) {
			$exec .= ', $args[' . $a . ']';
		}
		
		$exec .= ' );';
		return eval( $exec );
	}

	function pop() {
		return array_shift( $this->fifo );
	}
	
	function &pop_ref() {
		$e =& $this->top_ref();
		array_shift( $this->fifo );
		return $e;
	}
	
	function index( $i ) {
		if ( $i > count( $this->fifo ) - 1 || $i < 0 ) {
			return null;
		} else {
			return $this->fifo[ $i ];
		}
	}
	
	function &index_ref( $i ) {
		if ( $i > count( $this->fifo ) - 1 || $i < 0 ) {
			return null;
		} else {
			return $this->fifo[ $i ];
		}
	}
	
	function count() {
		return count( $this->fifo );
	}
	
	function is_empty() {
		return empty( $this->fifo );
	}

	function clear() {
		$this->fifo = array();
		return;
	}

	function get_queue() {
		return $this->fifo;
	}
	
	function exch() {
		$m0 = $this->pop_ref();
		$m1 = $this->pop_ref();
		$this->fifo[1] =& $m0;
		$this->fifo[0] =& $m1;
		return;
	}
	
	function dup() {
		array_unshift( $this->fifo, $this->top() );
		return;
	}
	
	function roll( $c ) {
		if ( is_int( $c ) ) {
			if ( abs( $c ) > ( $l = $this->count() ) ) {
				if ( $c < 0 ) {
					$c = ( abs( $c ) % $l ) * -1;
				} else {
					$c %= $l;
				}
			}
			
			if ( $c > 0 ) { // rotate right
				$this->fifo = array_merge( array_slice( $this->fifo, $c ),
										array_slice( $this->fifo, 0, $c ) );
			} else if ( $c < 0 ) { // rotate left
				$c = abs( $c );
				$this->fifo = array_merge( array_slice( $this->fifo, $l - $c ),
										array_slice( $this->fifo, 0, $l - $c ) );
			}
		}

		return;
	}
}

?>
Return current item: ps queue