EasyAuditBundle Custom Entity event resolver example
xiidea_easy_audit:
entity_class : MyProject\Bundle\MyBundle\Entity\AuditLog
entity_event_resolver : audit_trail.entity_event_resolver
services:
audit_trail.entity_event_resolver:
class: MyProject\Bundle\MyBundle\Resolver\EntityEventResolver
calls:
- [ setContainer,[ @service_container ] ]
<?php
namespace MyProject\Bundle\MyBundle\Resolver;
use Symfony\Component\EventDispatcher\Event;
use Xiidea\EasyAuditBundle\Events\DoctrineEntityEvent;
use Xiidea\EasyAuditBundle\Resolver\EntityEventResolver as BaseResolver;
class EntityEventResolver extends BaseResolver
{
/**
* @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);
return array(
'description' => $eventDescription,
'type' => $eventType,
'objectId' => $this->getProperty('id'),
'objectClass' => $reflectionClass->getName(),
'objectType' => $typeName,
'metaData' => $this->getAsSerializedString($changesMetaData)
);
}
/**
* @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 getDescriptionString(\ReflectionClass $reflectionClass, $typeName)
{
$property = $this->getBestCandidatePropertyForIdentify($reflectionClass);
$descriptionTemplate = '%s has been %s ';
if ($property) {
$descriptionTemplate .= sprintf(' with %s = "%s" ', $property, $this->getProperty($property));
}
return sprintf($descriptionTemplate,
$typeName,
$this->getEventShortName());
}
/**
* @param $changesMetaData
*
* @return null|string
*/
protected function getAsSerializedString($changesMetaData)
{
if (empty($changesMetaData)) {
return NULL;
} elseif (is_string($changesMetaData)) {
return $changesMetaData;
}
return serialize($changesMetaData);
}
}