<?php

namespace KupShop\KupShopBundle\Template;

class EntityWrapper extends BaseWrapper
{
    public function offsetExists($offset): bool
    {
        return parent::offsetExists($offset) || method_exists($this->object, $this->getterMethod($offset)) || method_exists($this, $this->getterMethod($offset));
    }

    protected function getterMethod($offset)
    {
        return 'get'.ucfirst($offset);
    }

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

            return $res;
        }

        $method = $this->getterMethod($offset);
        if (method_exists($this->object, $method)) {
            $res = call_user_func([$this->object, $method]);

            return $res;
        }

        return null;
    }

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

        if (method_exists($this->object, $name)) {
            return call_user_func_array([$this->object, $name], $arguments);
        }

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

    public function __debugInfo()
    {
        return (array) \Doctrine\Common\Util\Debug::export($this->object, 5);
    }
}
