<?php

namespace KupShop\KupShopBundle\Template;

class ArrayWrapper extends BaseWrapper implements \Countable, \IteratorAggregate
{
    public function getIterator(): \Traversable
    {
        return new \ArrayIterator($this->object);
    }

    public function count(): int
    {
        return count($this->object);
    }

    /**
     * Implements ArrayAccess interface.
     */
    public function offsetSet($offset, $value): void
    {
        $this->object[$offset] = $value;
    }

    public function offsetExists($offset): bool
    {
        return isset($this->object[$offset]) || parent::offsetExists($offset);
    }

    public function offsetUnset($offset): void
    {
        unset($this->object[$offset]);
    }

    public function offsetGet($offset): mixed
    {
        $method = $this->offsetMethod($offset);
        if (method_exists($this, $method)) {
            $res = call_user_func([$this, $method]);

            return $res;
        }

        if (isset($this->object[$offset])) {
            return $this->object[$offset];
        }

        return null;
    }

    public function __call($name, $arguments)
    {
        if (method_exists($this, $name)) {
            return call_user_func_array([$this, $name], $arguments);
        }

        throw new \Exception("Undefined method '{$name}' called on '{$this}'");
    }
}
