Utility classes

2019
// =============================================================================
// > SIMPLE FIFO/LIFO QUEUE
// =============================================================================
class Queue
{
    /**
     * The queue itself
     *
     * @var array
     */
    public $queue = [];

    /**
     * Create a new queue
     *
     * @param string $order FIFO or LIFO
     */
    public function __construct($order = "FIFO")
    {
        $this->order = $order;
    }

    /**
     * Add an item add the end of the queue
     *
     * @param  $item
     * @return void
     */
    public function insert($item)
    {
        $this->queue[] = $item;
    }

    /**
     * Get the next item
     *
     * @return mixed
     */
    public function extract()
    {
        return $this->order == "FIFO" ? array_pop($this->queue) : array_shift($this->queue);
    }

    /**
     * Number of elements in the queue
     *
     * @return int
     */
    public function count()
    {
        return count($this->queue);
    }
}


// =============================================================================
// > PRIORITY-BASED QUEUE
// =============================================================================
class PriorityQueue extends \SplPriorityQueue
{
    /**
     * Create a new queue
     *
     * @param string $order highest or lowest first
     */
    public function __construct($order = "highest")
    {
        $this->order = $order;
    }

    /**
     * Compare two items
     *
     * @param  $priority1
     * @param  $priority2
     * @return int
     */
    public function compare(mixed $priority1, mixed $priority2): int
    {
        return $this->order == "highest" ? $priority1 <=> $priority2 : $priority2 <=> $priority1;
    }

    /**
     * Get the whole queue as an array
     *
     * @return array
     */
    public function getArrayCopy()
    {
        $queue = clone $this;
        $array = [];
        while ($queue->count()) $array[] = $queue->extract();
        return $array;
    }
}