134 lines
2.8 KiB
PHP
134 lines
2.8 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Created by PhpStorm.
|
|
* User: wpj
|
|
* Date: 5/11/17
|
|
* Time: 1:00 PM.
|
|
*/
|
|
|
|
namespace KupShop\KupShopBundle\Template;
|
|
|
|
class BaseWrapper implements \ArrayAccess
|
|
{
|
|
protected $object;
|
|
|
|
protected static $objectType;
|
|
|
|
public function setObject($object)
|
|
{
|
|
if ($object === null && isDevelopment()) {
|
|
throw new \Exception('Setuješ null do wrapperu, to není dobré, radši ten wrapper přeskoč, ne?');
|
|
}
|
|
|
|
if (static::$objectType && !$object instanceof static::$objectType) {
|
|
throw new \Exception('Incorrect type wrapped: '.get_class($object).' not instanceof '.static::$objectType);
|
|
}
|
|
|
|
$this->object = $object;
|
|
|
|
return $this;
|
|
}
|
|
|
|
public static function wrap($object)
|
|
{
|
|
if ($object instanceof BaseWrapper) {
|
|
return $object;
|
|
}
|
|
|
|
$wrapper = new static();
|
|
$wrapper->setObject($object);
|
|
|
|
return $wrapper;
|
|
}
|
|
|
|
public static function unwrap($object)
|
|
{
|
|
if ($object instanceof BaseWrapper) {
|
|
return $object->getObject();
|
|
}
|
|
|
|
return $object;
|
|
}
|
|
|
|
public function getObject()
|
|
{
|
|
return $this->object;
|
|
}
|
|
|
|
/**
|
|
* Implements ArrayAccess interface.
|
|
*/
|
|
public function offsetSet($offset, $value): void
|
|
{
|
|
$methodName = 'set'.ucfirst($offset);
|
|
if (method_exists($this->object, $methodName)) {
|
|
$this->object->{$methodName}($value);
|
|
} else {
|
|
$this->object->$offset = $value;
|
|
}
|
|
}
|
|
|
|
public function offsetExists($offset): bool
|
|
{
|
|
return method_exists($this, $this->offsetMethod($offset));
|
|
}
|
|
|
|
public function offsetUnset($offset): void
|
|
{
|
|
}
|
|
|
|
public function offsetMethod($offset)
|
|
{
|
|
return 'field_'.$offset;
|
|
}
|
|
|
|
public function offsetGet($offset): mixed
|
|
{
|
|
$method = $this->offsetMethod($offset);
|
|
if (method_exists($this, $method)) {
|
|
$res = call_user_func([$this, $method]);
|
|
|
|
return $res;
|
|
}
|
|
|
|
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}'");
|
|
}
|
|
|
|
public function __set($name, $value)
|
|
{
|
|
return $this->offsetSet($name, $value);
|
|
}
|
|
|
|
public function __get($name)
|
|
{
|
|
return $this->offsetGet($name);
|
|
}
|
|
|
|
public function __isset($name)
|
|
{
|
|
return $this->offsetExists($name);
|
|
}
|
|
|
|
public function __unset($name)
|
|
{
|
|
$this->offsetUnset($name);
|
|
|
|
return null;
|
|
}
|
|
|
|
public function __debugInfo()
|
|
{
|
|
return (array) \Doctrine\Common\Util\Debug::export($this->object, 5);
|
|
}
|
|
}
|