Is there way to hydrate entity data like as after doctrine query
$entityData = $this->entityService->find($id)->getArrayResult();
and do it if you already have entity
$entity = $this->entityService->find($id)->getOneOrNullResult();
$entityData = $SomeDoctrineService->entityToArray($entity);
Solution
Firstly you can use \DoctrineModule\Stdlib\Hydrator\DoctrineObject
$hydrator = DoctrineObject(
$entityManager,
get_class($entity)
);
$entityData = $hydrator->extract($entity);
and secondly I've added custom hydrator trait EntityDataTrait
use Doctrine\ORM\Proxy\Proxy;
trait EntityDataTrait
{
/**
* @return array
*/
public function toArray()
{
$data = get_object_vars($this);
if ($this instanceof Proxy) {
$originClassName = get_parent_class($this);
foreach ($data as $key => $value) {
if (!property_exists($originClassName, $key)) {
unset ($data[$key]);
}
}
}
foreach ($data as $key => $value) {
if (method_exists($this, 'get' . ucfirst($key))) {
$data[$key] = $this->{'get' . ucfirst($key)}();
}
}
return $data;
}
}
for example
class MyEntity {
use EntityDataTrait;
/*properties and methods below*/
}
$entity = new MyEntity();
$entityData = $entity->toArray();