66 lines
1.9 KiB
PHP
66 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\Entity;
|
|
|
|
class ObjectInstanciator {
|
|
|
|
protected array $objectCallbackDefinition;
|
|
|
|
public function instanciate(string $type, array $arguments) : object
|
|
{
|
|
if ( isset($this->objectCallbackDefinition[$type]) ) {
|
|
return $this->objectCallbackDefinition[$type](...$arguments);
|
|
}
|
|
elseif ( ($obj = new $type() ) instanceof EntityObjectInterface ) {
|
|
return $obj->load(...$arguments);
|
|
}
|
|
elseif ( ($obj = new $type() ) instanceof JsonUnserializable ) {
|
|
$obj->jsonUnserialize(json_decode($arguments[0], true));
|
|
|
|
return $obj;
|
|
}
|
|
else {
|
|
return new $type(...$arguments);
|
|
}
|
|
}
|
|
|
|
public function convert(object $obj)
|
|
{
|
|
if ( $obj instanceof EntityObjectInterface ) {
|
|
return $obj->save();
|
|
}
|
|
elseif ( $obj instanceof \JsonSerializable ) {
|
|
return json_encode($obj->jsonSerialize());
|
|
}
|
|
elseif ( $obj instanceof \Stringable ) {
|
|
return (string) $obj;
|
|
}
|
|
|
|
throw new \InvalidArgumentException("Object %s could not be converted as an acceptable format.");
|
|
}
|
|
|
|
public function enum(\UnitEnum $obj)
|
|
{
|
|
if (! $obj instanceof \BackedEnum) {
|
|
throw new \Ulmus\Exception\BackedEnumRequired("Unable to extract a UnitEnum value from this variable. You must define your enum as a BackedEnum instead of an UnitEnum.");
|
|
}
|
|
|
|
return $obj->value;
|
|
}
|
|
|
|
public function registerObject(string $type, Callable $callback) : void
|
|
{
|
|
$this->objectCallbackDefinition[$type] = $callback;
|
|
}
|
|
|
|
public function unregisterObject(string $type) : void
|
|
{
|
|
unset($this->objectCallbackDefinition[$type]);
|
|
}
|
|
|
|
public function isObjectRegistered(string $type) : bool
|
|
{
|
|
return isset($this->objectCallbackDefinition[$type]);
|
|
}
|
|
}
|