Changed EntityConverter inner workings

In order to understand data types returned by DB engine better,
EntityConverter was changed to use getter/settter methods instead of raw
properties. That way, the methods inside entities can cast to desired
data types when accessed.
This commit is contained in:
Marcin Kurczewski 2014-09-14 16:42:06 +02:00
parent f0a077f2b4
commit cf0312ce43

View file

@ -3,22 +3,41 @@ namespace Szurubooru\Dao;
final class EntityConverter
{
protected $entityName;
private $entityName;
private $reflectionClass;
private $getterMethods = [];
private $setterMethods = [];
public function __construct($entityName)
{
$this->entityName = $entityName;
$this->reflectionClass = new \ReflectionClass($this->entityName);
$reflectionMethods = $this->reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($reflectionMethods as $reflectionMethod)
{
if (preg_match('/^(get|is)(\w+)$/', $reflectionMethod->getName(), $matches))
{
$columnName = lcfirst($matches[2]);
$this->getterMethods[] = [$reflectionMethod, $columnName];
}
else if (preg_matcH('/^set(\w+)$/', $reflectionMethod->getName(), $matches))
{
$columnName = lcfirst($matches[1]);
$this->setterMethods[] = [$reflectionMethod, $columnName];
}
}
}
public function toArray($entity)
public function toArray(\Szurubooru\Entities\Entity $entity)
{
$arrayEntity = [];
$reflectionClass = new \ReflectionClass($this->entityName);
$reflectionProperties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED);
foreach ($reflectionProperties as $reflectionProperty)
foreach ($this->getterMethods as $kv)
{
$reflectionProperty->setAccessible(true);
$arrayEntity[$reflectionProperty->getName()] = $reflectionProperty->getValue($entity);
list ($reflectionMethod, $columnName) = $kv;
$value = $reflectionMethod->invoke($entity);
$arrayEntity[$columnName] = $value;
}
return $arrayEntity;
}
@ -28,17 +47,14 @@ final class EntityConverter
if ($arrayEntity === null)
return null;
$entity = new $this->entityName;
$reflectionClass = new \ReflectionClass($this->entityName);
$args = [$arrayEntity['id']];
$entity = $this->reflectionClass->newInstanceArgs($args);
$reflectionProperties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED);
foreach ($reflectionProperties as $reflectionProperty)
foreach ($this->setterMethods as $kv)
{
if (isset($arrayEntity[$reflectionProperty->getName()]))
{
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($entity, $arrayEntity[$reflectionProperty->getName()]);
}
list ($reflectionMethod, $columnName) = $kv;
$value = $arrayEntity[$columnName];
$reflectionMethod->invoke($entity, $value);
}
return $entity;