<?php


namespace CMSMSExt\core;


class stack
{
  /**
   * @var array
   */
  private array $stack;
  
  /**
   * Creates a new instance of the class.
   *
   * @return void
   */
  public function __construct()
  {
    $this->clear();
  }
  
  /**
   * Pushes an item onto the stack.
   *
   * @param mixed $item the item to be pushed onto the stack
   *
   * @return \CMSMSExt\core\stack
   * @throws \RuntimeException if the stack is empty
   */
  public function push($item) : stack
  {
    $this->stack[] = $item;
    
    return $this;
  }
  
  /**
   * Pops and returns the top element of the stack.
   *
   * @throws \RuntimeException If the stack is empty.
   * @return mixed The popped element.
   */
  public function pop()
  {
    if ($this->isEmpty())
    {
      throw new \RuntimeException('Stack is empty');
    }
    
    return \array_pop($this->stack);
  }
  
  /**
   * Retrieves the top element of the stack without removing it.
   *
   * @throws \RuntimeException if the stack is empty
   * @return mixed the top element of the stack
   */
  public function peek()
  {
    if ($this->isEmpty())
    {
      throw new \RuntimeException("Stack is empty");
    }
    
    return \end($this->stack);
  }
  
  /**
   * Check if the stack is empty.
   *
   * @return bool
   */
  public function isEmpty() : bool
  {
    return empty($this->stack);
  }
  
  /**
   * Retrieve the size of the stack.
   *
   * @return int The number of elements in the stack.
   */
  public function size() : int
  {
    return \count($this->stack);
  }
  
  /**
   * Clears the stack.
   *
   * @return \CMSMSExt\core\stack
   */
  public function clear() : stack
  {
    $this->stack = [];
    
    return $this;
  }
}


?>