php-basics/src/DataStructures/Queue.php

74 lines
2.0 KiB
PHP
Raw Normal View History

<?php
/**
* Useful PHP Basics
* Copyright (C) 2023 Sebastian Meyer <sebastian.meyer@opencultureconsulting.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace OCC\Basics\DataStructures;
/**
2023-11-10 22:36:25 +01:00
* A type-sensitive, destructive First In, First Out Queue.
*
* @author Sebastian Meyer <sebastian.meyer@opencultureconsulting.com>
* @package opencultureconsulting/basics
* @implements \Countable
* @implements \Iterator
* @implements \Serializable
*/
2023-11-10 22:36:25 +01:00
class Queue extends AbstractList
{
/**
2023-11-10 22:36:25 +01:00
* Get the first item and remove it.
* @see Iterator::current
*
* @return mixed The first item or NULL if empty
*/
public function current(): mixed
{
return array_shift($this->items);
}
/**
2023-11-10 22:36:25 +01:00
* Get a single item without removing it.
*
2023-11-10 22:36:25 +01:00
* @param ?int $offset Optional offset to peek, defaults to first
*
2023-11-10 22:36:25 +01:00
* @return mixed The item or NULL if empty
*/
2023-11-10 22:36:25 +01:00
public function peek(?int $offset = null): mixed
{
2023-11-10 22:36:25 +01:00
if (is_null($offset)) {
return reset($this->items) ?? null;
}
$item = array_slice($this->items, $offset, 1);
return $item[0] ?? null;
}
/**
2023-11-10 22:36:25 +01:00
* Check if there is an item left on the queue.
* @see Iterator::valid
*
2023-11-10 22:36:25 +01:00
* @return bool Is there an item on the queue?
*/
2023-11-10 22:36:25 +01:00
public function valid(): bool
{
2023-11-10 22:36:25 +01:00
return (bool) $this->count();
}
}