Closed braianj closed 6 years ago
I'll share my entity resolver, if it help someone to work arround it
<?php
namespace AppBundle\Resolver;
use Symfony\Component\EventDispatcher\Event;
use Xiidea\EasyAuditBundle\Events\DoctrineEntityEvent;
use Xiidea\EasyAuditBundle\Resolver\EntityEventResolver as BaseResolver;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Psr\Log\LoggerInterface;
class EntityEventResolver extends BaseResolver
{
private $logger;
private $serializer;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @param Event|DoctrineEntityEvent $event
* @param $eventName
*
* @return array
*/
public function getEventLogInfo(Event $event, $eventName)
{
if (!$event instanceof DoctrineEntityEvent) {
return null;
}
$this->initialize($event, $eventName);
$changesMetaData = $this->getChangeSets($this->entity);
if ($this->isUpdateEvent() && $changesMetaData == NULL) {
return NULL;
}
$reflectionClass = $this->getReflectionClassFromObject($this->entity);
$typeName = $reflectionClass->getShortName();
//$eventType = $this->getEventType($typeName);
$eventDescription = $this->getDescriptionString($reflectionClass, $typeName);
$datos = [];
$ignorar = array('tu', 'ts', 'updated', 'created', 'transitions', '__initializer__', '__cloner__', '__isInitialized__', 'timezone', 'salt', 'password', 'nuevoPassword');
if (empty($changesMetaData)) {
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$this->serializer = new Serializer(array($normalizer), array($encoder));
$reflClass = new \ReflectionClass($this->entity);
$arrayDatos = [];
foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
if (
0 !== $reflMethod->getNumberOfRequiredParameters() ||
$reflMethod->isStatic() ||
$reflMethod->isConstructor() ||
$reflMethod->isDestructor()
) {
continue;
}
$name = $reflMethod->name;
$attributeName = null;
if (0 === strpos($name, 'get') || 0 === strpos($name, 'has')) {
// getters and hassers
$attributeName = substr($name, 3);
if (!$reflClass->hasProperty($attributeName)) {
$attributeName = lcfirst($attributeName);
}
} elseif (0 === strpos($name, 'is')) {
// issers
$attributeName = substr($name, 2);
if (!$reflClass->hasProperty($attributeName)) {
$attributeName = lcfirst($attributeName);
}
}
if (!is_null($attributeName) && !in_array($attributeName, $ignorar))
{
$val = $this->entity->$name();
$es_colecion = (is_array($val) || ($val instanceof \ArrayAccess && $val instanceof \Traversable));
if(!$es_colecion) {
$arrayDatos[$attributeName] = $this->extraerValor($val);
} else {
$arrayDatos[$attributeName] = [];
foreach ($val as $item) {
$arrayDatos[$attributeName][] = $this->extraerValor($item);
}
}
}
}
$datos = $this->serializer->serialize($arrayDatos,'json');
} elseif (is_string($changesMetaData)) {
// ONLY STRING
$datos = $changesMetaData;
} else {
foreach ($changesMetaData as $key => $value) {
if($value[0]!=$value[1] && !in_array($key, $ignorar)) {
if(gettype($value[0])== 'object') {
$entity = null;
foreach (explode('\\',get_class($value[0])) as $v) {
$entity = $v;
}
if((method_exists($value[0], 'getId'))) {
$value1 = $value[0]->getId();
$value2 = is_null($value[1]) ? null : $value[1]->getId();
$datos[$key] = array('entity' => $entity, 'id' => array($value1, $value2));
} else {
$value1 = $this->isDateOrNot($value[0]);
$value2 = $this->isDateOrNot($value[1]);
$datos[$key] = array($value1, $value2);
}
} else {
$datos[$key] = $value;
}
}
}
if (!empty($datos)) {
$datos = json_encode($datos);
}
}
$infoFinal = array(
'table' => $typeName,
'type' => $this->traducirType(),
'description' => $eventDescription,
);
if ($typeName!='Agentes') {
$infoFinal['tableId'] = $this->getProperty('id');
}
if (!empty($datos)) {
$infoFinal['data'] = $datos;
}
return $infoFinal;
}
protected function extraerValor ($value) {
$es_entidad = method_exists($value, 'getId');
if($es_entidad) {
return $value->getId();
} elseif ($value instanceof \Date) {
return $value->format("Y-m-d");
} elseif ($value instanceof \DateTime) {
return $value->format("Y-m-d H:i:s");
} elseif (gettype($value)== 'object') {
$value = json_encode($value, JSON_PRETTY_PRINT|JSON_ERROR_UNSUPPORTED_TYPE|JSON_PARTIAL_OUTPUT_ON_ERROR);
}
return $value;
}
/**
* @param DoctrineEntityEvent $event
* @param string $eventName
*/
private function initialize(DoctrineEntityEvent $event, $eventName)
{
$this->eventShortName = null;
$this->propertiesFound = array();
$this->eventName = $eventName;
$this->event = $event;
$this->entity = $event->getLifecycleEventArgs()->getEntity();
}
protected function isDateOrNot($var) {
if(is_a($var, 'DateTime')){
return print_r(($var->format('H:i:s')!='00:00:00') ? $var->format('c') : $var->format('Y-m-d'), true);
} else {
return print_r($var, true);
}
}
protected function getDescriptionString(\ReflectionClass $reflectionClass, $typeName)
{
$property = $this->getBestCandidatePropertyForIdentify($reflectionClass);
$descriptionTemplate = '%s %s';//'%s ha sido %s ';
if ($property) {
$descriptionTemplate .= sprintf('.%s = %s', $property, $this->getProperty($property));
}
return sprintf($descriptionTemplate,
$this->traducirType(),
$typeName);
}
/**
* @param $changesMetaData
*
* @return null|string
*/
protected function getAsSerializedString($changesMetaData)
{
if (empty($changesMetaData)) {
return NULL;
} elseif (is_string($changesMetaData)) {
return $changesMetaData;
}
return serialize($changesMetaData);
}
protected function traducirType() {
$accion = null;
switch ($this->getEventShortName()) {
case 'created':
$accion = 'Crear';
break;
case 'updated':
$accion = 'Actualizar';
break;
case 'deleted':
$accion = 'Eliminar';
break;
default:
$accion = 'Acción';
break;
}
return $accion;
}
}
I'm trying to save the user / roles but whe I do that, it save every for and then every user of those roles, and the every role and so on. If I insert a user inside another entity, it save all the object of user, and then roles, and then user and so on.
This is my event resolver
Posible duplicate with #24