<?php

namespace Snaju\Inception\Util\Loaders;

/**
 * Class Stack
 * @package Snaju\Inception\Util\Loaders
 * Collects a list of objects, represented in a Last In, First Out method.
 */
class Stack
{

    protected array $data;

    public function __construct()
    {
        $this->data = [];
    }

    /**
     * Returns true if the stack is empty, false otherwise.
     * @return bool
     */
    public function isEmpty(): bool
    {
        if ($this->count() >= 1) {
            return false;
        }
        return true;
    }

    /**
     * Retrieve the total number of items in the stack.
     * @return int
     */
    public function count(): int
    {
        return count($this->data);
    }

    /**
     * Retrieve the list of objects and return as an array.
     * @return array
     */
    public function toArray(): array
    {
        return (array)$this->data;
    }

    /**
     * Adds an object to the stack.
     * @param $object
     */
    public function push($object): void
    {
        $this->data[] = $object;
    }

    /**
     * Retrieves the next item in the stack without removing it.
     */
    public function peek()
    {
        if (!$this->count() > 0) {
            return null;
        }
        return $this->data[$this->count() - 1];
    }

    public function pop()
    {
        if ($this->isEmpty()) {
            return null;
        }

        return array_pop($this->data);
    }

    /**
     * Removes all the items from the stack and resets it.
     */
    public function clear(): void
    {
        $this->data = [];
    }

    /**
     * Alias of clear method.
     */
    public function empty(): void
    {
        $this->clear();
    }

    public function contains($obj): bool
    {
        foreach ($this->data as $o) {
            if ($o == $obj) {
                return true;
            }
        }

        return false;
    }

}