You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.1 KiB
73 lines
1.1 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Util;
|
|
|
|
/**
|
|
* Basic stack data structure.
|
|
*
|
|
* @author Adam Pippin <hello@adampippin.ca>
|
|
*/
|
|
class Stack
|
|
{
|
|
/**
|
|
* Stack data.
|
|
* @var mixed[]
|
|
*/
|
|
protected $stack;
|
|
|
|
/**
|
|
* Create a new stack.
|
|
*/
|
|
public function __construct()
|
|
{
|
|
$this->stack = [];
|
|
}
|
|
|
|
/**
|
|
* Count how many items this stack contains.
|
|
*
|
|
* @return int
|
|
*/
|
|
public function count(): int
|
|
{
|
|
return sizeof($this->stack);
|
|
}
|
|
|
|
/**
|
|
* Get all items in this stack.
|
|
*
|
|
* @return mixed[]
|
|
*/
|
|
public function get(): array
|
|
{
|
|
return $this->stack;
|
|
}
|
|
|
|
/**
|
|
* Pop an item off of this stack.
|
|
*
|
|
* @param int $offset offset from the end to pop if not the last element
|
|
* @return mixed
|
|
*/
|
|
public function pop(int $offset = 0)
|
|
{
|
|
if (sizeof($this->stack) < $offset + 1)
|
|
{
|
|
throw new \Exception('Stack underflow!');
|
|
}
|
|
return array_splice($this->stack, -1 * ($offset + 1), 1)[0];
|
|
}
|
|
|
|
/**
|
|
* Push an item onto the end of the stack.
|
|
*
|
|
* @param mixed $value
|
|
* @return void
|
|
*/
|
|
public function push($value): void
|
|
{
|
|
array_push($this->stack, $value);
|
|
}
|
|
}
|
|
|